lua-users home
lua-l archive

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


On Jan 16, 2010, at 8:52 AM, steve donovan wrote:

> On Sat, Jan 16, 2010 at 5:48 PM, Eike Decker <zet23t@googlemail.com> wrote:
>> formerly, this was much more complicated (assigning to a (short) local
>> variable and then writing something like v.x,v.y,v.z = 1,2,3
> 
> Yes, it is a lot easier than the equivalent Lua 5.1 setup ;)
> 
> t = {}
> 
> setfenv(function()
>    x = 1
>    y = 2
>    g = function() return x+y end
>    z = 2
> end,t)()
> 
> assert(t.x == 1 and t.y == 2)
> assert(t.g() == 3)
> 
> This doesn't however modify the envronment of loadstring, however.

This, by the way, is a case where dynamic scoping would hurt. t.g() would generally result in an error because definitions for x and y could not be found.

That said, one could write something like:

	function wrapCurrentEnvironment( fn )
		local env = getCurrentEnvironment()
		return function( ... )
			in env do
				return fn( ... )
			end
		end
	end

Or:

	function wrapTableEnvironment( t )
		for k, v in pairs( t ) do
			if type( v ) == 'function' then
				t[ k ] = function( ... )
					in t do return v( ... ) end
				end
			end
		end
		return t
	end

Mark