2
votes

I am struggling to understand this behavior in Lua. If I execute in local console:

tab={}
tab[100] = "E"

the table looks like this:

{
  [100] = "E"
}

Now I am populating my table in a for-loop with a few conditions:

cell_types = {}    
cell = 1    
for y=1, 1000 do
    for x=1, 1000 do
      if some_condition then
        cell_types[cell] = "E"
      elseif some_condition then
        cell_types[cell] = "M"
      else
        cell_types[cell] = "C"
      end
    cell = cell+1
    end
  end

Now however the table looks like this:

{ "E", "E", "M", "E", "C", "C", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E" }

If I remove the first table call (cell_types[cell] = "E") then again I have key/value pairs:

{
  [101] = "M",
  [102] = "M",
  [103] = "M",
  [104] = "M",
  [105] = "M",
  [106] = "M",
  [107] = "M"
}

What could cause this behavior? And how can I make sure to always store key/value pairs in my table?

Thank you.

1

1 Answers

3
votes

The Lua table is always a collection of key-value pairs.

It's just internally it's optimized to store continuous sequence as an array, and discontinuous values as a hash map.

By removing some assignments, like cell_types[cell] = "E" case, you're introducing the holes in the sequence, so it's no longer falls into the array implementation part, and has to be iterated as a hash map with pairs(). Note that ipairs() will only iterate the array part of the table, and will stop at some undefined point, where it will find a hole in sequence.