Lesson 8 of 10

Inheritance with tables

Goal

Build on the parent and override its method

01

Explanation

Inheritance in Lua is a chain of lookups. The line setmetatable(Warrior, { __index = Player }) means that anything not found in Warrior is looked up in Player. So Lua searches the warrior object itself first, then Warrior, then Player, and that's how the warrior inherits isAlive even though you never wrote it for Warrior.

To override a method, you write a method with the same name in the child class, and Lua finds it before the parent's. If you also want the parent's method to run, call it explicitly with a single dot and pass self along, like this: Player.takeDamage(self, amount). Writing self:takeDamage(amount) instead calls the child's own method over and over until you get a stack overflow error.

Watch out in the constructor. Player.new returns an object whose metatable is Player, and if you don't change it to Warrior, the object stays an ordinary player. The warrior's methods are written, but the lookup never reaches them, and you don't see any error.

02

Your task

Fix Warrior.new(name, hp, armor) so it builds on Player.new and the object it returns belongs to Warrior. Then write Warrior:takeDamage(amount), which subtracts armor from the hit without taking it below zero, then passes it on to the parent's takeDamage.

Checks

6 checks
  1. Warrior.new builds on Player.new
  2. The warrior inherits the parent's methods
  3. Armor reduces the damage from a hit
  4. A hit weaker than the armor neither hurts nor heals
  5. An ordinary player has no armor
  6. Warrior methods belong to warriors alone
main.lua
OutputLua 5.4 (wasmoon)

Loading Lua.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.