功能/变量范围(通过值还是引用?) [英] Function/variable scope (pass by value or reference?)
问题描述
我对 Lua 的变量作用域和函数参数传递(值或引用)完全感到困惑. /p>
请参见下面的代码:
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
无法 修改变量?
- 为什么
您猜对了,表变量是通过引用传递的.引用 Lua 5.1参考手册:
Lua中有八种基本类型:nil,布尔值,数字,字符串,函数,userdata,线程和表. ....
表,函数,线程和(完整)用户数据值是对象:变量实际上并不包含这些值,而只是对其的引用.赋值,参数传递和函数返回始终会操纵对此类值的引用;这些操作并不意味着任何形式的复制.
因此,零,布尔值,数字和字符串按值传递.这正好说明了您观察到的行为.
I'm completely confused by Lua's variable scoping and function argument passing (value or reference).
See the code below:
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)
As such, this behavior completely confuses me.
Does this mean that table variables are passed to the function by reference and not value?
How is the global variable creation conflicting with the already define local variable?
- Why is
modt
able to modify the table yetmoda
is not able to modify the a variable?
- Why is
You guessed right, table variables are passed by reference. Citing Lua 5.1 Reference Manual:
There are eight basic types in Lua: nil, boolean, number, string, function, userdata, thread, and table. ....
Tables, functions, threads, and (full) userdata values are objects: variables do not actually contain these values, only references to them. Assignment, parameter passing, and function returns always manipulate references to such values; these operations do not imply any kind of copy.
So nil, booleans, numbers and strings are passed by value. This exactly explains the behavior you observe.
这篇关于功能/变量范围(通过值还是引用?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!