I was able to store functions into a table. But now I have no idea of how to invoke them. The final table will have about 100 calls, so if possible, I'd like to invoke them as if in a foreach loop. Thanks!
Here is how the table was defined:
game_level_hints = game_level_hints or {}
game_level_hints.levels = {}
game_level_hints.levels["level0"] = function()
return
{
[on_scene("scene0")] =
{
talk("hint0"),
talk("hint1"),
talk("hint2")
},
[on_scene("scene1")] =
{
talk("hint0"),
talk("hint1"),
talk("hint2")
}
}
end
Aaand the function definitions:
function on_scene(sceneId)
-- some code
return sceneId
end
function talk(areaId)
-- some code
return areaId
end
EDIT:
I modified the functions so they'll have a little more context. Basically, they return strings now. And what I was hoping to happen is that at then end of invoking the functions, I'll have a table (ideally the levels table) containing all these strings.
Using what you guys answered and commented, I was able to come up with the following code as a solution:
Now,
asd
contains the area strings I need. Although ideally, I intended to be able to access the data like:accessing it like:
to retrieve the area data would suffice. I'll just have to work around the keys.
Thanks, guys.
It's not really clear what you're trying to do. Inside your anonymous function, you're returning a table that uses
on_scene
's return value as keys. But youron_scene
doesn't return anything. Same thing fortalk
.I'm going to assume that you wanted
on_scene
andtalk
to get called when invoking each levels in yourgame_level_hints
table.If so, this is how you can do it:
Short answer: to call a function (reference) stored in an array, you just add
(parameters)
, as you'd normally do:In fact, you can simplify this to
Long answer: You don't describe what your expected results are, but what you wrote is likely not to do what you expect it to do. Take this fragment:
[This paragraph no longer applies after the question has been updated]
You referenceon_scene
andtalk
functions, but you don't "store" those functions in the table (since you explicitly referenced them in your question, I presume the question is about these functions). You actually call these functions and store the values they return (they both returnnil
), so when this fragment is executed, you get "table index is nil" error as you are trying to storenil
usingnil
as the index.If you want to call the function you stored in
game_level_hints.levels["level0"]
, you just dogame_level_hints.levels["level0"]()