Logo

Programming-Idioms

History of Idiom 26 > diff from v27 to v28

Edit summary for version 28 by :
New Lua implementation by user [Nepta]

Version 27

2016-02-19, 14:56:31

Version 28

2016-04-07, 06:44:10

Idiom #26 Create a 2-dimensional array

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

Idiom #26 Create a 2-dimensional array

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

Code
local array = setmetatable({},{
   __index = function(t1,k1)
      t1[k1] = setmetatable({},{
         __index = function(t2,k2)
            t2[k2] = 0
            return t2[k2]
         end
      })
      return t1[k1]
   end
})
Comments bubble
2D array are table of table (table are hashmap).

Use metatable to lazy initialize each row (t1[k1]) and each column (t2[k2]) the first time it's accessed.
Doc URL
http://www.lua.org/pil/11.2.html
Demo URL
http://codepad.org/KUJ0koqr