变量 – 函数/变量范围(通过值或引用?)

我完全困惑于 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)

因此,这种行为完全使我困惑。

>这意味着表变量
被传递给函数by
参考而不是价值?
>如何创建全局变量
与已定义的冲突
局部变量?

>为什么是modt能
修改表但moda不能
修改一个变量?

解决方法

你猜到了,表变量通过引用传递。引用 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.

所以nil,布尔,数字和字符串通过值。这正好解释了你观察的行为。

相关文章

1.github代码实践源代码是lua脚本语言,下载th之后运行thmai...
此文为搬运帖,原帖地址https://www.cnblogs.com/zwywilliam/...
Rime输入法通过定义lua文件,可以实现获取当前时间日期的功能...
localfunctiongenerate_action(params)localscale_action=cc...
2022年1月11日13:57:45 官方:https://opm.openresty.org/官...
在Lua中的table(表),就像c#中的HashMap(哈希表),key和...