如何在 Lua 中获取哈希表中的键数? [英] How do I get the number of keys in a hash table in Lua?

查看:26
本文介绍了如何在 Lua 中获取哈希表中的键数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

myTable = {}
myTable["foo"] = 12
myTable["bar"] = "blah"
print(#myTable) -- this prints 0

我真的必须遍历表中的项目才能获得键的数量吗?

Do I actually have to iterate through the items in the table to get the number of keys?

numItems = 0
for k,v in pairs(myTable) do
    numItems = numItems + 1
end
print(numItems) -- this prints 2

推荐答案

我尝试了 # 运算符和 table.getn().我认为 table.getn() 会做你想做的事,但事实证明它返回与 # 相同的值,即 0.似乎字典根据需要插入 nil 占位符.

I experimented with both the # operator and table.getn(). I thought table.getn() would do what you wanted but as it turns out it's returning the same value as #, namely 0. It appears that dictionaries insert nil placeholders as necessary.

遍历键并计算它们似乎是获得字典大小的唯一方法.

Looping over the keys and counting them seems like the only way to get the dictionary size.

这篇关于如何在 Lua 中获取哈希表中的键数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆