Lua search tables using index or value

安稳与你 提交于 2019-12-10 15:55:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!