使用索引或值的Lua搜索表 [英] Lua search tables using index or value
本文介绍了使用索引或值的Lua搜索表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以,如果我有一张颜色表:
So if I have a table of colours:
colour["red"] = 1
colour["blue"] = 4
colour["purple"] = 5
我想将红色添加到蓝色,我可以很容易地获得红色和蓝色的数字值,但是如果值为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?
推荐答案
如果色号是唯一的,则需要一个同时包含哈希和数组部分的表.例如:
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
这篇关于使用索引或值的Lua搜索表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文