Files
catscript/examples/generators.cat
T
Minus 6f6f444beb selectors: a.b sends with self, a::b without; drop a:b
The `.` and `::` selectors swap meaning and `a:b` is removed, so every
access is one of:

  a.b          read the member
  a.b(args)    call the member WITH a as self
  a::b         static read (no self)
  a::b(args)   call the member WITHOUT self

- compiler: postfix `.` emits CALLMETHOD (with self) when followed by
  `(`, else GETATTR; `::` emits GETATTR + CALL (no self); the `:` form
  is gone (with a helpful error suggesting `.`/`::`).
- `:` remains only for type hints (local x : int), unchanged.
- ffi: `lib.func(...)` (with self) and `ffi::load(...)` (no self); the
  native loaders no longer skip a receiver.
- file: `File::open` is static, so cm_open reads args[0]/args[1].
- lexer: fix cat_lexer_kind_name, whose table had drifted from the enum
  (missing `nil`), mislabelling tokens.
- self-hosted parser (std/lang/parser.cat): `.name(` -> method (self),
  `::name(` -> call (no self); compiler/checker unchanged.
- tools/migrate_selectors.py: one-pass migration of the call forms.
- regenerated std/glfw and std/vulkan; migrated examples/tests/std and
  the README; new tests/selectors.cat (130 green).

Verified live: GLFW window + Vulkan device still work; `a:b` now errors.
2026-11-17 18:55:18 +00:00

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)