表内 Lua 表比较
所以我有一个表,其中包含对其他表的引用,例如:
local a = newObject()
a.collection = {}
for i = 1, 100 do
local b = newObject()
a[#a + 1] = b
end
现在,如果我想查看某个特定对象是否在“a”内,我必须使用像这样的对:
local z = a.collection[ 99 ]
for i,j in pairs( a.collection ) do
if j == z then
return true
end
end
z 对象位于第 99 个位置,我必须等待成对地迭代其他 98 个对象。这种设置使我的程序爬行。有没有一种方法可以制作某种不是字符串的键,也不是单行的表与表比较?例如:
if a.collection[{z}] then return true end
提前致谢!
So I have a table that holds references to other tables like:
local a = newObject()
a.collection = {}
for i = 1, 100 do
local b = newObject()
a[#a + 1] = b
end
Now if I want to see if a particular object is within "a" I have to use pairs like so:
local z = a.collection[ 99 ]
for i,j in pairs( a.collection ) do
if j == z then
return true
end
end
The z object is in the 99th spot and I would have to wait for pairs to iterate all the way throughout the other 98 objects. This set up is making my program crawl. Is there a way to make some sort of key that isn't a string or a table to table comparison that is a one liner? Like:
if a.collection[{z}] then return true end
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么将对象存储在表的值槽而不是键槽中?
查看特定对象是否在“a”内
如果您需要对集合进行整数索引访问,
请以两种方式存储它:
Why are you storing the object in the value slot and not the key slot of the table?
to see if a particular object is within "a"
If you need integer indexed access to the collection, store it both ways:
Finding:
不知道它是否更快,但这也许有帮助:
填充:
查找:
如果这不是您想要做的,您可以将整个数组分成更小的存储桶,并使用哈希来跟踪哪个对象属于哪个存储桶。
Don't know if it's faster or not, but maybe this helps:
Filling:
Finding:
If that's not what you wanted to do you can break your whole array into smaller buckets and use a hash to keep track which object belongs to which bucket.
您可能需要考虑从使用pairs()切换到使用常规for循环并为表建立索引,pairs()在较大的表集合上似乎更慢。
我比较了使用pair()和表索引迭代100万个表的集合的速度,并且索引每次都快一点。尝试使用 os.clock() 来分析您的代码。
除了使用某种哈希函数在 a.collection 表中设置唯一索引之外,我真的想不出更快的解决方案。然而,这样做会使获取特定的表成为一项不平凡的任务(您不仅能够执行 a.collection[99],您还必须迭代直到找到您想要的一个。但是然后您可以通过执行类似 a.collection[hashFunc(z)] ~= nil... 的操作来轻松测试表是否在 a.collection 中
you might want to consider switching from using pairs() to using a regular for loop and indexing the table, pairs() seems to be slower on larger collections of tables.
i compared the speed of iterating through a collection of 1 million tables using both pairs() and table indexing, and the indexing was a little bit faster every time. try it yourself using os.clock() to profile your code.
i can't really think of a faster way of your solution other than using some kind of hashing function to set unique indexes into the a.collection table. however, doing this would make getting a specific table out a non-trivial task (you wouldn't just be able to do a.collection[99], you'd have to iterate through until you found one you wanted. but then you could easily test if the table was in a.collection by doing something like a.collection[hashFunc(z)] ~= nil...)