> For the complete documentation index, see [llms.txt](https://vypxl.gitbook.io/scar/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://vypxl.gitbook.io/scar/application-structure/spaces.md).

# Spaces

A space is a logical container for [entities](/scar/application-structure/entities.md), [objects](/scar/application-structure/objects.md) and [systems](/scar/application-structure/systems.md). It holds all things for one 'layer' of a [scene](/scar/application-structure/scenes.md). For example, there would be a space for the background, one for the level and one for the UI. Spaces should not interact with other spaces.

[Systems](/scar/application-structure/systems.md),  [entities](/scar/application-structure/entities.md) and [objects](/scar/application-structure/objects.md) can be inserted via the `<<` instance method but not removed. To remove entities, one has to call their `Entity#suicide` method, all dead entities are removed upon the next update. Systems should not be removed.

Spaces have multiple ways to select [entites](/scar/application-structure/entities.md). The `[]` and `[]?` methods can be used for direct access via entity id. Then there is  `each_with`. It is used to get all entities in a space which hold the specified [components](/scar/application-structure/components.md). The call signatures are:

```ruby
each_with(comp_type, &block)
each_with(comp_type, *other_comp_types, &block)
```

Both methods accept a block and yields the found [entity](/scar/application-structure/entities.md) and the [component](/scar/application-structure/components.md) with the type specified in the first parameter.

`comp_type` and `*comp_types` are classes (not instances) which inherit from `Scar::Component`. `comp_types` are not yielded but filtered for. This allows [systems](/scar/application-structure/systems.md) to only process entities with certain components. That way, empty components can also be used as tags.

### Example

```ruby
...
# in app#init
backgroundEntity = Entity.new(...)
playerEntity = Entity.new(...)

self << Scene.new(
    Space.new("level",
        LevelScrollSystem.new,
        backgroundEntity,
        playerEntity z: -1),
    Space.new("ui",
        FpsCounterSystem.new,
        Entity.new(...)
    )
)
```

To see the `each_with` methods in action, please refer to the [systems](/scar/application-structure/systems.md) section.
