lua-users home
lua-l archive

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


Title: Message
Hello. Lua Newbie here.
 
If I declare a local variable in a function, when does that local variable exist, and when does the initialization happen? In the draft of the book Programming In Lua, there is a function shown below:
function new_counter()
  local count = {v=0}
  return function ()
      %count.v = %count.v + 1
      return %count.v
    end
end
 
Now, from a C programming background, I would expect that the local variable count is created on the stack for each invocation of the function, and destroyed when the function exits. But the description in the book makes it looks like each *reference* held to each function has its own set of locals for the function, which are not initialized on each function invocation. So when are they initialized? When a reference is made to the function? If so, how do you have local variables that get initialized on every invocation of the function? Do you have to assign it to something in addition to the declaration?
 
Please help me understand. Thanks,
 
Curt