Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua search tables using index or value

Tags:

lua

lua-table

So if I have a table of colours:

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

and I want to add red to blue, I can easily get the number values of red and blue, but then with the value 5, can I get it to return "purple" without scanning the whole table?

like image 745
user2425595 Avatar asked Dec 15 '22 10:12

user2425595


1 Answers

You would need a table with both hash and array part, if colour numbers are unique. For example:

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

You can create a little helper function that would facilitate populating the table, such as:

function addColour(coltab, str, val)
    coltab[str] = val
    coltab[val] = str
end
like image 136
W.B. Avatar answered Jan 05 '23 21:01

W.B.