In Programming in Lua (3rd Ed.) by Roberto Ierusalimschy it is stated that
A common idiom in Lua is
local foo = fooThis code creates a local variable,
foo, and initializes it with the value of the global variablefoo. (The localfoobecomes visible only after its declaration.) This idiom is useful when the chunk needs to preserve the original value offooeven if later some other function changes the value of the globalfoo; it also speeds up the access tofoo.
Could someone explain this more in detail and provide a simple example?
At the moment, the only use I can think of for this idiom is to manage local variables (in a given block) that have the same names as global variables, so that the global variable is left unchanged after the block.
An example:
foo = 10
do
local foo = foo
foo = math.log10(foo)
print(foo)
end
print(foo)
this gives:
1
10
But the same could be accomplished without using the idiom at all:
bar = 10
do
local bar = math.log10(bar)
print(bar)
end
print(bar)
that gives the same result. So my explanation doesn't seem to hold.