使用 load() 时将字符串用作函数。它returns"attempt to call a nil value"

When using load() to use a string as a function. It returns "attempt to call a nil value"

所以我正在开发一款游戏,我想使用一个可以作为函数调用的字符串,这样我就可以同时快速调用多个函数。我有一个我正在努力工作的例子:

function state_machine_1()
    print("Hello world")
end

function state_machine_2()
    print("Goodbye world")
end

local func="state_machine_".."1"
load(func)()

func="state_machine_".."2"
load(func)()

当我 运行 lua 演示站点中的代码时,我现在得到完全相同的错误,即“尝试调用 nil 值”。我试过查找它,但 load() 对于搜索引擎来说太模糊了,即使有上下文也无法知道。有什么我可以改变的想法吗?

您可能希望在 table 中定义函数并使用 table 顶部查找您想要的函数,如下所示:

local funcs = {}

function funcs.state_machine_1()
  print("Hello World")
end

funcs.state_machine_2 = function() -- another to define the function in a table
  print("Goodbye World")
end

local func = "state_machine_" .. "1"

funcs[ func ]()

func = "state_machine_" .. "2"

funcs[ func ]()

加载函数采用包含实际 Lua 代码的字符串:

nil错误是因为编译代码失败

您可以添加断言来捕获编译错误

assert(load(func))()

它失败的原因是 func 应该以 () 结束,它是一个函数调用。

local func = "state_machine_" .. "1" .. "()"

assert(load(func))()