I needed to add elements to a lua table in a certain order and tried to insert each element to its final position (but in a random order). I'm new to lua and hadn't worked with table.insert before (only read that tables support both an associative and an array form), but I was pretty sure it couldn't work this way, so I made a little test:
local test = {}
table.insert(test, 5, "5")
table.insert(test, 1, "1")
table.insert(test, 4, "4")
table.insert(test, 3, "3")
table.insert(test, 2, "2")
Test output after each insert delivered this interesting behavior:
["5"]
["5","1"]
["1","4","5"]
["1","3","4","5"]
["1","2","3","4","5"]
Actually it worked better than expected (I thought that inserting to a table with two elements at position 4 would probably append), but the lines 2 and 3 got me absolutely confused. Inserting at position 1 appends, and the next insert reorders the other elements?!?
Next try was to avoid table.insert and instead use test[5] = "5" etc. The result was exactly the same...
Only way to fix it was to initialize elements 1 through 5 with an empty string first, and then inserting the actual values in random order.
Does anybody have an idea why the tables behave this way?
Your operations do not apply sensibly a table without a sequence. The first statement creates a table without a sequence. Then it all goes south.
6.6 – Table Manipulation
Remember that, whenever an operation needs the length of a table, all caveats about the length operator apply (see §3.4.7).
One generally chooses to maintain the sequence of a table or not. If not, avoid functions and the # operator (it's built-in implementation) that are designed for sequences.
You could build up the table as @lhf describes:
local test = {}
test[5] = "5"
test[1] = "1"
test[4] = "4"
test[3] = "3"
test[2] = "2"
and then at a point when you are convinced that you have created a table with a sequence, begin treating the table as such.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With