- delete the nil type; catscript has no nil and no null - add the empty object (Object with no members), exposed as the global 'empty'; it is a shared immutable singleton - 'nil' is no longer a keyword: it is an undefined global, which raises - undefined global -> error (consistent with a missing attribute) - only 'false' is falsy (numbers/objects are truthy); booleans kept - OP_NIL -> OP_EMPTY; compiler, VM, stdlib, toml, ffi, generator, file, list, selector, value all migrated - rename the table type to Object - std/ front-end and examples/tests migrated to 'empty' - 84/84 tests
45 lines
804 B
Plaintext
45 lines
804 B
Plaintext
-- examples/generators.cat -- generators, iterators, yield, for..in.
|
|
|
|
-- a generator: calling it returns a generator, not a value
|
|
function count_up(n)
|
|
local i = 1
|
|
while i <= n do
|
|
yield i
|
|
i = i + 1
|
|
end
|
|
end
|
|
|
|
print("type:", type(count_up(3)))
|
|
|
|
-- manual iteration with next
|
|
local g = count_up(3)
|
|
print("next:", g:next())
|
|
print("next:", g:next())
|
|
print("next:", g:next())
|
|
print("next:", g:next()) -- empty: exhausted
|
|
|
|
-- for..in drives any iterator automatically
|
|
local sum = 0
|
|
for x in count_up(5) do
|
|
sum = sum + x
|
|
end
|
|
print("sum 1..5 =", sum)
|
|
|
|
-- infinite generator + take: lazy, stopped by break
|
|
function naturals()
|
|
local i = 0
|
|
while true do
|
|
yield i
|
|
i = i + 1
|
|
end
|
|
end
|
|
|
|
local taken = 0
|
|
for x in naturals() do
|
|
if x >= 3 then
|
|
break
|
|
end
|
|
taken = taken + 1
|
|
end
|
|
print("taken < 3:", taken)
|