lua-users home
lua-l archive

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


It sounds quite logical, and the colon operator often seems to be irritating for
beginners (which I really don't understand at all, since it is dead simple - but
it is often the topic of posts and was always taking longer than I expected when
teached in courses). So a hidden lexical reference to the orignal table sounds
not too bad. 

> Implementation details aside, it seems to me that from the 
> semantics of any local reference to self in a function body, Lua 
> should always be able to infer the caller / object from the 
> lexical scope -- without the need for a colon operator or 
> "hidden" parameters.
> 

However, this could also break some code. By using metatables, it is not clear,
which table to be used as self reference, since the function is just sitting on
the stack and is then called.

-- assuming your colon free here implementation
foo = {}
function foo.new ()
  local obj = {}
  setmetatable(obj,{__index = self})
  return obj
end

function foo.bar ()
  print(self)
end

huu = {}
setmetatable(huu,{__index = foo})
function huu.new ()
  return foo.new(self) -- But - I want to use huu as self value now!?
end

obj = huu.new() 
huu.bar() -- which table is now self? obj, huu or foo?

otherobj = {}
foo.bar(otherobj) -- won't work, foo will be self
-- the colon operator handles the stuff above just fine and allows 
-- more complex OO concepts, not only the inheritance

So - what value has the self value in all these cases? And how can I pass a
value that should be used as a self reference other than the table where the
function resides?
The colon operator makes it clear for the compiler, which table should be used
as the self value. An implicit form wouldn't be sufficient I think, especially
not if the function that should be called is tunneled through different
metatable calls. 
The initial idea sounded reasonable, but I think in that way, it cannot replace
the colon operator. I had cases where a function written for one class where
used by objects of total different classes (i.e. if certain calculations on
variables were just the same because the names where identical). All this
wouldn't work then any more I think.

-eike