Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]

Counting elements in a table
Started by horacebury Aug 31 2010 11:50 PM

- - - - -
1 reply to this topic
This topic has been archived. This means that you cannot reply to this topic.
[TOPIC: post.html]


[GLOBAL: userInfoPane.html]
  • Corona Geek

  • 3,070 posts
  • Corona SDK

Sorry if this has been asked before, but if I declare a table:

local t = {}

Then give it a single value:

t.count = 28

And then add some content by index:

for i = 1, 10 do
t[ I ] = "some value"

Would I get 10 or 11 if I print it's content.:


And does the first element now refer to the first "some value" or the 28.

I guess the short question would be; does assigning . property values affect the value inserted by index?
Having tested this, it appears as though I maybe misunderstood how the table length operator works. It seems to me that it will return the last non-nil index on a 1-based indices. This means that properties assigned values without an index numeral, ie: ".count", do not get counted, whereas entries made as "t[ index ] = ..." do.
In short, it seems as though the example in my original post would print 10 if elements 1 to 10 had values, would also print 10 if they were all nil except element 10 and will print 10 regardless of the value of property .count
It would be great if someone could just post stating whether or not I'm correct here, please?

Many thanks,
uid: 8271 topic_id: 1854 reply_id: 301854

[TOPIC: post.html]


[GLOBAL: userInfoPane.html]
  • Enthusiast

  • 61 posts
  • Guests

the easiest way to count all the things you have added to a table:

for a table t

for k,v in pairs(t)
count = count + 1

(you could use while/next also)

you are right it starts at 1 and scans for the first missing index that is pretty much how length works.
uid: 846 topic_id: 1854 reply_id: 5634