[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: More on environments and objects
 
- From: Rici Lake <lua@...>
 
- Date: Fri, 26 Aug 2005 12:26:43 -0500
 
On 26-Aug-05, at 9:35 AM, Chris Marrin wrote:
    Function MyClass:f(v) a = v end
then you could go:
    local instance = MyClass()
    instance:f(5)
and when f(v) runs, the __setindex metamethod would get called with 
the parameters of the common function environment, the property 'a' 
and the value 'v'. This __setindex method can then go up to the next 
function to the stack and find the 'self' reference as the first 
param. It can then look up 'a' in this reference, set its value to 'v' 
and you're done. A nice object-oriented mechanism for handling 
instance local access.
Isn't this a complicated way of confusing the difference between 
instance and class members? I would have thought that:
  function MyClass:f(v) self.a = v end
was not much harder to type and quite a bit more self-documenting.
I'm aware that some languages do perform this sort of scoping exercise, 
so I guess some people must like it. I think it also leads to obscure 
bugs.
That doesn't avoid the self confusion error which you noted.
However, in many cases you can avoid the problem by using get/set 
notation instead of methods. If the user interface were:
  obj.f = v
instead of
  obj:f(v)
then there would be no possibility of programmer error, and it would 
have the advantage of letting you define both an f-setter and an 
f-getter. (Or the disadvantage of forcing you to :) Anyway, that was 
the motivation for the library for which I sent you an excerpt.
This doesn't work in the case of setters which require more than one 
argument, or getters which require arguments. But that's not the common 
case (although it's not a rare case, either).