lua-users home
lua-l archive

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


Implementing both methods and properties gets convoluted and results in
slower code for both the userdata case and the table case. We did it, but
I'm not sure it was a great choice in retrospect because of the performance
issues.

The problem is that __index can't just be a table but instead needs to be a
function which then figures out whether it's dealing with a property that
needs to be computed from the object somehow or a method which gets shared.

One writes something like:

    __index = function( t, k )

        local method = methods[ k ]

        if method then
            return method
        end

        return properties[ k ]( t, k )

    end

Where methods and properties are tables of appropriate functions.

What would mitigate this would be support for accessing the base table in a
chain of __index lookups. That way one could set the methods table as the
__index table for the object and have a properties function as the __index
metamethod for that table:

    setmetatable( methods, { __index = function( t, k, base )
        return properties[ k ]( base, k )
    end }

    obj_mt = { __index = methods }

This way, method dispatch never leaves the optimized path through the Lua VM
for dealing with __index table chaining and properties are probably a bit
faster as well since again the Lua VM does most of the recognition about
which case applies.

Mark