Lesson 2 of 10

Entities and components

Goal

An update loop that safely removes the dead

01

Explanation

Everything in a game world is an entity, whether it's a player, a monster, an arrow or a rock. In Lua an entity is a table that holds its components, such as its position in pos, its health in hp and its speed in speed. Not every entity has every component: a rock has a position but no speed, and an arrow flies but has no health. So an entity's behavior comes from the components it has, not from its type.

The update(entities, dt) function is called every frame, just like love.update(dt) in LÖVE. dt is the time in seconds since the previous frame, and when you multiply speed by it, an entity moves at the same rate on a fast machine and on a slow one.

Be careful when you remove dead entities. table.remove(entities, i) shifts everything after i down one slot, so if the loop runs from the start, it skips the entity that moved into the removed one's place, and a dead entity escapes removal. Run the code and look at the wolf. The fix is to loop from the end, for i = #entities, 1, -1, so the shift only affects entries you've already visited.

02

Your task

Fix update(entities, dt) so it increases pos.x by speed * dt for every entity that has a speed, and removes from the same list every entity whose hp is zero or less, while the remaining entities keep their order. An entity without speed doesn't move, and an entity without hp is never removed.

Checks

6 checks
  1. The entity moves forward by speed * dt
  2. An entity without speed stays where it is
  3. A dead entity is removed from the same list
  4. Two dead entities in a row are both removed
  5. The remaining entities keep their order
  6. An entity without hp is not removed
main.lua
OutputLua 5.4 (wasmoon)

Loading Lua.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.