I want to make a table with specific names as keys and specific functions as values. The key names represent commands that a user enters and if a key by that name exists, then the program should execute the code stored in that keys value.
So for example, we make a table with keys and functions inside the key value:
local t = {
["exit"] = quitGame,
...,
...
}
and we also have a function for example:
function quitGame()
print("bye bye")
os.exit()
end
so now we do:
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
I hope you understand what I'm trying to do.
You have a table keyed by value. There's no need to loop to find the key you want. Just look it up directly. Then just call the value you get back.
local fun = t[userInput]
if fun then
fun()
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With