lua-users home
lua-l archive

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


Hello,
I would like to have a "Mathematica style" table arthmetics in Lua.
it is ok to have it implemented in Lua, something like:

local function ar_func (o1, o2, op)
  local o = {};
  if type(o1) == "table" and type(o2) == "table" then
    if #o1 == #o2 then
      for i = 1, #o1 do o[i] = op(o1[i], o2[i]) end
      return o
    end
  elseif type(o1) == "table" and type(o2) == "number" then
  for i = 1, #o1 do o[i] = op(o1[i], o2) end
  return o
  elseif type(o1) == "number" and type(o2) == "table" then
    for i = 1, #o2 do o[i] = op(o1, o2[i]) end
    return o
  end
  return nil
end


table.default_metatable = {}

table.default_metatable.__add = function (t1,t2) return ar_func(t1,t2, function (o1,o2) return o1+o2 end) end table.default_metatable.__mul = function (t1,t2) return ar_func(t1,t2, function (o1,o2) return o1*o2 end) end table.default_metatable.__sub = function (t1,t2) return ar_func(t1,t2, function (o1,o2) return o1-o2 end) end table.default_metatable.__div = function (t1,t2) return ar_func(t1,t2, function (o1,o2) return o1/o2 end) end table.default_metatable.__pow = function (t1,t2) return ar_func(t1,t2, function (o1,o2) return o1^o2 end) end table.default_metatable.__unm = function (t1 ) return ar_func(t1,t1, function (o1,o2) return -o1 end) end


BUT, the problem is there is no way to set it as metatable to newly created tables automatically, to make code like {x,y,z} * {1,0,1} + 5 working.

I made it the ugly way, by modifing OP_NEWTABLE in lvm.c:

void luaV_execute (lua_State *L) {
...
vmcase(OP_NEWTABLE) {

  Table *t = luaH_new(L);

//+++++++++++++++
  if (NULL == t->metatable){
    if (LUA_TTABLE == lua_getglobal(L, "table")){
if (LUA_TTABLE == lua_getfield(L, -1, "default_metatable")){
        t->metatable = hvalue(L->top - 1);
      }
      lua_pop(L,1);
    }
    lua_pop(L,1);
  }
//+++++++++++++++
...

Currently there are "per type" metatables for all the other types: numbers, strings. Is it possible to add one more for the table type, which would be set as metatable for new tables by default?