lua-users home
lua-l archive

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


On Nov 5, 2009, at 6:57 AM, Fabien wrote:

In metalua:

-- Metalua extension --
-{ block:

   local function index_builder(expr, indices)
      indices = indices[1]
      if #indices==1 then return `Index{ expr, indices[1] } end
      local var = mlp.gensym()
      return `Stat{ 
         +{block: local -{var} = -{expr} }, 
         `Call{ +{getmetatable(-{var}).__index}, var, unpack(indices) } } 
   end

   mlp.expr.suffix:del '[' -- remove old "[...]" suffix parser

   mlp.expr.suffix:add{ "[", gg.list{mlp.expr, separators=","}, "]", builder=index_builder } 
}

-- Test code: a metatable with __index accepting several indices --
MT = { __index = |t, ...|
         "requesting from " .. tostring(t) ..
         " index " .. table.concat({...}, ", ") }

x = setmetatable({ }, MT)

-- Use the metatable --
print (x[1])
print (x[1,2])
print (x[1,2,3])

It generates normal code for 1-dimension indices; if there are several indices, it directly calls the __index metamethod with all the indices.

What about assignment? I guess if the __newindex function knows it will have a fixed number of indices there isn't a problem, but if you don't know that you need to tack the extra indices on after the value.

Mark