lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> I'm planning to translate the code like that:
> 
> m[i, j]         => __index(m, i, j)
> m[i, j] = v    => __newindex(m, i, j, v)
> 
> So all the indexes will be feeded to the __index or __newindex
> metamethods in the order. I guess that the variable number of
> arguments is not a problem: the metamethods are supposed to check how
> many arguments and act accordingly.

I guess the next code gives a reasonable solution for 2D arrays.
(It should not be too dificult to generalize it to n dimensions.)

-------------------------------------
local mt1 = { __index = function (t,k)
                local nt = setmetatable({}, {
                             __index = function (t1, k1)
                                         return t:index(k,k1) 
                                       end,
                             __newindex = function (t1, k1, v)
                                            t:newindex(k,k1,v) 
                                          end,
                           })
                t[k] = nt
                return nt
              end,
              mode = 'v',
            }


function newmatrix (index, newindex)
  return setmetatable({index = index, newindex = newindex}, mt1)
end
-------------------------------------

The call 'newmatrix(f1,f2)' creates a new matrix 'm' that calls
f1(m,i,j) for accesses m[i][j] and calls f2(m,i,j,v) for
assignments m[i][j]=v. Memorization avoids creating too much
garbage (mainly if you traverse these matrices in proper order).

(I slightly different approach is to use a fixed metatable for the
inner tables, storing in those tables what are upvalues here. This
might save some memory but makes the calls a little more expensive.)

-- Roberto