zoukankan      html  css  js  c++  java
  • lua变量作用域

    3.5 – Visibility Rules

    Lua is a lexically scoped language. The scope of a local variable begins at the first statement after its declaration and lasts until the last non-void statement of the innermost block that includes the declaration. Consider the following example:

         x = 10                -- global variable
         do                    -- new block
           local x = x         -- new 'x', with value 10
           print(x)            --> 10
           x = x+1
           do                  -- another block
             local x = x+1     -- another 'x'
             print(x)          --> 12
           end
           print(x)            --> 11
         end
         print(x)              --> 10  (the global one)
    

    Notice that, in a declaration like local x = x, the new x being declared is not in scope yet, and so the second x refers to the outside variable.

    Because of the lexical scoping rules, local variables can be freely accessed by functions defined inside their scope. A local variable used by an inner function is called an upvalue, or external local variable, inside the inner function.

    Notice that each execution of a local statement defines new local variables. Consider the following example:

         a = {}
         local x = 20
         for i=1,10 do
           local y = 0
           a[i] = function () y=y+1; return x+y end
         end
    

    The loop creates ten closures (that is, ten instances of the anonymous function). Each of these closures uses a different y variable, while all of them share the 

  • 相关阅读:
    vuejs 组件通讯
    导出pdf
    css 鼠标选中内容背景色
    console.log() 字体颜色
    使用cross-env解决跨平台设置NODE_ENV的问题
    Visual Studio动态生成版权信息(VS2015,VS2010,VS2008)
    程序员常用工具汇总
    存储过程分页
    oracle全表扫描
    CDM常用命令
  • 原文地址:https://www.cnblogs.com/zhangdongsheng/p/10049603.html
Copyright © 2011-2022 走看看