【问题标题】:Lua - Local variable scope in functionLua - 函数中的局部变量范围
【发布时间】:2016-04-26 15:58:14
【问题描述】:

我有以下功能

function test()

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

test()

这打印出 nil

以下脚本

local a = 1
function test()

    local function test2()
        print(a)
    end

    test2()
end

test()

打印出 1。

我不明白这一点。我认为声明一个局部变量使其在整个块中有效。既然变量 'a' 是在 test()-function 范围内声明的,而 test2()--function 是在同一个范围内声明的,为什么 test2() 不能访问 test() 局部变量?

【问题讨论】:

  • lua 不是 javascript,它不会“提升”变量。

标签: scope lua local-variables


【解决方案1】:

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

function test()

    local a; -- same scope, declared first

    local function test2()
        print(a);
    end

    a = 1;

    test2(); -- prints 1

end

test();

【讨论】:

  • "局部变量的范围从其声明后的第一条语句开始,一直持续到包含该声明的最里面块的最后一个非 void 语句。" -- lua.org/manual/5.3/manual.html#3.5
  • 实际上,只有'local a'部分需要先出现,因为分配给它的值可能还不知道。所以,赋值仍然可以遵循内部函数的定义。
  • @tonypdmtr 没错,虽然这就是我说的原因,“声明”
【解决方案2】:

在第一个示例中您得到 nil,因为在使用 a 时没有看到 a 的声明,因此编译器将 a 声明为全局变量。在调用test 之前设置a 将起作用。但如果您将 a 声明为本地,则不会。

【讨论】:

    猜你喜欢
    • 2017-03-05
    • 2018-08-25
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 2013-05-10
    • 2014-07-14
    相关资源
    最近更新 更多