lua-users home
lua-l archive

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

I am trying to understand the implementation of Lua. I am refereing to
this document for
details[]. I have
a question regarding the implementation of upValues as done for
function closures.
Takking the example given in the document:
function add(x)
  return function(y)
   	 return x+y


As explained further in the document, the reference to the variable x
is stored in an upValue which can either point to the stack (when
referenced from within the inner function) or can point to itself
(when referenced from the creator of the closure).

Consider the following flow of actions:
1.Take the creation of the closure add2
2.function add is called with the parameter 2
3.within the inner function of the add function, the reference to the
parameter x is on the stack (x is actually 2 on the stack now)
4.An inner function is returned to the caller which contains a
reference to the x on the stack. Of course, this reference to the x on
the stack will no longer exist, as we have returned from the function
call and hence the stack frame will not be valid
5.Now, this reference to the variable / value x on the stack degrades
(if you might allow that expression) to an upValue wherein the x now
lies within the upValue.
6.The caller now has no problems in accessing the value of x.

In this scenario, the question I have is - when does the value x
change from being a variable on the stack to a value within the
upValue. How is this transition done transparent to the caller. If you
think this is too basic a question and I ought to figure this out,
please let me know the source file and I shall try to figure it out.
This question popped because of this sentence in the document
<quote>Unlike its inner functions, the function that declares the
variable accesses it as it accesses its own local variables: directly
in the stack.[pg:9]</quote>. I wanted to understand if this is access
is when the closure is being created or when the creator was accessing
the inner function.

Thank you for your help