如何获取Lua表中的条目数? [英] How to get number of entries in a Lua table?
问题描述
听起来像是让我为您代劳",但是我却找不到答案. Lua #
运算符仅对带有整数键的条目进行计数,table.getn
也是如此:
Sounds like a "let me google it for you" question, but somehow I can't find an answer. The Lua #
operator only counts entries with integer keys, and so does table.getn
:
tbl = {}
tbl["test"] = 47
tbl[1] = 48
print(#tbl, table.getn(tbl)) -- prints "1 1"
count = 0
for _ in pairs(tbl) do count = count + 1 end
print(count) -- prints "2"
如何获得 all 个条目的数量而不计数?
How do I get the number of all entries without counting them?
推荐答案
您已经有了问题的解决方法–唯一的方法是使用pairs(..)
迭代整个表.
You already have the solution in the question -- the only way is to iterate the whole table with pairs(..)
.
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
此外,请注意,#"运算符的定义要比这复杂得多.让我通过这张表来说明这一点:
Also, notice that the "#" operator's definition is a bit more complicated than that. Let me illustrate that by taking this table:
t = {1,2,3}
t[5] = 1
t[9] = 1
根据手册, 3、5和9中的任何一个对于#t
是有效的结果.唯一合理的使用方式是使用一个不包含nil值的连续部分组成的数组.
According to the manual, any of 3, 5 and 9 are valid results for #t
. The only sane way to use it is with arrays of one contiguous part without nil values.
这篇关于如何获取Lua表中的条目数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!