Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]
Photo

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

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

horacebury

[GLOBAL: userInfoPane.html]
horacebury
  • Corona Geek

  • 3,069 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"
end

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

print(#t)

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,
Matt.
uid: 8271 topic_id: 1854 reply_id: 301854


[TOPIC: post.html]
#2

akhtar

[GLOBAL: userInfoPane.html]
akhtar
  • 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
end

(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



[topic_controls]
[/topic_controls]