quote:So if a new local variable is being created for each new fuction call, why is it using the variable of the last fuction call?
One way to look at this is with an analogy to Lua tables. Whenever you see curly braces in Lua code, for example,
you know that a new table will be created when the expression is executed. Subsequent expressions involving Tbl, for example,
won't create a new table. Similarly, the keyword 'function' is your clue that a new function will be created. When such an expression is evaluated, the function is "closed". That's what the following rule refers to.
quote:"Each time a function or local function statement is executed, or a function expression is evaluated, a new function is created."
Calling a function is analagous to accessing an already-constructed table. Since calling a function doesn't involve the keyword 'function', it won't create a new function.
Here's an example:
local A = 10
local function Fnc(B)
return A + B
First, a variable is created and bound to the name 'A', and then a function is created (or "closed") and bound to the name 'Fnc'. When Fnc is called, it is not created again. It does create a new variable for a copy of the argument (here, the value 5) and binds it to the name 'B', but it doesn't create a new variable for A. That way, the value of A persists between function calls.
quote:In my opinion this seems to be working a lot like setter methods in OOP, where the state of a fuction can be stored and changed throughout a program.