变量 – 函数/变量范围(通过值或引用?)
我完全困惑于
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能 解决方法
你猜到了,表变量通过引用传递。引用
Lua 5.1 Reference Manual:
所以nil,布尔,数字和字符串通过值。这正好解释了你观察的行为。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |