Lesson 7 of 10
A class from a table
- 14 min
- 6 checks
- 3 hints
- Go to task
Goal
Methods, self and the colon
Explanation
Lua has no class keyword. A class is just a table that holds the methods. The line Player.__index = Player lets that table serve as the metatable for its objects: each player is a table holding only its own data, and anything it can't find there, meaning the methods, it looks up in Player. Player.new creates the table and attaches it to the class like this: setmetatable({}, Player).
The colon : is shorthand for a hidden parameter named self. Writing function Player:heal(amount) means function Player.heal(self, amount), and writing hero:heal(10) means hero.heal(hero, 10). That way one method serves every player and knows, through self, which of them called it.
The most common mistake here is writing hero.takeDamage(30) with a single dot. hero never reaches the method, so self becomes 30 and amount becomes nil, and then the error attempt to index a number value (local 'self') shows up inside the method, far away from the line where the mistake really is.
Your task
Write Player.new(name, hp) so it stores name and hp, plus a maxHp equal to hp. Then write the methods heal(amount), which raises health without going over maxHp, and isAlive(), which returns true or false. Finally, fix the takeDamage call in the example.
Checks
6 checks- Player.new creates a player with the given values
- Each player has its own hp
- Every player can reach the class's methods
- heal raises health without going over maxHp
- isAlive tells the living from the dead
- The example runs and prints the player's data