Lua lookup tables using an index or value

So, if I have a color table:

colour["red"] = 1 colour["blue"] = 4 colour["purple"] = 5 

and I want to add red to blue, I can easily get the numerical values โ€‹โ€‹of red and blue, but then with a value of 5, can I make it return โ€œpurpleโ€ without looking at the whole table?

+4
source share
2 answers

You will need a table with hash and array elements if the color numbers are unique. For instance:

 colour["purple"] = 5 colour[5] = "purple" 

You can create a small helper function that makes it easier to populate the table, for example:

 function addColour(coltab, str, val) coltab[str] = val coltab[val] = str end 
+7
source

@WB's answer is good, if you want something more magic, you can use this change using the __newindex __newindex :

 local colour = setmetatable({}, { __newindex = function(self,k,v) rawset(self,k,v) rawset(self,v,k) end }) colour["red"] = 1 colour["blue"] = 4 colour["purple"] = 5 print(colour["purple"]) -- 5 print(colour[4]) -- blue 
+5
source

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


All Articles