lua-users home
lua-l archive

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


On Fri, May 30, 2003 at 09:39:45PM -0400, Peter Shook wrote:
> You could use setfenv to add magic to your 
> methods, but then each object must have its own copy of each method.  I 
> don't think this is a practical approach.

It seems to be  possible to do this without copying each method if you
exploit debug.getlocal():

function make_object_scoped(fn)
    local env=getfenv(fn)
    function ind(tab, name)
        local slf, slfval=debug.getlocal(2, 1)
        if slf=="self" then
            if slfval[name] then
                return slfval[name]
            end
        end
        return env[name]
    end
    setfenv(fn, setmetatable({}, {__index=ind, __newindex=env}))
end

Foo={}

function Foo.new()
    return setmetatable({}, {__index=Foo})
end

function Foo:bar()
    print(baz)
end

make_object_scoped(Foo.bar)

a=Foo.new()
a.baz=3
a:bar()

This code seems to work, but I could be doing something wrong. Personally,
I'd prefer something like Ruby's @foo as syntactical sugar for self.foo,
yet prefer self.foo over implicit object scoping.

> It sure would be nice if we could type:
> function someclass:method(x)
>  local this, that in self
>  if this and that then this = x + that end
> end

You could use a similar trick as above to set class variables after
the function has been defined. 

-- 
Tuomo