1.函数的参数数目
printResult = ""
function print(...)
for i, v in ipairs(arg) do
printResult = printResult .. tostring(v).."\t"
end
printResult = printResult .. "\n"
end
其中(…)三个点表示可变长度的参数, 当函数调用时,所有参数被转变为一个表,便是隐藏的参数被称作arg。此外arg还包含一个值n,指的是实际传入参数的数目。
指定接收参数
local _, x = string.find(s,p)
--now use 'x',接收第二个参数
或者使用select函数对返回参数进行选择:
print(string.find("hello hello", "hel")) -->6 9
print(select(1,string.find("hello hello", "hel")) -->6
print(select(2,string.find("hello hello", "hel")) -->9
以上所示的select函数的输入便是一个固定的参数值、以及加上剩下的数目不固定的参数值。
举个例子如下:
function g(a,b,...) end
-CALL PARAMETERS
-g(3) a=3,b=bil,arg={n=0}
-g(3,4) a=3,b=4, arg={n=0}
-g(3,4,5,8) a=3,b=4,arg={5,8;n=2}
select函数的定义如下:
function select (n,...)
return arg[n]
end
使用unpack函数传参:
function fwrite(fmt, ...)
return io.write(string.format(fmt, unpack(arg)))
end