Lua does something stored in a table, key value

Lua is starting here, trying to learn how to do ... This is my 4th day with Lua, so please come with me.

I want to create a table with specific names as keys and specific functions as values. Key names are commands that the user enters, and if a key by that name exists, the program must execute the code stored in this key value.

So, for example, we create 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.

+5
source share
1 answer

You have a table with a key by value. There is no need for a loop to find the key you want. Just look straight. Then just call the resulting value.

 local fun = t[userInput] if fun then fun() end 
+3
source

Source: https://habr.com/ru/post/1209783/


All Articles