Lua - 函数中的局部变量范围

spu*_*rra 5 lua scope local-variables

我有以下功能

function test()

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

test()
Run Code Online (Sandbox Code Playgroud)

这打印出零

以下脚本

local a = 1
function test()

    local function test2()
        print(a)
    end

    test2()
end

test()
Run Code Online (Sandbox Code Playgroud)

打印1.

我不明白.我认为声明一个局部变量使它在整个块中有效.由于变量'a'在test() - 函数范围内声明,并且test2() - 函数在同一范围内声明,为什么test2()不能访问test()局部变量?

I a*_*ica 5

test2可以访问已经声明的变量.订单很重要.所以,a在之前声明test2:

function test()

    local a; -- same scope, declared first

    local function test2()
        print(a);
    end

    a = 1;

    test2(); -- prints 1

end

test();
Run Code Online (Sandbox Code Playgroud)

  • "局部变量的范围从声明后的第一个语句开始,一直持续到包含声明的最内层块的最后一个非void语句." - http://www.lua.org/manual/5.3/manual.html#3.5 (6认同)