Lua计算表格包含的字段数量

Lua中计算表格包含的字段数量,也可以理解为计算表的长度,很多人平时都习惯用#,但是#table.nums()还是有区别的。
Lua table"#" 操作只对依次排序的数值下标数组有效,table.nums() 则计算 table 中所有不为 nil 的值的个数。

1
2
3
4
5
6
7
8
9
10
11
-- @function [parent=#table] nums
-- @param table t 要检查的表格
-- @return integer#integer

function table.nums(t)
local count = 0
for k, v in pairs(t) do
count = count + 1
end
return count
end