以确定最有效的方式,如果一个Lua表是空的(不包含任何条目)?
题
什么,以确定是否一个表是空的最有效的方式(即,目前既不包含阵列式的值也不字典式值)?
目前,我使用的next()
:
if not next(myTable) then
-- Table is empty
end
是否有一个更有效的方式?
注意:#
操作不足以在这里,因为它仅在该表中的阵列式的值进行操作 - 从而#{test=2}
是从#{}
难以区分,因为两个回0。还请注意,如果检查表变量是nil
不足以作为我不找零的值,但0的条目(即{}
)。而表
解决方案
您的代码是有效的,但错误的。 (考虑{[false]=0}
)正确的代码
if next(myTable) == nil then
-- myTable is empty
end
有关最大效率你要结合next
到本地变量,例如
...
local next = next
...
... if next(...) ...
其他提示
一种可能性是通过使用元表“newindex”键计数元件的数量,。当分配的东西不nil
,增加计数器(计数器可以住在元表为好)和分配nil
时,递减计数器。
为空表测试将是用0至测试计数器。
下面是一个指针,指向元表文档
我不喜欢你的解决方案,虽然,我真的不能想当然地认为我的解决办法是更快的整体。
这也可能是你想要的东西:
function table.empty (self)
for _, _ in pairs(self) do
return false
end
return true
end
a = { }
print(table.empty(a))
a["hi"] = 2
print(table.empty(a))
a["hi"] = nil
print(table.empty(a))
输出:
true
false
true
我知道这是老了,我就可以在某种程度上误解你,但你只是想表是空的,也就是说,除非你只是检查,如果是,你不真的想要或需要它是空的,你可以通过简单地重新创建它,除非我错了清除。这可以用下面的语法来进行。
yourtablename = {} -- this seems to work for me when I need to clear a table.
更好地避免__eq的评价如果过载。
if rawequal(next(myTable), nil) then
-- myTable is empty
end
或
if type(next(myTable)) == "nil" then
-- myTable is empty
end
尝试蛇,对我的工作。
serpent = require 'serpent'
function vtext(value)
return serpent.block(value, {comment=false})
end
myTable = {}
if type(myTable) == 'table' and vtext(myTable) == '{}' then
-- myTable is empty
end
这个怎么样?
if endmyTable[1] == nil then
-- myTable is empty
end
尝试使用#
。它将返回一个表中的所有实例。如果不存在表中的情况下,则它返回0
if #myTable==0 then
print('There is no instance in this table')
end
不隶属于 StackOverflow