- 变长参数(variable number of arguments)
Lua函数中传递参数可以使用(…)来表示不确定数量的参数。一个函数要访问变长参数,需要借由{…}形式来访问,此时变长参数被转化为了一个数组。
function add(...)
local s = 0
for i,v in ipairs{...} do
s = s + v
end
return s
end
print(add(3, 4, 10, 25, 12)) -- 54
当变长参数中包含nil时,上述的函数计算可能会出问题:
function add(...)
local s = 0
for i,v in ipairs{...} do
s = s + v
end
return s
end
print(add(3, 4, nil, 25, 12)) -- 7
ipairs遍历变长参数时,遇到nil时变终止了。
有两种方法可以避免这个问题:
- 0x00 select函数
function add_select(...)
local s = 0
for i = 1, select('#', ...) do
local arg = select(i, ...)
if (arg ~= nil) then
s = s + arg
end
end
return s
end
print(add_select(3, 4, nil, 25, 12)) -- 44
官方文档:
select (index, ···)
If index is a number, returns all arguments after argument number index; a negative number indexes from the end (-1 is the last argument). Otherwise, index must be the string “#”, and select returns the total number of extra arguments it received.
如果index是数字,返回index对应的参数;-1表示最后一个参数。否则,index必须是字符串“#”,并返回参数的总数。
- 0x01 pairs函数
function add(...)
local s = 0
for i,v in pairs{...} do
if v ~= nil then
s = s + v
end
end
return s
end
print(add(3, 4, nil, 25, 12)) -- 44
ipairs函数和pairs函数之间有什么区别?
先上文档:
ipairs (t)
Returns three values (an iterator function, the table t, and 0) so that the construction
for i,v in ipairs(t) do body end
will iterate over the key–value pairs (1,t[1]), (2,t[2]), …, up to the first nil value.
ipairs将会迭代key-value结构形如(1, t[1]),(2, t[2]), …直到第一个nil
pairs (t)
If t has a metamethod __pairs, calls it with t as argument and returns the first three results from the call.
Otherwise, returns three values: the next function, the table t, and nil, so that the construction
for k,v in pairs(t) do body end
will iterate over all key–value pairs of table t.
pairs将会迭代所有的key-value结构。
See function next for the caveats of modifying the table during its traversal.
总结一下,ipairs与pairs的区别在于两处:
1. 遍历的范围
- ipairs只能用于遍历key为整数,且key从1开始依次递增的key-value;
- pairs可以遍历所有key-value。
2.有序性
- ipairs保证遍历过程以key的顺序进行;
- pairs遍历是以table中存储数据的顺序进行的。
以table存取数据,应尽量将有序的数据与无序的数据分开存储在不同的table中。如果由于项目需求不得不维护一个有序与无序混合的table,而遍历处理时又要求按照顺序进行处理。那么直接通过ipairs和pairs没办法满足需求,这时候需要引入一个的table来保存遍历顺序。(该方法来自《Lua程序设计》第19章)
重新定义一个迭代器,先将待处理table的key值保存到一个临时的sortTable{key1,key2,…}中,然后对其中的元素key进行排序。再按照排序后的sortTable来输出table的key-value数据。
function pairsByKeys(t, f) --~ 其中f为可选参数,用于指定排序顺序。类似C++中的仿函数
local a = {}
for n in pairs(t) do a[#a + 1] = n end
table.sort(a, f)
local i = 0
return function()
i = i + 1
return a[i], t[a[i]]
end
end
--~ 使用上述迭代器:
for k,v in pairsByKeys(inputTable) do
print(k, v)
end