Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between local function myFunction and local myFunction = function()

Tags:

scope

lua

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
like image 509
liver Avatar asked Jun 27 '13 20:06

liver


2 Answers

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
like image 175
hugomg Avatar answered Jan 04 '23 05:01

hugomg


The difference is that according to the manual:

The statement

local function f () body end

translates to

local f; f = function () body end

not to

local f = function () body end

(This only makes a difference when the body of the function contains references to f.)

The main reason is that the scope of a variable (where the variable is visible) starts AFTER the local statement, and if a function was recursive, it would not reference itself, but a previous local or a global named f.

like image 38
Michal Kottman Avatar answered Jan 04 '23 04:01

Michal Kottman