Search code examples
luaoperatorsevaluationmetatablemeta-method

Setting multiplication operator through metatable in specific environment in Lua


local names  = setmetatable({},
{__mul = function(a,b) return a|b end}
)
names={i=0,j=1}
tr=load("return i*j",nil,"t",names)()
print(tr)

It prints tr as 0. The expected answer is 1 as 0|1 results to 1. Where is the code wrong?


Solution

  • Try:

    local mt_obj = {
       __tostring = function(o) return tostring(o[1]) end,
    }
    local function get(o)
       if type(o) == "table" then return o[1] else return o end
    end
    local function new(v)
       return setmetatable({v}, mt_obj)
    end
    function mt_obj.__mul(a,b)
       return new(get(a)|get(b))
    end
    local mt_env = {
       __index = function(t,k) return new(t.variables[k]) end,
       __newindex = function(t,k,v) t.variables[k] = v end,
    }
    
    local names = {i=0,j=1}
    local env = setmetatable({variables = names}, mt_env)
    tr=get(load("return i*j*8",nil,"t",env)())
    print(tr)