forked from blitmap/lua-snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spairs.lua
executable file
·55 lines (40 loc) · 1.04 KB
/
spairs.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
local tsort = table.sort
local setmeta = setmetatable
require('helpers')
local tkeys = table.keys
local iter =
function (tbl, sort_func)
local keys = tkeys(tbl)
tsort(keys, sort_func)
local x = 0
-- Our iterator function.
-- Upvalues: tbl, keys, and x
local spairs_iterator =
function ()
x = x + 1
return keys[x], tbl[keys[x]]
end
return spairs_iterator
end
return iter
--[[
Example usage:
-- Simple example with only number & string keys.
for k, v in spairs({ 1, 2, [99] = '99', [23] = '23' }) do
print(k, v)
end
print(srep('-', 40))
local whatever =
{
[1] = 'one',
[5] = 'two',
[6] = 'three',
['99'] = 'four',
[{}] = 'five',
[function () end] = 'six'
}
-- Second example.
for k, v in spairs(whatever, function (a, b) return tos(a) < tos(b) end) do
print(k, v)
end
]]