Lua执行存储在表键值中的内容

the*_*hee 5 lua lua-table

我想创建一个具有特定名称作为键和特定函数作为值的表.键名表示用户输入的命令,如果存在该名称的键,则程序应执行存储在该键值中的代码.

因此,例如,我们在键值中创建一个包含键和函数的表:

local t = {
    ["exit"] = quitGame,
    ...,
    ...
}
Run Code Online (Sandbox Code Playgroud)

我们还有一个功能,例如:

function quitGame()
  print("bye bye")
  os.exit()
end
Run Code Online (Sandbox Code Playgroud)

所以现在我们做:

userInput = io.read()

for i,v in pairs(t) do
    if userInput == i then
        --now here, how do I actually run the code that is stored in that key value (v)?
    end
end
Run Code Online (Sandbox Code Playgroud)

我希望你明白我在做什么.

Eta*_*ner 3

您有一个按值键控的表。无需循环查找所需的密钥。直接查一下就可以了。然后只需调用您返回的值即可。

local fun = t[userInput]
if fun then
    fun()
end
Run Code Online (Sandbox Code Playgroud)