Lua丨函数中的可变参数(返回多个参数)~arg的用法

版权声明:欢迎转载,转载请注明出处 https://blog.csdn.net/weixin_38239050/article/details/82466560

可变参数

Lua中可返回多个参数,C#只能返回一个

function test(...)
	print(arg)
	--print(arg[2])
end

test()
test(1)
test(1,2)
test(1,2,3)



>lua -e "io.stdout:setvbuf 'no'" "table.lua" 
table: 003BB0B8
table: 003BB1A8
table: 003BB248
table: 003BB310
>Exit code: 0

arg将我们传递的参数封装成一个表(表内含有输入的参数和所有参数的个数),输出的为该参数的内存地址

将arg定义为arg={...}   便解决了这个问题。此时,这个表里只有输入的参数

function test(...)
	--local arg={...}
	res=0
	for k,v in pairs(arg) do
		res=res+v
	end
	print(res)
end

test()
test(1)
test(1,2)
test(1,2,3)




>lua -e "io.stdout:setvbuf 'no'" "table.lua" 
0
2
5
9
>Exit code: 0
function test(...)
	local arg={...}
	res=0
	for k,v in pairs(arg) do
		res=res+v
	end
	print(res)
end

test()
test(1)
test(1,2)
test(1,2,3)




>lua -e "io.stdout:setvbuf 'no'" "table.lua" 
0
1
3
6
>Exit code: 0

arg的用法

除了上述的可用于遍历,获得表中传入的内容,还可用#arg获得传入参数的个数

同时,#“string”也可取得一个字符串的长度

function test(...)
	local arg={...}
	res=0
	for k,v in pairs(arg) do
		res=res+v
	end
	print(res.."+"..#arg)
end

test()
test(1)
test(1,2)
test(1,2,3)



>lua -e "io.stdout:setvbuf 'no'" "table.lua" 
0+0
1+1
3+2
6+3
>Exit code: 0

猜你喜欢

转载自blog.csdn.net/weixin_38239050/article/details/82466560