因此,如果我有一张颜色表:
colour["red"] = 1
colour["blue"] = 4
colour["purple"] = 5
我想把红色加到蓝色,我可以很容易地得到红色和蓝色的数值,但是用值 5,我可以让它在不扫描整个表的情况下返回“紫色”吗?
如果颜色编号是唯一的,您将需要一个包含哈希和数组部分的表。例如:
colour["purple"] = 5
colour[5] = "purple"
您可以创建一个有助于填充表格的小辅助函数,例如:
function addColour(coltab, str, val)
coltab[str] = val
coltab[val] = str
end
@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