# Coroutines & Events

## Coroutines (`castle.co.*`)

Coroutines let you write async sequences without callback hell.

```lua
castle.co.start(function()
  castle.co.wait(1.0)          -- wait 1 second
  print("one second later")

  castle.co.waitUntil(function()
    return someCondition == true
  end)
  print("condition met")
end)
```

### `castle.co.start(fn)`
Starts a coroutine. Runs concurrently with `onUpdate`. Safe to call at module top-level.

### `castle.co.wait(seconds)`
Pauses the coroutine for the given duration.

### `castle.co.waitUntil(conditionFn)`
Pauses until `conditionFn()` returns true (checked each frame).

### `castle.co.waitFor(eventName)`
Pauses until the named coroutine event fires (via `castle.co.fireEvent`). Returns the event data.

```lua
castle.co.start(function()
  local data = castle.co.waitFor("playerScored")
  print("scored: " .. data.points)
end)
```

### `castle.co.fireEvent(eventName, data)`
Fires a coroutine event, waking any coroutines waiting on `castle.co.waitFor`.

```lua
castle.co.fireEvent("playerScored", { points = 10 })
```

### `castle.co.parallel(...fns)`
Runs multiple functions concurrently and waits for **all** to finish.

```lua
castle.co.start(function()
  castle.co.parallel(
    function() castle.co.wait(1) end,
    function() castle.co.wait(2) end
  )
  print("both done after 2s")
end)
```

### `castle.co.race(...fns)`
Runs multiple functions concurrently and returns as soon as **any one** finishes.

```lua
castle.co.start(function()
  castle.co.race(
    function()
      castle.co.wait(3)
      print("timeout")
    end,
    function()
      castle.co.waitUntil(function() return playerWon end)
      print("player won!")
    end
  )
end)
```

---

## Events (`castle.events.*`)

A separate event bus from `castle.co.*`. Use for callback-based subscriptions.

### `castle.events.on(name, handler)`
Subscribes to an event. Returns an unsubscribe function.

```lua
local unsub = castle.events.on("explosion", function(data)
  print("explosion at " .. data.x .. ", " .. data.y)
end)
unsub()  -- unsubscribe later
```

### `castle.events.once(name, handler)`
Subscribes to an event, fires once then auto-unsubscribes.

### `castle.events.emit(name, data)`
Emits an event to all `castle.events.on` listeners.

```lua
castle.events.emit("explosion", { x = 0.1, y = 0.2 })
```

**Note:** `castle.co.fireEvent` and `castle.events.emit` are completely separate buses — they do not trigger each other's listeners.
