lua-users home
lua-l archive

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


I was playing around with primitive metatables. The following works in 5.1:

local function factorial(n)
  return n < 3 and n or n*factorial(n-1)
end
Number = { factorial = factorial }
debug.setmetatable(3, {__index=Number})

Now I can do (7):factorial() and voila! returns 5040! And it seems
that I can pass any number I want into debug.setmetatable, with the
same effect. Pretty snazzy.

My question is: is there a performance penalty associated with doing
this? Does adding this metatable cause all numeric operations to
perform slower? Also, I notice that overriding any of the operator
metamethods (like __div) for numbers has no effect. Is this for
performance reasons?

If you could override the operators for primitives, seems like you'd
need rawdiv, rawadd, and so on. For example:

Number = {
  __div = function(num, denom)
    return denom ~= 0 and (num / denom) or error("Divide by zero!")
  end
}

num / denom would just call the same metamethod, leading to an infinite loop.

-Paul