calling functions from a table

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
TheFriendlyFoe
Prole
Posts: 7
Joined: Fri Mar 18, 2022 11:42 am

calling functions from a table

Post 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.
User avatar
pgimeno
Party member
Posts: 3656
Joined: Sun Oct 18, 2015 2:58 pm

Re: calling functions from a table

Post 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
User avatar
darkfrei
Party member
Posts: 1197
Joined: Sat Feb 08, 2020 11:09 pm

Re: calling functions from a table

Post 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
:awesome: in Lua we Löve
:awesome: Platformer Guide
:awesome: freebies
TheFriendlyFoe
Prole
Posts: 7
Joined: Fri Mar 18, 2022 11:42 am

Re: calling functions from a table

Post by TheFriendlyFoe »

Thanks pgimeno, that works perfectly!
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 3 guests