Home Global and local recursive functions in lua
Reply: 0

Global and local recursive functions in lua

user1112
1#
user1112 Published in July 17, 2018, 7:49 am

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?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.353101 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO