Any variable that is created for the first time (by using assignment statement variable_name = value) in the body of a function definition is a local variable, and can only be accessed by the statements in the body of the current function definition. Local variables are even not accessible inside the body of a function definition contained in the current function body. For example
f = function x -> y var = 35; f = function u -> v // this f is not the previous f v = u + var; // bad, since var is not defined .... .... end endThe function input and output arguments automatically become local variables of the function. When the function is called, the input arguments receive the values passed by the caller, where the output variable is initialized to null.
The assignment operator = can be used to declare and initialize a local variable, or update the value of an existing variable. The operand on the left side of the = sign is called the lvalue. If the lvalue is an identifier, it must refer to a local variable. If a local variable by that name does not exist yet, a new local variable with this name will be created and initialized. Otherwise the existing variable by that name will be updated. Here we have an example function:
// binary search for target in a list x binsearch = function (x, target) -> index n = #x; left = 1; right = #x; while left < right // round down using floor center = floor(left + (right - left) / 2); if x # center < target right = center; elseif x # center > target left = center + 1; else index = center; return; end end endIt has local variables x, target, index, n, left, right, center, among which x and target are input arguments, index is output argument, and the rest are variables created inside the function body.
When a function definition such as
f = function x -> y ... ... endis executed, the function definition is processed, and the code is compiled to instructions in some internal format. But the local variables do not exist until a call to the function is made. When a function is called, a stack is initialized that contains all the local variables of this function. Different calls to the same function will have different variable stacks and therefore different copies of the local variables.
Upon termination of the function call, all the local variables except for the output argument will cease to exist, the memory they occupy is recycled, and the stack is destroyed. The value of the output argument will be kept and returned to the caller. If the caller chooses to ignore the return value, the Shang interpreter will claim the memory used by the return value - the programmer never needs to worry about `garbage collection'.