Doing inheritance in Lua

Posted by Nick Gammon on Sun 23 Apr 2006 09:36 PM — 1 posts, 5,293 views.

Australia Forum Administrator #0
The example code below, based on ideas in the Lua book, show how you might use Lua to implement an object-oriented hierarchy of inherited attributes. This example shows how you might set up an inheritance based on:

  • All objects in the MUD
  • A particular type of object: weapons
  • Sub-class of weapons: swords
  • A particular sword prototype
  • An instance of that sword that is actually created for the player



objects = {}

-- see Lua book section 16.2

function objects:new (o)
  o = o or {}
  setmetatable (o, self)
  self.__index = self
  return o
end -- objects:new 

-- generic weapons table

weapons = objects:new {
  equipable = true,
  kind = "weapon",
  stack_limit = 1,  -- max in inventory slot
  }  -- end weapon

-- generic sword

weapons.sword = weapons:new {
  weapon_type = "cutting",
  } -- end sword


-- particular sword

weapons.newbie_sword = weapons.sword:new {
  damage_low = 3,  -- hits 3 to 6 damage
  damage_high = 6,
  speed = 2,    -- every 2 seconds
  desc = "Newbie Sword",
  long_desc = "You see a decrepit sword lying here",
  } -- end newbie_sword 

-- a particular instance of a sword

instances = {}

instances.a_sword_instance = weapons.newbie_sword:new ()



This technique adds a function to the object table that effectively creates a new table with an existing one as the base, and adds an __index item to the new object, so that when you attempt to query a field, looks up its parent for it, if it isn't in the base object.

Now we will look at extracting the various fields from the particular instance of the sword, which itself has no member fields.


print ("desc =", instances.a_sword_instance.desc)
print ("damage_low =", instances.a_sword_instance.damage_low)
print ("weapon_type  =", instances.a_sword_instance.weapon_type)
print ("equipable =", instances.a_sword_instance.equipable)

... output is ...


desc = Newbie Sword
damage_low = 3
weapon_type  = cutting
equipable = true




It all seems to extract out nicely.