Brekkjern, on 09 August 2013 - 08:02 PM, said:
How would you pass a function with arguments from such a table? Would that even work?
It depends. What exactly are you asking?
If you're asking "Can you pass arguments to functions stored in tables like that?", then the answer is "Yes."
This code:
function hello(name) -- This function takes a single argument
print("Hello, " .. name .. "!") -- and uses the argument in its body.
end
function goodbye(name) -- Same here.
print("Goodbye, " .. name .. ".")
end
local lookupTable = {
[1] = hello,
[2] = goodbye
}
is equivalent to this code:
local lookupTable = {
[1] = function(name) -- Exactly the same as above, except we are directly storing the function in a table
print("Hello, " .. name .. "!") -- instead of storing it in a variable then putting the variable in the table.
end,
[2] = function(name)
print("Goodbye, " .. name .. ".")
end
}
You would use either like this:
lookupTable[1]("Your Name") -- Call functions stored in tables exactly the same as a function normally stored in a variable.
lookupTable[2]("Your Name")
You could also do this:
local hello = lookupTable[1] -- Take the function stored in the table and put it into a variable.
local goodbye = lookupTable[2]
hello("Your Name") -- Then call the variable like normal.
goodbye("Your Name")
Functions are first-class values in Lua. In other words, whatever you can do to another type of value, you can (theoretically) do to a function. (I won't get into how to make that happen. It won't work unless you set it up yourself.)
So, you can store functions in a table and call them with or without any arguments, just like you would store them in a variable (the function name is actually a variable) and call them normally.
I hope that makes some sense. I'm kinda' tired right now. ;-)