Search code examples
randomluakeylua-table

When defining keys in table, why is it inserted in a random order?


While working on a Love2d project, I noticed that when defining tables with a key and putting said tables in another table, in a loop, the tables were being inserted in a random order.

To test this, I made a short script that will hopefully explain my predicament a little better. My first assumption is because the keys are inserted wherever I have memory available, though I'm not sure. I've never encountered this before, anyone have any ideas?

enter image description here


Solution

  • Lua implements tables as hash tables, hence the apparent random order when traversing them. That is by design so that access to tables can be done in amortized constant time.

    If order is important to you, use sequential indices and complex values, like this

    t[1] = { key="CA", value="California" }
    t[2] = { key="TX", value="Texas" }