How can I toggle the color of a SODA button permanent if touched
This does not work:
local function onPress(sender) local buttonStyle = { shape = {fill = color(39, 255, 0, 200)}, text = {fill = "white", fontSize = 1.5}, highlight = { shape = {fill = "white", stroke = color(255, 180, 0)}, text = {fill = color(255, 180, 0), fontSize = 1.5} } } sender.title = 'X' sender.style = buttonStyle end
One step further:
The following code changes the color, but not only of the touched button but also of all others:
``
local function onPress(sender)
print(sender.title)
sender.title = ‘X’
sender.style.shape = {fill = color(39, 255, 0, 200)}
end
local function draw(x,y)
Soda.Button{ --parent = Tiles.window,
x=x*(w+5)+55,y=y*(w+5)+45,w=w,h=w,title=x…‘/’…y,callback = onPress}
end
function Tiles:touched(touch)
– Codea does not automatically call this method
end
function Tiles:drawBoard()
for i =0,11 do
for j = 0,8 do
draw(i,j)
end
end
end
``
Yes, what’s happening in your above code is that because in Lua, tables are objects, and therefore have reference (not value) semantics, so if you modify one element in the style
table, you modify every instance of the default style, which isn’t what you want. TBH the style system could be substantially simplified. The idea though is that it is meant to cascade through a series of style tables held in the objects styleList
. If you wanted to toggle one button a certain colour you could do this by setting and un-setting the last item in that list (in the case of a button, the third index). Probably safest to set the entire table. The table only has to specify the fields you want to override tho. E.g., to toggle just the fill colour and text colour, you could do this:
--upvalues that will be captured by button callback closure
local magentaButton = {
shape = { fill = color(255, 0, 133, 255) },
text = { fill = color(255) }
}
local toggle = false
Soda.Button{
title = "Tap me",
h = 60,
callback = function(this)
toggle = not toggle
this.styleList[3] = toggle and magentaButton or nil
end
}
You don’t have to use closures, you could use named functions, as you do in your code above.
Great! It works - thank a lot for the super quick response … and for this great framework!