How are upvalues ​​calculated in Lua nested functions?

With the lua code block like this:

local a, b function fA () print(a) function fB () print(b) end end 

How many upvalues ​​fA exactly has 1 or 2?

+4
source share
2 answers

By definition, all external local variables used in a function are considered upvalues. As already mentioned, Lua 5.2 also has a hidden up value for the environment if the function uses global variables.

You can read the bytecode generated for your code with luac -l -l .

What may confuse you is the definition of fB in the body of fA . Recall that function fB () print(b) end is just sugar for fB = function () print(b) end . When you do this, it is clear that b used in fA , and also that you are assigning the global variable fB . Therefore, you will get 3 upvalues ​​for fA in Lua 5.2. (Using print also implies that fA uses global variables.) If you use local function fB ... and delete print , you will see that fA uses 2 upvalues ​​in both 5.1 and 5.2.

+4
source

Implementation defined; it can be one or two. Or three (one value for the environment). You do not know, and you will never have to care.

+2
source

Source: https://habr.com/ru/post/1498540/


All Articles