Okay, so I’ve got a strange problem with the following Lua code:
function quantizeNumber(i, step)
local d = i / step
d = round(d, 0)
return d*step
end
bar = {1, 2, 3, 4, 5}
local objects = {}
local foo = #bar * 3
for i=1, #foo do
objects[i] = bar[quantizeNumber(i, 3)]
end
print(#fontObjects)
After this code has been run, the length of objects should be 15, right? But no, it’s 4. How is this working and what am I missing?
Thanks, Elliot Bonneville.
Yes it is 4.
From the Lua reference manual:
Let’s modify the code to see what is in the table:
When you run this you see that
objects[4]is 3 butobjects[5]isnil. Here is the output:It is true that you filled in 15 slots of the table. However the
#operator on tables, as defined by the reference manual, does not care about this. It simply looks for an index where the value is not nil, and whose following index is nil.In this case, the index that satisfies this condition is 4.
That is why the answer is 4. It’s just the way Lua is.
The nil can be seen as representing the end of an array. It’s kind of like in C how a zero byte in the middle of a character array is actually the end of a string and the “string” is only those characters before it.
If your intent was to produce the table
1,1,1,2,2,2,3,3,3,4,4,4,5,5,5then you will need to rewrite yourquantizefunction as follows: