Function/variable scope (pass by value or reference?)

前端 未结 5 1416
囚心锁ツ
囚心锁ツ 2020-12-08 02:22

I\'m completely confused by Lua\'s variable scoping and function argument passing (value or reference).

See the code below:

local a          


        
5条回答
  •  臣服心动
    2020-12-08 02:45

    I won't repeat what has already been said on Bas Bossink and jA_cOp's answers about reference types, but:

    -- since it's define local, should not have func scope

    This is incorrect. Variables in Lua are lexically scoped, meaning they are defined in a block of code and all its nested blocks.
    What local does is create a new variable that is limited to the block where the statement is, a block being either the body of a function, a "level of indentation" or a file.

    This means whenever you make a reference to a variable, Lua will "scan upwards" until it finds a block of code in which that variable is declared local, defaulting to global scope if there is no such declaration.

    In this case, a and t are being declared local but the declaration is in global scope, so a and t are global; or at most, they are local to the current file.

    They are then not being redeclared local inside the functions, but they are declared as parameters, which has the same effect. Had they not been function parameters, any reference inside the function bodies would still refer to the variables outside.

    There's a Scope Tutorial on lua-users.org with some examples that may help you more than my attempt at an explanation. Programming in Lua's section on the subject is also a good read.

提交回复
热议问题