Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Lua执行存储在表中的某个键值_Lua_Lua Table - Fatal编程技术网

Lua执行存储在表中的某个键值

Lua执行存储在表中的某个键值,lua,lua-table,Lua,Lua Table,我想创建一个表,用特定的名称作为键,用特定的函数作为值。 键名表示用户输入的命令,如果存在同名键,则程序应执行该键值中存储的代码 例如,我们制作一个表,其中包含键值内的键和函数: local t = { ["exit"] = quitGame, ..., ... } 我们还有一个函数,例如: function quitGame() print("bye bye") os.exit() end 所以现在我们做: userInput = io.read() fo

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

例如,我们制作一个表,其中包含键值内的键和函数:

local t = {
    ["exit"] = quitGame,
    ...,
    ...
}
我们还有一个函数,例如:

function quitGame()
  print("bye bye")
  os.exit()
end
所以现在我们做:

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

我希望您理解我的意图。

您有一个按值键入的表。无需循环查找所需的密钥。直接查一下。然后,只需调用您得到的值

local fun = t[userInput]
if fun then
    fun()
end

这正是我需要的。谢谢还有一个问题,当调用表中的函数时,如何阻止程序退出?例如,如果我希望函数打印出一些内容,然后再次等待下一个用户输入?@这最终取决于您的环境,但在一个独立的(例如)循环中,如
,而true do userInput=io.read()。。。完成
将起作用。