2

how to count number of sub array in lua string.

I have a lua string in following format,

{{"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":"", },}

I want to count number of sub arrays in lua string , something like {{},{},{},{}} as here count is 4

I tried something below code to check its contains array but not able to get the exact count. below code is working for single array but not working for multiple array

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
  • 1
    Have you tried looking at JSON libraries? Commented Jun 14, 2014 at 13:04
  • Why do you need to count these? What are you trying to achieve? Commented Jun 14, 2014 at 13:44

2 Answers 2

1

If s contains your string, then n below contains the count:

local _,n=s:gsub("[^{}]",""):gsub("{}","")
Sign up to request clarification or add additional context in comments.

1 Comment

Why do you need to count these? Depending on number of elements found in string I need to run a for loop and display these values.
0

If your table works correctly, you should be able to use the function table.getn(table).

Examples:

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

I hope that does the trick ;)

Source: 19.1 - Array Size

1 Comment

wouldn't just #a be better, also because of forward compatibility to 5.2?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.