generators/iterators, raise/try/except, and slot-based object layout
- VM refactor: resumable CAT_VM_Frame (ip/sp/locals/handlers) - yield/next/generators: calling a yield-function returns a generator - for..in over any iterator, ends on explicit exhaustion status - raise/try/except: structured error values, nearest-handler unwinding - slots: C-declared member layout (offsetof), PyTypeObject/tp_members style - File now exposes path/mode/closed via slots - examples: generators.cat, errors.cat, slots.cat; 40/40 tests
This commit is contained in:
1 parent
52d118211f
commit
3c20496c78
19 files changed
+978
-99
No files matched your search
@@ -0,0 +1,44 @@
|
||||
-- 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()) -- nil: 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)
|
||||
Reference in new issue
Block a user