在lua中计算字符串索引表 [英] counting string-indexed tables in lua

查看:62
本文介绍了在lua中计算字符串索引表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对具有一些用字符串索引的元素的表中的元素进行计数.当我尝试使用#运算符时,它只会忽略字符串索引的那些.例如:

I am trying to count elements in a table that has some elements indexed with strings. When I try to use the # operator, it just ignores string indexed ones. example:

local myTab = {1,2,3}
print(#myTab)

将返回3

local myTab = {}
myTab["hello"] = 100
print(#myTab)

将返回0混合它们,我尝试过

will return 0 mixing them, I tried

local myTab = {1,2,3,nil,5,nil,7}
print(#myTab)
myTab["test"] = try
print(#myTab)

先返回7,然后返回3,这是正确的,因为我读到某个地方#运算符在找到nil值时会停止(但是为什么第一张印刷品打印了7?)

returned 7 and then 3, that is right because I read somewhere that the # operator stops when it finds a nil value (but then why the first print printed 7?)

最后,我尝试了

local myT = {123,456,789}
myT["test"] = 10
print(#myT)

打印3,而不是4

为什么?

推荐答案

规则很简单,来自长度运算符:

除非给出了 __ len 元方法,否则仅在表为序列(即其正数字键的集合)的情况下定义表 t 的长度对于某些非负整数 n 等于 {1..n} .在这种情况下, n 是它的长度.

Unless a __len metamethod is given, the length of a table t is only defined if the table is a sequence, that is, the set of its positive numeric keys is equal to {1..n} for some non-negative integer n. In that case, n is its length.

在您的示例中:

local myTab = {1,2,3,nil,5,nil,7}

#mytab 是未定义的,因为 myTab 不是序列,带有或不带有 myTab ["test"] = try .

#mytab is undefined because myTab isn't a sequence, with or without myTab["test"] = try.

local myT = {123,456,789}

myT 是一个序列,长度为 3 ,带有或不带有 myT ["test"] = 10

myT is a sequence, and the length is 3, with or without myT["test"] = 10

这篇关于在lua中计算字符串索引表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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