Search code examples
lualua-table

Lua execute something stored in tables key value


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.


Solution

  • 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