给定一个像
...
一样的可变参数1, 2, 3, nil, 5
,我想编写一个函数reverse
,这样reverse(...)
返回可变参数5, nil, 3, 2, 1
。
使用临时表:
local function reverse(...)
local n = select("#", ...)
local t = {...}
-- Reverse the table
for i = 1, n/2 do
local j = n - i + 1
t[i], t[j] = t[j], t[i]
end
return unpack(t, 1, n)
end
或者使用辅助函数来选择第
n
个元素,将其添加到新的 vararg 中,然后递归直到 n = 0
:
local function h(n, ...)
if n == 0 then return end
return select(n, ...), h(n - 1, ...)
end
local function reverse(...)
return h(select("#", ...), ...)
end