In my game I have a menu with a lot of buttons, each with a number. That number is associated with a function to call when the button is pressed. Instead of having a super long "if-else-chain" to call the right function, I wanted to make a for loop. I can't figure out how to call a function with i as the number to call from.
--called when a button is pressed, bn is the button number
function buttonAction(bn)
for i=1, #buttonAction do
if bn == i then
buttonAction[i]()
end
end
end
buttonAction = {}
function buttonAction[1]()
--preform the buttons actions
end
--I have more buttons than this
Also it's possible to keep the table for the handler of function and give it's name, position, size, flags (hovered; pressed but not released; hidden; disabled; etc.).
handlers ={
{name = "sin", func = math.sin},
{name = "cos", func = math.cos},
}
function performHandler (name)
for i, handler in ipairs (handlers) do
if handler.name = name then
return handler.func (math.pi/2)
-- return handler.func -- return the function, but not perform it
end
end
end
print(performHandler ("sin")) -- sin pi/2
print(performHandler ("cos")) -- cos pi/2