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,它们所指向的内容都是一样的)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值