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

前端 未结 5 1406
囚心锁ツ
囚心锁ツ 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:41

    Lua's function, table, userdata and thread (coroutine) types are passed by reference. The other types are passed by value. Or as some people like to put it; all types are passed by value, but function, table, userdata and thread are reference types.

    string is also a kind of reference type, but is immutable, interned and copy-on-write - it behaves like a value type, but with better performance.

    Here's what's happening:

    local a = 9
    local t = {4,6}
    
    function moda(a)
      a = 10 -- sets 'a', which is a local introduced in the parameter list
    end
    
    function modt(t)
      t[1] = 7 -- modifies the table referred to by the local 't' introduced in the parameter list
      t[2] = 8
    end
    

    Perhaps this will put things into perspective as to why things are the way they are:

    local a = 9
    local t = {4,6}
    
    function moda()
      a = 10 -- modifies the upvalue 'a'
    end
    
    function modt()
      t[1] = 7 -- modifies the table referred to by the upvalue 't'
      t[2] = 8
    end
    
    -- 'moda' and 'modt' are closures already containing 'a' and 't',
    -- so we don't have to pass any parameters to modify those variables
    moda()
    modt()
    print(a)  -- now print 10
    print(t[1]..t[2])  -- still print 78
    

提交回复
热议问题