I am very new to lua and I would like to understand following behaviour.
When I try to run following recursion function:
local func = function ( n )
if n == 1 then return 1
else return n * func( n - 1 )
end
end
print( func( 5 ) )
The program will fail with error:
lua: main.lua:16: attempt to call a nil value (global 'func')
stack traceback:
main.lua:16: in local 'func'
main.lua:38: in main chunk
[C]: in ?
which is ok, since according to the explanation, local version of func variable is not known yet so it tries to call the global one. But when I delete local keyword, following code works correctly?
func = function ( n )
if n == 1 then return 1
else return n * func( n - 1 )
end
end
print( func( 5 ) )
Program prints 120 as result, but global func was never initialized or used before. How is it possible, that this does not throw error as well? Isn't the second example referencing to global func as it does in the first one?