【问题标题】:Lua execute something stored in tables key valueLua 执行存储在表键值中的内容
【发布时间】:2018-06-20 18:15:14
【问题描述】:

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

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

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

我希望你明白我想要做什么。

【问题讨论】:

    标签: lua lua-table


    【解决方案1】:

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

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

    【讨论】:

    • 这正是我所需要的。谢谢!还有一个问题,当调用表中的函数时,如何阻止程序退出?例如,如果我希望函数打印出一些内容,然后再次等待下一个用户输入?
    • @thee 最终取决于您的环境,但在独立的(例如)循环中,while true do userInput=io.read() ... done 将起作用。
    猜你喜欢
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 2011-03-08
    • 2020-06-09
    • 2015-03-06
    • 2013-07-08
    • 2018-11-20
    相关资源
    最近更新 更多