lua-users home
lua-l archive

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


I'm designed an OO system for a configuration language for a tool I'm working 
on. The configuration language is, of course, Lua.

In my OO system, I want to use the function environment as an implicit 'this' 
value, so I don't have to force the user to use it explicitly. I've mostly 
got this working, but I won't go into the implementation details right now 
(because they're fiddly).

However, one thing I keep finding myself doing is fiddling around with 
function environments. What I really want is a way to set a function 
environment to be the special value 'same as caller', but this doesn't seem 
possible. What I'm actually doing is something like this:

function massagefunction(f)
	return function(...)
		local oldenvironment = getfenv(f)
		setfenv(f, getfenv(2))

                -- Should really be using pcall here.
		local result = {f(unpack(arg))}

                -- Have to put the environment back afterwards, or else
                -- we'll horribly break reentrant calls.
		setfenv(f, oldenvironment)
		return result
	end
end

So, if I do:

function foo()
	print(wibble)
end
foo = massagefunction(foo)

...then when I call foo(), it'll look up 'wibble' in the environment of where 
I called foo().

This seems to be needlessly complex, and there's lots of overhead. This is a 
configuration language, so overhead is not a problem, but my sense of 
elegance is protesting.

Can anyone suggest a better way?

-- 
+- David Given --McQ-+ 
|  dg@cowlark.com    | "All power corrupts, but we need electricity." ---
| (dg@tao-group.com) | Diana Wynne Jones, _Archer's Goon_
+- www.cowlark.com --+ 

Attachment: pgpC9O1R9vVsy.pgp
Description: PGP signature