Question about getn

Hello to everybody. I bought Codea a few days ago and I am enjoying it very much. Congrats to its creators, and please, keep improving it, I’m sure it will become a great development tool.

I have a question regarding getn. I need to know the size of a table, but I think getn is not working as expected, according to the Lua manual:

a={}
a[13] = 25
a[6] = 37
print(table.getn(a)) 

This program prints 0, as if the table were empty. Is it normal?

I don’t know how to post source code. I see now that the code I’ve pasted is in one line…

Value you are looking for is #a

a = {}
a[13] = 25
a[6] = 37
print(#a)

Use “~~~” to start/stop code sections.

getn is a bit odd, as are lua tables in general - the implementation really is “what’s the highest non-nil key?”. Lua arrays (which are just tables) start at 1, so because a[1] is nil, getn is 0.

Yes, this is just weird. The practical upshot is if you want to know how many elements are in a sparse array/table, you have to keep track as you insert/delete them, or just count them using pairs().

@kmeb - #a in your example will return 0, try it (I did, to double-check).

Thank you, I think the best solution is counting the elements with pairs.

Hrmm… seems to me that a lua table only works properly when you you fill it sequentially starting with index 1. Your solution of manually counting the elements doesn’t even work correctly. Try this:

a[13] = 25
a[6] = 37
--Now lets print out the values
for i,v in ipairs(a) do print(v) end

Nothing. Doens’t work. Now, try:

a[1] = 25
a[2] = 37
--Now lets try that again.
for i,v in ipairs(a) do print(v) end

Works fine. Does anyone know if you can get the size of a table, or iterate over the elements of a table, if the indexes are not sequential?

    t = {}
    t[10] = "Here"
    t[20] = " you"
    t[30] = " go."
    table.foreach(t, print)

Note that order is not predictable. If you want to do something with each item, you can substitute your own function where print is in this example. Such as…

function setup()
    i = 0
    t = {}
    t[10] = "Here"
    t[20] = " you"
    t[30] = " go."
    table.foreach(t, count)
end

function count()
    i = i + 1
    print(i)
end

you could use this @Vega

for i,v in pairs(a) do print(v) end

that works even with non sequential tables…

@Vega ipairs is specifically for array-like tables beginning at 1. As @inviso says, you want pairs.

It’s actually possible to build your own version of table that keeps count of its elements. You could do the by overriding the __newindex metamethod.

Okay, thanks.

function Len(TABLE)
    count = 0
    for i,v in pairs(TABLE) do count = count + 1 end
    return count
end

That might be a handy function to have in my toolbox.