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

查看:277
本文介绍了如何获取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天全站免登陆