user2425595
user2425595

Reputation: 41

Lua search tables using index or value

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?

Upvotes: 4

Views: 1284

Answers (2)

catwell
catwell

Reputation: 7020

@W.B.'s answer is good, if you want something more magic you can use this variation using the __newindex metamethod:

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

Upvotes: 5

W.B.
W.B.

Reputation: 5525

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

Upvotes: 7

Related Questions