我想制作一个以特定名称作为键和特定功能作为值的表。
键名代表用户输入的命令,如果该键名存在,则程序应执行存储在该键值中的代码。
例如,我们在键值中创建一个包含键和函数的表:
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
我希望你明白我在做什么。
最佳答案
您有一个按值键控的表。无需循环查找所需的 key 。直接查一下就行了。然后只需调用您返回的值。
local fun = t[userInput]
if fun then
fun()
end
关于Lua 执行存储在表键值中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27624548/