This repository has been archived by the owner on Dec 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
range.lua
executable file
·79 lines (61 loc) · 1.54 KB
/
range.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env lua
local setmeta = setmetatable
local cyield = coroutine.yield
local cresume = coroutine.resume
local ccreate = coroutine.create
local select = select
module('range')
local count =
function (i, to, inc)
while i ~= to do
i = i + inc
-- should return two values for
-- some_table[i] = i usage
cyield(i, i)
end
end
-- our range() example separates the arg handling of
-- the function from the yielding coroutine body (count())
iter =
function (i, to, inc)
if not to then
to = i
i = to == 0 or (to > 0 and 1 or -1)
end
inc = inc or (i < to and 1 or -1)
local co = ccreate(count)
return
function () -- iterator
return select(2, cresume(co, i - 1, to, inc)) -- select past the status
end
-- The above lines up to ccreate() could instead be written like so:
-- return cwrap(function () count(i - 1, to, inc) end)
-- coroutine.wrap() turns yielding functions into iterators (roughly)
end
-- require('range') range() -> iter()
return setmeta(_M, { __call = function (_, ...) return iter(...) end })
--[[
-- Usage:
require('range')
for i in range(10) do
print(i)
end
debug.setmetatable(
function () end,
{
__index =
{
collect =
function (...)
local tmp = {}
for k, v in ... do
tmp[k] = v
end
return tmp
end
}
}
)
-- it's that easy. :p
local some_table = range(3, 243, 9):collect()
]]