我想创建一个具有特定名称作为键和特定函数作为值的表. 键名表示用户输入的命令,如果存在该名称的键,则程序应执行存储在该键值中的代码. 因此,例如,我们在键值中创建一个包含键
键名表示用户输入的命令,如果存在该名称的键,则程序应执行存储在该键值中的代码.
因此,例如,我们在键值中创建一个包含键和函数的表:
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
