Lua - Local scope variable in function

I have the following function

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

Prints nil

Next script

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

prints 1.

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

+5
source share
2 answers

test2 has access to already declared variables. Questions for the order. 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() 
+4
source

In the first example, you get zero because when using a there was no declaration for a , so the compiler declares a global. Setting a right before calling test will work. But this will not happen if you declare a as local.

+2
source

Source: https://habr.com/ru/post/1247972/


All Articles