Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua - Local variable scope in function

I have the following function

function test()

  local function test2()
      print(a)
  end
  local a = 1
  test2()
end

test()

This prints out nil

The following script

local a = 1
function test()

    local function test2()
        print(a)
    end

    test2()
end

test()

prints out 1.

I do not understand this. I thought declaring a local variable makes it valid in its entire block. Since the variable 'a' is declared in the test()-function scope, and the test2()-function is declared in the same scope, why does not test2() have access to test() local variable?

like image 595
spurra Avatar asked Apr 26 '16 15:04

spurra


People also ask

How do local variables work in Lua?

Local variables help you avoid cluttering the global environment with unnecessary names. Moreover, the access to local variables is faster than to global ones. Lua handles local variable declarations as statements. As such, you can write local declarations anywhere you can write a statement.

What is Lua scope?

In Lua, the preferred scope is local which you control by using the local declaration before you define a variable/function. For example: local someVariable. local function someFunction() end.

Are Lua functions global?

In Lua, though we don't have variable data types, we have three types based on the scope of the variable. Global variables − All variables are considered global unless explicitly declared as a local.


2 Answers

test2 has has access to variables which have already been declared. Order matters. So, declare a before test2:

function test()

    local a; -- same scope, declared first

    local function test2()
        print(a);
    end

    a = 1;

    test2(); -- prints 1

end

test();
like image 155
canon Avatar answered Sep 18 '22 06:09

canon


You get nil in the first example because no declaration for a has been seen when a is used and so the compiler declares a to be a global. Setting a right before calling test will work. But it won't if you declare a as local.

like image 40
lhf Avatar answered Sep 19 '22 06:09

lhf