lua-users home
lua-l archive

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


Hi list,
Here's something I can't seem to figure out.  I want to write a
function that generates a particular class of functions.  The function
generator is passed into a constructor where the generator is called.
The trick is that I want the generated function's upvalues to be taken
from the constructor's local variables, but I can't seem to figure out
how to do it.  Here's some example code:


function gen1()
   return function()
       print(val)
   end
end


function constructor(generator)
   local val = 100

   return function()

       local function gen2()
            return function()
               print(val)
            end
       end

       local f1 = gen1()
       local f2 = gen2()

      f1()
      f2()

   end
end


What I get from this code printed in a console is:

nil   //from f1
100  //from f2

What I'd like is f1's val upvalue to refer to constructor's local
variable val.  Is this possible somehow through environments?

thanks,
wes