确定Lua表是否为空(不包含任何条目)的最有效方法?

Most efficient way to determine if a Lua table is empty (contains no entries)?

确定表是否为空(即,当前既不包含数组样式值也不包含dict样式值)的最有效方法是什么?

当前,我正在使用next()

1
2
3
if not next(myTable) then
    -- Table is empty
end

有没有更有效的方法?

注意:#运算符在这里不能满足要求,因为它仅对表中的数组样式值进行运算-因此#{test=2}#{}是无法区分的,因为它们都返回0。还要注意,检查表变量是否为 nil不足,因为我不是在寻找nil值,而是具有0项的表(即{})。


您的代码有效,但错误。 (考虑{[false]=0}。)正确的代码是

1
2
3
if next(myTable) == nil then
   -- myTable is empty
end

为了获得最高效率,您需要将next绑定到本地变量,例如,

1
2
3
4
...
local next = next
...
... if next(...) ...


一种可能性是通过使用元表" newindex"键来计算元素的数量。分配非nil的内容时,增加计数器(计数器也可以存在于元表中),而分配nil时,则减少计数器。

测试空表将测试计数器为0。

这是指向元文档的指针

我确实喜欢您的解决方案,但老实说,我不能认为我的解决方案总体上更快。


这可能是您想要的:

1
2
3
4
5
6
7
8
9
10
11
12
13
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))

输出:

1
2
3
true
false
true


这个怎么样 ?

1
2
3
if endmyTable[1] == nil then
  -- myTable is empty
end


试蛇,为我工作

1
2
3
4
5
6
7
8
9
10
11
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

如果过载,最好避免对__eq的求值。

1
2
3
if rawequal(next(myTable), nil) then
   -- myTable is empty
end

要么

1
2
3
if type(next(myTable)) =="nil" then
   -- myTable is empty
end


我知道这已经很老了,我可能会以某种方式误解您,但是您只是希望表为空,也就是说,除非您只是检查表是否为空,并且实际上并不需要或不需要它为空,您可以通过简单地重新创建它来清除它,除非我弄错了。这可以通过以下语法完成。

1
yourtablename = {} -- this seems to work for me when I need to clear a table.


尝试使用#。它返回表中的所有实例。如果表中没有实例,则它返回0

1
2
3
if #myTable==0 then
print('There is no instance in this table')
end