如何在Lua字符串中计算子数组的数量

如何在 lua 字符串中计算子数组的数量。

我有一个 lua 字符串,格式如下,

{{"engName1":"Test1","validDurPeriod":0,"appStatus":2,"engName3":"", "ExtraInfo":{"returnPeriod":7,"stayType":50,"fingerprintInd":49,"stayPeriod":6,"medicalInd":49},} {"engName1":"Test2","validDurPeriod":3,"appStatus":2,"engName3":"", }, {"engName1":"Test3","validDurPeriod":2,"appStatus":2,"engName3":"","ExtraInfo":{"returnPeriod":7,"stayType":50,"fingerprintInd":49,"stayPeriod":6,"medicalInd":49} }, {"engName1":"Test4","validDurPeriod":3,"appStatus":2,"engName3":"", },}

我想计算 lua 字符串中子数组的数量, 像这样的 {{},{},{},{}} 在这里计数为 4

我尝试了一些以下代码来检查它是否包含数组,但无法得到精确的计数。 以下代码适用于单个数组但不适用于多个数组

function checkType(sample)
    if string.startswith(sample, "{{", true) or string.startswith(sample, "{ {", true)  or string.startswith(sample, "{  {", true) then
        return true;
    else
        return false;
    end
end
点赞
用户107090
用户107090

如果 s 包含您的字符串,则 n 包含以下计数:

local _,n=s:gsub("[^{}]",""):gsub("{}","")
2014-06-14 13:44:23
用户3740440
用户3740440

如果你的数组正常工作,你应该能够使用 table.getn(table) 函数。

举例:

print(table.getn{10,2,4})          --> 3
print(table.getn{10,2,nil})        --> 2
print(table.getn{n=1000})          --> 1000

a = {}
print(table.getn(a))               --> 0

希望这个能有帮助;)

来源:19.1 - Array Size

2014-06-15 16:43:33