lua-users home
lua-l archive

Re: Multiple functions: was the gc

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


Some more thoughts on global access through an upvalue...
Functions are constructed in two ways:
1. By a load command (including require)
2. By a function expression in a script
To start with option 2: in this case lexical scoping is a natural candidate for "inheriting" the globals. Think of a global access to "x" as basically syntactic sugar for "(globals or getfenv(0)).x". Here "globals" can refer to an actual local definition or function argument in the script. A load command can implicitly provide an outer "globals" definition, so "globals" is always present:
 -- loader functions do something similar like shown here...
 -- implicit globals
 local globals = load_time_globals
 -- script function
 return function(...)
 -- loaded script code goes here.
 end
And that's it really. All other implications can be derived from the current lexical scoping rules. For example, to define some functions with different globals one could do:
 function foo()
 -- new globals
 local globals = { <some table data> }
 -- bar binds to the local globals
 -- (by lexical scoping)
 function bar(x)
 <...>
 end
 -- baz as well...
 function baz(y)
 <...>
 end
 -- one can even easily change globals for
 -- bar and baz...
 globals = some_other_table
 -- or provide a function for that...
 function setbarbazenv(table)
 globals = table
 end
 end
Also, a load... function always creates (implicitly) a new upvalue. So changing the globals of the loaded script will not change the globals of the script that calls the load... function.
Etc.
There will no doubt be many implications that I'm not aware of. But I think it's an intriguing idea...
--
Wim

AltStyle によって変換されたページ (->オリジナル) /