Lua - Execute a Function Stored in a Table

一世执手 提交于 2019-12-05 08:04:41

Short answer: to call a function (reference) stored in an array, you just add (parameters), as you'd normally do:

local function func(a,b,c) return a,b,c end
local a = {myfunc = func}
print(a.myfunc(3,4,5)) -- prints 3,4,5

In fact, you can simplify this to

local a = {myfunc = function(a,b,c) return a,b,c end}
print(a.myfunc(3,4,5)) -- prints 3,4,5

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:

game_level_hints.levels["level0"] = function()
    return
    {
        [on_scene("scene0")] =
        {
            talk("hint0"),
        }
    }
end

[This paragraph no longer applies after the question has been updated] You reference on_scene and talk 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 return nil), so when this fragment is executed, you get "table index is nil" error as you are trying to store nil using nil as the index.

If you want to call the function you stored in game_level_hints.levels["level0"], you just do game_level_hints.levels["level0"]()

Using what you guys answered and commented, I was able to come up with the following code as a solution:

asd = game_level_hints.levels["level0"]()

Now, asd contains the area strings I need. Although ideally, I intended to be able to access the data like:

asd[1][1]

accessing it like:

asd["scene0"][1]

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 your on_scene doesn't return anything. Same thing for talk.

I'm going to assume that you wanted on_scene and talk to get called when invoking each levels in your game_level_hints table.

If so, this is how you can do it:

local maxlevel = 99
for i = 0, maxlevel do
  game_level_hints.levels["level" .. i] = function()
    on_scene("scene" .. i)
    talk("hint" .. i)
  end
end
-- ...
for levelname, levelfunc in pairs(game_level_hints.levels) do
  levelfunc()
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!