3

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?

8
  • 1
    I get bad argument #2 to 'insert' (position out of bounds) at line 2.
    – lhf
    Aug 22, 2019 at 15:20
  • Oh, that's interesting. Different lua version maybe? Looks like I'm using Lua 5.1
    – dg_emp
    Aug 22, 2019 at 15:24
  • Yes, that message is output by Lua 5.2+.
    – lhf
    Aug 22, 2019 at 15:26
  • 1
    Anyway, test[5] = "5" is the simplest and best approach.
    – lhf
    Aug 22, 2019 at 15:27
  • 3
    My 5 outputs on Lua 5.1 are: {[5]="5"}, {[1]="1", [5]="5"}, {[1]="1", [4]="4", [5]="5"}, {[1]="1", [3]="3", [4]="4", [5]="5"}, {[1]="1", [2]="2", [4]="3", [5]="4", [6]="5"} Aug 22, 2019 at 16:46

1 Answer 1

4

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.

1
  • Thank you, Tom! The paragraph about table borders finally dissolved my confusion.
    – dg_emp
    Aug 26, 2019 at 7:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.