调用方式
Functions.collections.spairs(t, order)
将其记录为名为 Functions.collections.spairs 的依赖项(接受自动补全即可完成),然后按该名称调用。
作用
创建一个遍历表键排序快照的迭代器。默认按键排序;自定义排序回调会收到原始表和两个键。每次产出一个键时,值从原始表中读取。当下一个捕获的键为 nil 或 false 时,旧版迭代器结束。
参数
| 名称 | 类型 | 作用 |
|---|---|---|
t | table | 要遍历的表;未提供自定义排序时,键之间必须可以相互比较。 |
order | function | nil | 可选的排序回调,以 order(t, leftKey, rightKey) 的形式调用。 |
返回值
| 1 | function | 产出一个捕获的键及其当前表值的迭代器;耗尽时不产出任何值。 |
|---|
版本
内置辅助函数在每个版本上都会注册。不同的是它们读取的游戏 API;某个 API 缺失时,辅助函数会改用后备方案,或返回 nil 并附上原因。
它不直接读取任何游戏 API。
示例
local stacks = { Frost = 2, Arcane = 1, Fire = 3 }
local byCount = function(t, a, b) return t[a] > t[b] end
for school in Functions.collections.spairs(stacks, byCount) do
return school == "Fire"
end
return false源码
Functions/collections.lua,第 38 行。在游戏中为只读;“复制”会生成一份可编辑的副本。
Functions.collections.spairs(t, order)
-- collect the keys
local keys = {}
for k in pairs(t) do keys[#keys+1] = k end
-- if order function given, sort by it by passing the table and keys a, b,
-- otherwise just sort the keys
if order then
table.sort(keys, function(a,b) return order(t, a, b) end)
else
table.sort(keys)
end
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end