BreezyMain
BreezyMain

Reputation: 163

Why a global function with recursion can directly be defined, but a local function can't

a local function that directly define recursive functionality is wrong:

local fact = function (n)
  if n <= 1 then return 1
  else return n * fact(n - 1) end -- looking up global function
end

but for a global function, suck defination is ok:

function fact(n)
  if n <= 1 then return 1
  else return n * fact(n - 1) end -- correctly called itself
end

Why there has such difference? Global variables' scope is unbounded?(obvious not)

Upvotes: 0

Views: 59

Answers (1)

DarkWiiPlayer
DarkWiiPlayer

Reputation: 7066

That's actually incorrect; you can define local functions recursively:

local function fact(n)
   if n <= 1 then
      return 1
   else
      return n * fact(n -1)
   end
end

However, this doesn't work with anonymous functions:

local fact = function(n)
   -- ...
end

Because the right-hand-side of the assignment is evaluated before the left-hand-side. To make this work, you'd have to first declare the local:

local fact
fact = function(n)
   -- ...
end

But this problem doesn't affect the local function name() syntax as you described. As Egor pointed out, the problem with your code is that you don't close the if block with a corresponding end.

Upvotes: 2

Related Questions