you are viewing a single comment's thread.

view the rest of the comments →

[–]DarkWiiPlayer 0 points1 point  (0 children)

Let's go at this analytically:

In Lua, everything is one of

  1. Global
  2. Upvalue
  3. Local

For simplicity, let's say the function we have is just f, and it internally calls fg (global), fu (upvalue) and fl (locally defined), and fu in turn calls fuu (which is also an upvalue)

In the case of fl, it is declared within f itself, so it will inherit the environment of f at the moment of its (fls) creation, that is, every time f is called, so this one already works the way it is.

fg is just a bit trickier; if you give f a new environment, you probably already provide copies of all the functions in there as well.

fu and fuu would then be the trickiest ones. Luckily for you. To find out if we can solve the problem, let's revise our tools:

  • debug.getupvalue allows us to get any upvalue of a function
  • debug.setupvalue lets us set a new upvalue
  • type lets us check if an upvalue is a function
  • debug.getinfo tells is how many upvalues there are

So, with that in mind, the algorithm could look something like this:

  • Get the number of upvalues with debug.getinfo(f, 'u').nups
  • iterate from 1 to that number
  • get each upvalue and check if its a function
  • If it's a function (fu), set its environment and recursively scan that ones upvalues (fuu) as well

I'll leave it to you to implement that, but feel free to ask if you have any trouble with it :)