-- Chapter 27 example: Character class.

local Character = {}
Character.__index = Character

function Character.new(name, hp)
    local self = setmetatable({}, Character)
    self.name = name
    self.hp = hp
    self.max_hp = hp
    return self
end

function Character:takeDamage(amount)
    self.hp = self.hp - amount
    if self.hp < 0 then self.hp = 0 end
end

function Character:heal(amount)
    self.hp = self.hp + amount
    if self.hp > self.max_hp then self.hp = self.max_hp end
end

function Character:isAlive()
    return self.hp > 0
end

local c = Character.new("Keiko", 100)
c:takeDamage(30)
print(c.hp)           -- 70
c:heal(50)
print(c.hp)           -- 100  (capped)
print(c:isAlive())    -- true
