lua-users home
lua-l archive

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


I wonder if Lua might consider adding a __method metamethod, which
could be used for OO programming and as an alternative to the colon
operator.

For example, if you wanted to do OO programming without using the
colon syntax using Lua 5.2, you might write:

local funcs = {
    inc = function(self)
        self.a = self.a + 1
        return self
    end
}

local function new(t)
   local o = t or {a = 0}
   return setmetatable(o, {
      __index = function(t, k)
          return function(...) return funcs[k](t, ...) end
      end
   })
end

assert(new().inc().inc().inc().a == 3)


This style, when compared to using the colon operator, has the nice
property that the parentheses are optional.  You can write:

local f = new().inc
assert(f().a == 1)

But performance here is far worse than using the colon operator.  In
the assertion above, 3 closures are created, whereas there are zero if
using the colon operator.

If, however, Lua offered a __method metamethod that matched the syntax
"t.k(...)", then we could add the following to our metatable:

    __method = function(t, k, ...)
       return funcs[k](t, ...)
    end

Like using the colon operator, the following code would create no closures:

    new().inc().inc().inc()

Thoughts?

Thanks,
Greg