[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: importing in local scope
- From: Peter Shook <peter.shook@...>
- Date: Wed, 28 Nov 2001 22:30:55 -0500
> How can I "explode" a table in a local scope like:
> t = { foo=1, bar=2}
> foo = 2
> function foobaz()
> local_explode(t)
> local baz = foo + bar -- baz = 3 (not 4)
> end
> print(foo) -- 2 (not 1)
Here is an approximate solution to your problem.
> t= { foo=1, bar=2}
> foo = 2
> function foobaz() local baz = foo+bar print("baz=",baz) end
> print(foo)
2
> inscope( t, foobaz )
baz= 3
> print(foo)
2
This is the inscope function:
local tagnil = tag(nil)
------------------------------------------------------------------------------
-- make table s the global scope and call function fun with the
remaining
-- arguments.
--
function inscope( s, fun, ... )
local g = globals()
local tm = gettagmethod( %tagnil, 'getglobal' )
settagmethod( %tagnil, 'getglobal', function( name, value )
local v
v = %s[name] if v then return v end -- support delegation via
index
v = %rawget( %g, name ) if v then return v end
-- rawget must be an upvalue
if %tm then return %tm( name, value ) end
end )
globals( s )
local result = { %call( fun, arg ) }
%globals( g )
settagmethod( %tagnil, 'getglobal', tm )
return unpack(result)
end
Here is another example:
> t = { a=1, b=2, c=3 }
> a,b = 45,63
> function f(x) print( a+x, b+c ) print(a,b,c) a=99 end
> inscope( t, f, 5 )
6 5
1 2 3
> print(a,b,c)
45 63 nil
> foreach(t,print)
a 99
c 3
b 2
- Peter