Lua中的值传递和引用传递
老规矩,直接代码
值传递
-- 例1 a = 1 b = a b = 2 print("a ==",a) -- 输出:a == 1 -- 例2 a = "this is str" b = a b = "this is not str" print("a ==",a) -- 输出:a == this is str -- 例3 function fun1(a) a = 2 end b = 1 fun1(b) print("b ==",b) -- 输出:b == 1 -- 例4 function fun1() print("this is fun1") end function fun2() print("this is fun2") end a = fun1 b = a a = fun2 a() b() --[[ 输出:this is fun2 this is fun1 ]] -- 例5 a = {"您好","Hello"} b = a[1] a[1] = "非常好" print("b == ",b) -- 输出:b == 您好
引用传递
-- 例6 a = {1,2} b = a a = {"q","w"} for k,v in pairs(b) do print(k,v) end -- [[输出:1 q -- 2 w
从上面的例子结果得出:
-
例子1到5都是值传递,只有例子6是引出传递 只有参数是table的时候是引用传递(相当于一个指针a将地址传给指针b,它们所指向的内容都是一样的)