[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: setfenv on userdata
- From: Rici Lake <lua@...>
- Date: Tue, 23 Aug 2005 19:12:46 -0500
On 23-Aug-05, at 6:51 PM, David Burgess wrote:
I am obviously missing something. The way I read it, each object has
an environment (LUA_ENVIRONINDEX) that by default points at
the global environment (LUA_GLOBALSINDEX). Am I wrong?
There is no global environment in 5.1. By default it gets set to the
current environment, which is the environment of the currently running
Any table can then be set as the environment that can
replace the environment for an object. Yes?
Yes, indeed. But you cannot set "no table" as the environment for an
Consider the following case: I bind myFancyWidget to a Lua userdata and
export it into the Lua environment.
The Lua script may want to override some method in a particular
instance of MyFancyWidget (to make it fancier, maybe :). Now, it could
create an entire new object to do that, but it would be a lot simpler
to do this:
local oldDoKeyPress = myFancyWidget.doKeyPress
if key == "ctl-y" then
-- handle control y the way I want to
return oldDoKeyPress(widget, key)
local widget = overrideCtlY(MyFancyWidget.new())
If I want to allow the Lua script to do that, then I need to have a
place to store the overloaded doKeyPress member function. I can't store
it in the standard metatable; that would apply to all instances.
Logically, I should store it in the widget's environment table, since
that is local to the widget instance.
In the common case, of course, no methods are overridden. So I don't
want an environment table at all; I want the method lookup to go
directly to the metatable. If I can't set the environment table to nil,
then I have to set it to some sentinel and test for that on every
lookup. So I was looking for something that:
a) semantically corresponded to (my) expected use of environment tables.
b) involved fewer API calls on common operations.