Most efficient way to determine if a Lua table is empty (contains no entries)?
确定表是否为空(即,当前既不包含数组样式值也不包含dict样式值)的最有效方法是什么?
当前,我正在使用
1 2 3 | if not next(myTable) then -- Table is empty end |
有没有更有效的方法?
注意:
您的代码有效,但错误。 (考虑
1 2 3 | if next(myTable) == nil then -- myTable is empty end |
为了获得最高效率,您需要将
1 2 3 4 | ... local next = next ... ... if next(...) ... |
一种可能性是通过使用元表" newindex"键来计算元素的数量。分配非
测试空表将测试计数器为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. |
尝试使用
1 2 3 | if #myTable==0 then print('There is no instance in this table') end |