我完全困惑Lua的變量作用域和函數參數傳遞(值或引用)。函數/變量作用域(傳遞值或引用?)
請參見下面的代碼:
local a = 9 -- since it's define local, should not have func scope
local t = {4,6} -- since it's define local, should not have func scope
function moda(a)
a = 10 -- creates a global var?
end
function modt(t)
t[1] = 7 -- create a global var?
t[2] = 8
end
moda(a)
modt(t)
print(a) -- print 9 (function does not modify the parent variable)
print(t[1]..t[2]) -- print 78 (some how modt is modifying the parent t var)
因此,這種行爲完全混淆了我。
這是否意味着通過 引用傳遞給函數 ,而不是看重的表變量?
如何創建全局變量 與已定義的 局部變量衝突?
- 爲什麼
modt
能夠 修改表尚未moda
不能 修改一個變量?
- 爲什麼
這與通過引用略有不同。 (看我的答案)。特別是'function(x)x = {} end'的行爲是不同的。 – 2011-12-02 08:32:03
所有東西都是按值傳遞的,通過某些類型(表,函數,線程和(完整)用戶數據值)是引用。這些引用是按值傳遞的。 – Ethan 2015-10-30 01:10:16