问题
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?
回答1:
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
回答2:
@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
来源:https://stackoverflow.com/questions/16776694/lua-search-tables-using-index-or-value