Ad

What Is The Difference Between Local Function MyFunction And Local MyFunction = Function()

- 1 answer

I know this question seems simple, but I want to know the difference between two ways of creating functions in Lua:

local myFunction = function()
    --code code code
end

Or doing this

local function myFunction()
    --code code code
end
Ad

Answer

The difference happens if the function is recursive. In the first case, the "function" name is not yet in scope inside the function body so any recursive calls actually refer to whatever the version of "myFunction" that was in scope before you defined your local variable (most of the times this meas an empty global variable).

fac = "oldvalue"
local fac = function()
    print(fac) --prints a string
end

To be able to write recursive functions with the assignment pattern, one thing you can do is predeclare the variable:

local myFunction
myFunction = function()
   -- ...
end

Predeclaring variables also happens to be the only way to define a pair of mutually recursive local functions:

local even, odd    
even = function(n) if n == 0 then return true  else return odd(n-1)  end end
odd  = function(n) if n == 0 then return false else return even(n-1) end end
Ad
source: stackoverflow.com
Ad