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

So, if I do:

function foo()
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-+ 
|    | "All power corrupts, but we need electricity." ---
| ( | Diana Wynne Jones, _Archer's Goon_
+- --+ 

Attachment: pgpE9QXcbGub1.pgp
Description: PGP signature