lua-users home
lua-l archive

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


Hi Bernd!

Wow, finally!!! A constructive response that actually has THOUGHT in it. I almost thought this list was unable of that.

IMO you are expressing your criticism a little harshly ("severe flaws" that are not really that severe in the end :)), but at least there is technical thought in it and I sincerely applaud that.

I will look into the technical details of your answer very soon and give you an appropriate reply (retort? whatever :)).

Cheers,
Stefan

On Sat, Nov 26, 2011 at 7:58 PM, Bernd Eggink <monoped@sudrala.de> wrote:
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