lua-users home
lua-l archive

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


Rafael told you the "standard" handling, but this really does not solve the
problem you presented (not wanting to require prefixing the member variables
with an explicit table lookup).

Daniel gave you the start to solving your problem with setfenv.

However, after you check that out you will likely want to search for "proxy
tables" in the list archives.

Basically setfenv overrides the "globals" for a function.  You will probably
want to add to this a mechanism to fall back on the "actual" globals in the
event that a variable is not located in the new "environment" for the
function.  Discussions about "proxy tables" relate to that type of handling.

Also, you should lookup "upvalues" as well as they are likely to be
important to your solution as well.


--- OK the following is a quick stab at a functionalized solution
--- I have no idea if this is coded accurately, and I KNOW it
--- incorrectly handles boolean members of tbl.

function AddMember(func, tbl) do
	local NewEnv = {}
	local NewEnvMeta = {}

	NewEnvMeta.tbl=tbl
	NewEnvMeta:__index = function(key) do
		return self.tbl[key] or _G[key]
	end
	NewEnvMeta:__newindex = function(key, value) do
		if (self.tbl[key]) then
			self.tbl[key] = value
		else
			_G[key] = value
		endif
	end

	setmetable(NewEnv, NewEnvMeta}

	setfenv(func,NewEnv)
end


-----Original Message-----
From: lua-bounces@bazar2.conectiva.com.br
[mailto:lua-bounces@bazar2.conectiva.com.br]On Behalf Of Daniel
Silverstone
Sent: Tuesday, April 13, 2004 10:31 AM
To: Lua list
Subject: Re: A question of scoping (I think)


On Tue, 2004-04-13 at 03:00, Ryan Leigh wrote:
> Which is a pain and error prone (because I'm a lousy typist). So, to
> finally get to the point, is there something I can do where when I
> call a function that is in some object and I reference a variable, is
> there someway I can force it to look in the object's table first
> before going global? I guess this is similar to having a C++ class and
> I want to scope to member variables in a member function. Or am I just
> not envisioning all the possibilities of Lua and there exists a much
> better way of doing things.

Erm, it doesn't help the whole object-then-global thing (you'd need
metatables for that) but..

setfenv(myobject.update,myobject) might do what you want. (no guarantees
here, I can't remember the exact syntax or side-effects, read the docs
for more info)

D.

--
Daniel Silverstone                       http://www.digital-scurf.org/
Hostmaster, Webmaster, and Chief Code Wibbler: Digital-Scurf Unlimited
GPG Public key available from keyring.debian.org       KeyId: 20687895