Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua execute something stored in tables key value

Tags:

lua

lua-table

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.

like image 934
thee Avatar asked Oct 19 '22 20:10

thee


1 Answers

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
like image 122
Etan Reisner Avatar answered Dec 06 '22 03:12

Etan Reisner