lua-users home
lua-l archive

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


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.

   -- Fabien