Coroutine-based game behavior
Save as enemy-turns.atom. Each resume advances one behavior through a single frame. Cancellation runs the cleanup of the suspended coroutine.
use task
func patrol(entity):
try:
for frame in 0..10:
entity.x += entity.speed
yield entity.x
return entity.x
finally:
entity.active = false
enemy = {x = 0, speed = 2, active = true}
behavior = create(coroutine, patrol, enemy)
for frame in 0..3:
print('frame {frame}, x = {task.resume(behavior)}')
task.cancel(behavior)
assert(not enemy.active and task.status(behavior) == 'cancelled')