seqlua

view seqlua_ipairs_example.lua @ 19:2fad7f50076b

Added coroutine based filter(func, ...) example to new file seqlua_ipairs_example.lua
author jbe
date Wed Aug 20 12:23:31 2014 +0200 (2014-08-20)
parents
children ed7a82f85e6f
line source
1 require "seqlua"
3 t = {"a", "b", "c"}
5 for i, v in ipairs(t) do
6 print(i, v)
7 end
8 -- prints:
9 -- 1 a
10 -- 2 b
11 -- 3 c
13 function alphabet(from, to)
14 local letter = nil
15 return function()
16 if letter == nil then
17 letter = from
18 elseif letter == to then
19 return nil
20 else
21 letter = string.char(string.byte(letter) + 1)
22 end
23 return letter
24 end
25 end
27 f = alphabet("a", "z")
29 for i, v in ipairs(f) do
30 print(i, v)
31 end
32 -- prints:
33 -- 1 a
34 -- 2 b
35 -- 3 c
36 -- ...
37 -- 25 y
38 -- 26 z
40 c = setmetatable(
41 { iter = alphabet("a", "f") },
42 { __call = function(t) return t.iter() end }
43 )
45 for i, v in ipairs(c) do
46 print(i, v)
47 end
48 -- prints:
49 -- 1 a
50 -- 2 b
51 -- 3 c
52 -- 4 d
53 -- 5 e
54 -- 6 f
56 g = coroutine.wrap(function()
57 coroutine.yield("Alice")
58 coroutine.yield("Bob")
59 for i = 1, 3 do
60 coroutine.yield("Person #" .. tostring(i))
61 end
62 end)
64 for i, v in ipairs(g) do
65 print(i, v)
66 end
67 -- prints:
68 -- 1 Alice
69 -- 2 Bob
70 -- 3 Person #1
71 -- 4 Person #2
72 -- 5 Person #3
74 function filter(f, iter, iter_s, iter_i)
75 return coroutine.wrap(function()
76 for i, v in ipairs(iter, iter_s, iter_i) do f(v) end
77 end)
78 end
80 function filterfunc(v)
81 local type_v = type(v)
82 if type_v == "string" then
83 coroutine.yield(v)
84 elseif type_v == "number" then
85 for i = 1, v do
86 coroutine.yield(true)
87 end
88 end
89 end
91 for v in filter(filterfunc, {"a", "b", 3, "c"}) do
92 print(v)
93 end
94 -- prints:
95 -- a
96 -- b
97 -- true
98 -- true
99 -- true
100 -- c
102 set = {apple = true, banana = true}
103 for i, k, v in ipairs(pairs(set)) do
104 print(i, k, v)
105 end
106 -- prints:
107 -- 1 banana true
108 -- 2 apple true
109 -- (order of "apple" and "banana" may vary)

Impressum / About Us