What is the difference between 'local function var' and 'local var = function ...'?

2

There are two ways to declare a local function directly.

local var = function()
end;

and

local function var()
end

What's the difference between them?

    
asked by anonymous 27.01.2017 / 23:17

2 answers

2

The difference is how the local variable can be accessed by its own value (currently a function).

First you need to know that the declaration of a local variable is not available in its entire scope and can duplicate, without problems. The following statements can reference previously declared locations, or environment (global) fields ( _ENV[nomeDaLocal] on Lua 5.2).

Finally, a simple feature.

Case types when a function declared in the local f = function() end model tries to access it using f , but fails:

# 1

local f = function()
    print(f) -- nil, mas deveria ser a função
end          -- nessa local f.

f()

# 2

local f = 0;

local f = function()
    print(f) -- 0
end

f()

# 3

f = 0;

local f = function()
    print(f) -- 0 também
end

f()

The special syntax local function f() end creates a local variable with the name f , and a function for it, a function that pulls its presence.

# 1

local function f()
    print(f) -- ok
end

# 2

local f;

local function f()
    print(f) -- ok
end
    
14.02.2017 / 20:54
6

Quoting the manual :

The command

 local function f () corpo end

is translated to

 local f; f = function () corpo end

Not for

 local f = function () corpo end

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

    
28.01.2017 / 01:57