lua-users home
lua-l archive

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


On 21.11.2011 15:15, Leo Razoumov wrote:
On Sun, Nov 20, 2011 at 07:27, Stefan Reich
<stefan.reich.maker.of.eye@googlemail.com>  wrote:
Hi guys!

I just created a neat little object system for Lua (5.1) that does pretty
much exactly what I want.

You use it like this:

newThing = object(function() -- could add arguments here too
   var1 = 1
   local var2 = 'test'

   function method1()
     var1 = var1+1
   end
[[snip]]

An elegant idea, indeed! And  'self' reference is avoided.

It may look elegant, but it has some severe flaws (IMHO).

1. If the function's environment is made identical to the global environment, any global variable X can be accessed as obj.X. This is at least confusing and contradicts the OO paradigma. Example:

--------------------------------------------------------
y = 222

function Class(c)
    x = c
end

function ctor(definition)
    return function(...)
        local env = setmetatable({}, {__index = _G })
        setfenv(definition, env)(...)
        return env
    end
end

obj = ctor(Class)(1)
print(obj.y)   --> 222
--------------------------------------------------------

2. In the example above, obj.x can be read and changed from outside. To prevent this, one would normally make the variable local. This leads to even more weirdness:

--------------------------------------------------------
x = 111

function Class(c)
    local x = c
    function pr() print("obj.x", x) end
end

function ctor(definition)
    return function(...)
        local env = setmetatable({}, {__index = _G })
        setfenv(definition, env)(...)
        return env
    end
end

obj = ctor(Class)(1)

print(obj.x, x)   --> 111 111
obj.pr()          --> 1

obj.x=112
print(obj.x, x)   --> 112 111
obj.pr()          --> 1
--------------------------------------------------------

I admit that I don't quite understand why the last example behaves as it does. I would be glad if somebody could explain what happens here; I'm experienced in Java, but still a beginner in Lua.

Regards,
Bernd

--
http://sudrala.de