lua-users home
lua-l archive

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


Steve wrote:
> It really would be nice to be able change how Lua looks up local variables
from within
> Lua. This would allow variable references in object methods to
automatically look in
> self (as in many OO languages) if a local doesn't match.
>
>function Person:fullName()
>  return self.title.." "..self.firstName.." "..self.lastName
>end
>
>Could become:
>
>function Person:fullName()
>  return title.." "..firstName.." "..lastName
>end

This could be done, if only the changes to the treatment of the global scope
that I've been whining about since April would be implemented.  Maybe you
are giving me chance here to demonstrate how the change would solve a
practical problem...

If global accesses triggered the table events of the global table instead of
getglobal/setglobal events, we could implement what you desire as follows:

1) make a wrapper for your classes methods that would back up the current
global table and replace it with your class object.  That is, when the user
calls obj:fullName() it's really first handled by a wrapper that switches
the global table and then calls the actual fullName().

2) now global accesses such as the variable "title" will just access the
fields in your object.  Make the "index" event of your class (remember, in
my fictitious world a failed global access will call the index event of the
global table) access the real global table that you backed up in the method
wrapper.

3) go have a beer, because Lua let's you do neat things like mimic the name
lookups of other languages

That's all I want.  I showed the other day how the changes could be
backwards compatible.  What's left?

-John