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

时间:2014-06-14 10:25:42

标签: lua

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

我有以下格式的lua字符串,

  

{{ “engName1”: “测试1”, “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

2 个答案:

答案 0 :(得分:1)

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

local _,n=s:gsub("[^{}]",""):gsub("{}","")

答案 1 :(得分:0)

如果你的表工作正常,你应该可以使用函数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