When you declare a local that local stays around forever till it falls out of scope.
There are several scope types but two common ones are:
- file-level - Throughout whole file after line of (the local’s) declaration.
-
function/method level - Within the body of a function/method after line of (the local’s) declaration.
Example. The following should be considered to be a module saved in a file called “myModule”:
local public = {} -- Two local variables with file-level scope (never destroyed unless module is unloaded). local var1 = 50 local var2 = display.newCircle( 10, 10, 10 ) -- dumb, but hey its an example of syntax... function public.doit1() -- This removes the circle object refered to by var2 and nils var2 so that -- the left-over Lua stub object (a table) cab be garbage collected display.remove( var2 ) var2 = nil -- At this point, var2 exists, but is empty (refers to nothing) -- Now I make a new circle stored in var2 (var2 IS NOT GLOBAL) -- var2 = display.newCircle( 10, 10, 10 ) end function public.doit2() -- Creates two function-level locals -- local var1 = 10 -- This local has the same name as the file-level one. It does not replace it. -- Instead, the new one is used till it goes out of scope local var3 = 12 print( var1, var3 ) -- Always prints: 10 12 -- When this is called, as soon as 'end' is reached, -- the function-level locals: var1, var3 are destroyed. end function public.doit3() This prints the file-level scope var1 print( var1 ) -- Always prints: 50 end return public
Now, doing this:
local myModule = require "myModule" myModule.doit2() myModule.doit3() myModule.doit2() myModule.doit3()
prints:
10 12 50 10 12 50