What is the difference between local`Function var` and local`var = Function...`?

Asked

Viewed 175 times

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?

2 answers

6

Quoting the manual:

The command

 local function f () corpo end

is translated to

 local f; f = function () corpo end

not to

 local f = function () corpo end

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

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 instructions (statements) can reference previously declared locations, or environment fields (Environment) (global) (_ENV[nomeDaLocal] on the Moon 5.2).

Anyway, a simple functionality.

Types of cases when a function declared in the model local f = function() end 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 Synthesis 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.