Call as
Functions.collections.spairs(t, order)
Record it as a dependency named Functions.collections.spairs (accepting the completion does this), then call it by that name.
What it does
Create an iterator over a sorted snapshot of table keys. Default ordering compares keys; a custom order callback receives the original table and two keys. Values are read from the original table when each key is yielded. The legacy iterator ends when the next captured key is nil or false.
Arguments
| Name | Type | What it does |
|---|---|---|
t | table | Table to traverse; keys must be mutually comparable when no custom ordering is supplied. |
order | function | nil | Optional ordering callback called as order(t, leftKey, rightKey). |
Returns
| 1 | function | Iterator yielding a captured key and its current table value, or no values when exhausted. |
|---|
Editions
Built In helpers are registered on every edition. What differs is the game API they read; where one is missing the helper falls back or returns nil with a reason.
It reads no game API directly.
Example
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 falseSource
Functions/collections.lua, line 38. Read only in game; Duplicate makes an editable copy.
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