Table creation + table iteration using for loops

I’m a Defold beginner :slight_smile:

So when I write this code and run it:

test = {}
for i = 10, 20, 0.5 do
print(i)
test[i] = i * 5
end
for key, val in pairs(test) do
print(key, val)
end

The result is:

|DEBUG:SCRIPT: 10|50|
|DEBUG:SCRIPT: 11|55|
|DEBUG:SCRIPT: 12|60|
|DEBUG:SCRIPT: 13|65|
|DEBUG:SCRIPT: 14|70|
|DEBUG:SCRIPT: 15|75|
|DEBUG:SCRIPT: 16|80|
|DEBUG:SCRIPT: 13.5|67.5|
|DEBUG:SCRIPT: 12.5|62.5|
|DEBUG:SCRIPT: 18.5|92.5|
|DEBUG:SCRIPT: 16.5|82.5|
|DEBUG:SCRIPT: 10.5|52.5|
|DEBUG:SCRIPT: 17.5|87.5|
|DEBUG:SCRIPT: 19.5|97.5|
|DEBUG:SCRIPT: 19|95|
|DEBUG:SCRIPT: 20|100|
|DEBUG:SCRIPT: 18|90|
|DEBUG:SCRIPT: 17|85|
|DEBUG:SCRIPT: 11.5|57.5|
|DEBUG:SCRIPT: 15.5|77.5|
|DEBUG:SCRIPT: 14.5|72.5|

Can anyone tell me why this order is so random?

Also is the actual order of the keys and values in the table or is it an iteration thing?

I think you can only rely on the order of a table if you use integer keys (i.e. 1,2,3 … n). In your example the keys are in 0.5 intervals, and so the order is no longer reliable. You will notice that if you drop 0.5 from your iterator, your table will be in the expected order.

In summary, use integer keys if you want to rely on the order of your table. Otherwise the order can vary from one time to another.

This is a feature of Lua and is by design.

4 Likes

Oh, thanks for your answer! Is there any way I can make them ordered or am I going to have to find a different way to do it?

You work around it.

If you know the step is in 0.5 interval then you can just make an integer based table and whenever you access it you multiply the key by 0.5. So 20 would be 10 (20 x 0.5) and 21 would be 10.5 (21 x 0.5). That seems kind of messy to me though.

You could design it such that the keys of the table are meaningless integers, and the meaningful values are stored in a table inside each value:

	test[1] = {key = 10, value = 50}
	test[2] = {key = 10.5, value = 55}

There may be better ways someone else might suggest. It really depends on what you are trying to achieve.

2 Likes

you can use ipairs to iterate over index-value pairs.

2 Likes

The “problem” is that ipairs() assumes a starting index of 1 with the index incrementing by 1 for each iteration and no gaps in the sequence (ie no nil values)

3 Likes