Lua upvalue definition

Lua is a lexically scoped language.The scope of a local variable begins at the first statement afterits declaration and lasts until the last non-void statementof 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 functionsdefined inside their scope.A local variable used by an inner function is calledan upvalue, or external local variable,inside the inner function.

Notice that each execution of a local statementdefines 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 same x.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值