lua-users home
lua-l archive

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


It's another good case, because x is not used after print(x), it's no longer needed and a smart compiler can mark it as dead to reuse its slot in the current closure.
[[
(not really on the stack which stores insteads references to closure objects having a static size predetermined at compile-time for storing references to the needed upvalues and has slots for holding references to the needed local variables including input parameters, and one slot in upvalues for the reference to the sequence of all return values).
Lua can run without any stack, using a basic chaining of closures. The call stack is then used only when performing native calls to the builtin library. such chaining perfectly emulates the pure-Lua call stack and smplified the memory management. Mixing the native call stack and the Lua call stack creates various integration problems.
]]
It's the role of a compiler to track variable usages accesses in each scope, and discard unneeded variables or variables that are no longer accessed, in order to reduce the memory footprint and properly allocate as few slots as possible in each scope.

Le sam. 1 juin 2019 à 18:50, Gé Weijers <ge@weijers.org> a écrit :
A general observation:

An optimizing implementation of Lua could do variable liveness analysis and reuse stack slots, resulting in the following:

function f(x)
  print(x)
  local y = g() -- this overwrites x, making it collectable
  print(y)
end

I have seen this behavior in compiled languages that use a garbage collector, the compiler translates the code into static single assignment form, and 'x' is considered dead once its value is passed to 'print', so the GC no longer traces it and 'x' disappears. 

PUC's Lua interpreter does not do this but a different implementation (JIT-based?) may well. Assuming the object is reachable until the function returns is hazardous to your health 😕