Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Lua

Idiom #26 Create a 2-dimensional array

Declare and initialize a matrix x having m rows and n columns, containing real numbers.

local x = setmetatable({},{
   __index = function(t1,k1)
      t1[k1] = setmetatable({},{
         __index = function(t2,k2)
            t2[k2] = 0
            return t2[k2]
         end
      })
      return t1[k1]
   end
})

2D arrays are tables of tables (tables are hashmaps).

Use metatable to lazy initialize each row (t1[k1]) and each column (t2[k2]) the first time it's accessed.

See http://www.programming-idioms.org/idiom/27/create-a-3-dimensional-array/1675/lua for a more "standard" way.
x = {}
for i=1,m do
  x[i] = {}
  for j=1,n do
    x[i][j] = 0
  end
end
X : array (1 .. M, 1 .. N) of Float := (others => (others => 1.0));

New implementation...