Page 1 of 1

calling functions from a table

Posted: Mon Apr 25, 2022 3:31 pm
by TheFriendlyFoe
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.

Code: Select all

--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
Thats what I have so far, but it doesn't work.

Re: calling functions from a table

Posted: Mon Apr 25, 2022 8:21 pm
by pgimeno
Don't call the function to invoke the same as the table, because you're overwriting the function with the table.

You can do this:

Code: Select all

buttonAction = {}

buttonAction[1] = function ()
  -- perform button 1's actions
end

buttonAction[2] = function ()
  -- perform button 2's actions
end
Then you can call them like this:

Code: Select all

buttonAction[num]()
Or you can make a function if you wish, but don't call it buttonAction because that's the name of the table! Also, you don't need a loop:

Code: Select all

function performButtonAction(bn)
  buttonAction[bn]()
end

Re: calling functions from a table

Posted: Tue Apr 26, 2022 7:16 am
by darkfrei
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.).

Code: Select all

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

Re: calling functions from a table

Posted: Tue Apr 26, 2022 3:39 pm
by TheFriendlyFoe
Thanks pgimeno, that works perfectly!