Skip to content

Instantly share code, notes, and snippets.

@alaurie
Created March 21, 2025 00:13
Show Gist options
  • Save alaurie/3d106fe842752ff379764ff6c80fa814 to your computer and use it in GitHub Desktop.
Save alaurie/3d106fe842752ff379764ff6c80fa814 to your computer and use it in GitHub Desktop.
Lua Wizard
-- Wizard object
Wizard = {}
Wizard.__index = Wizard
-- Add methods
function Wizard.new(name, stamina, intelligence)
local self = setmetatable({}, Wizard)
self.name = name
self._stamina = stamina
self._intelligence = intelligence
self.max_mana = intelligence * 10
self.mana = self.max_mana
self.health = stamina * 100
return self
end
function Wizard:cast_fireball(target)
if self.mana < 50 then
error(self.name .. " cannot cast fireball - insufficient mana.")
end
self.mana = self.mana - 50
target:get_fireballed()
end
function Wizard:is_alive()
return self.health > 0
end
function Wizard:get_fireballed()
local fireball_damage = 200
self.health = self.health - fireball_damage
if self.health < 0 then
self.health = 0
end
end
-- Method to drink a mana potion
function Wizard:drink_mana_potion()
local potion_mana = 100 -- Constant mana restoration value
self.mana = self.mana + potion_mana
if self.mana > self.max_mana then
self.mana = self.max_mana -- Cap mana at max_mana
end
end
-- ToString equivalent for printing wizard status
function Wizard:__tostring()
return "Wizard " .. self.name .. ": Health=" .. self.health .. ", Mana=" .. self.mana
end
-- Example usage
local wizard1 = Wizard.new("Gandalf", 10, 15)
local wizard2 = Wizard.new("Saruman", 8, 12)
print(wizard1) -- Wizard Gandalf: Health=1000, Mana=150
wizard1:cast_fireball(wizard2)
print(wizard1) -- Wizard Gandalf: Health=1000, Mana=100
print(wizard2) -- Wizard Saruman: Health=600, Mana=120
wizard2:drink_mana_potion()
print(wizard2) -- Wizard Saruman: Health=600, Mana=120 (capped at max_mana)
print("Gandalf alive? " .. tostring(wizard1:is_alive())) -- Gandalf alive? true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment