lua-users home
lua-l archive

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


On Sun, Oct 25, 2015 at 11:47 AM, Egor Skriptunoff
<egor.skriptunoff@gmail.com> wrote:
> Hi!
>
> Some functions are better to be generated and "load"-ed on-the-fly
> instead of be fully prepared in the source code.
>
> At the moment, we are forced to use globals or pass separate environment
> table to share variables with "load"-ed functions, which is not very handy.
> It also implies frequent hash-table lookups, which is not very fast.
>
> To make sharing local variables with "load"-ed functions nice and easy,
> a new keyword, a new syntax and a new function can be introduced:

This is very much indulging premature optimization but I'll bite.

The existing functionality (debug.upvaluejoin) is all you need to do
what you want:

- Declare locals to be exported:

local x = 1
export("x", function() return x end) -- **
local y = 2
export("y", function() return y end)

- hook the load function which creates locals with the names of the
exported locals and then joins them to the loaded chunk, something
like:

-- get exported local names
local new_chunk = "local x,y; return function(...)"..chunk.." end"
local f = original_load(new_chunk)()
-- join exported upvalues on f

** It's necessary to create this function otherwise you have no
closure with x as an upvalue

-- 
Patrick Donnelly