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?
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).
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