Description | Demonstrates the use of Inheritance |
Used on | |
Code |
Animal = {} -- An example table, "Animal"
Animal.name = "Smith" -- a name for our animal
Animal.action = "acts" -- an action to preform
function Animal:act ()
Msg( self.name .. " " .. self.action .. "\n" )
end
-- You can inherit values from a parent, then make changes to your own table...
Bird = {}
table.Inherit( Bird, Animal )
Bird.name = "Polly"
Bird.action = "flies"
-- Or you can set up your own table, then inherit what it's missing!
Dog = { name = "Fido", action = "barks" }
table.Inherit( Dog, Animal )
-- Then, you can use inherited functions and inherited values!
Bird:act()
Dog:act()
Animal:act()
-- Any changes to the table after it has been inherited apply only to that table
Dog.name = "Max" -- Changes dog's name!
Dog:act() -- Dog uses it's new name!
Animal:act() -- No Change!
-- If you change the base class, it does not change the children directly, but each child has a reference to it's parent named BaseClass
Animal.name = "Joe"
Dog:act() -- Dog still uses it's old name, "Max"
Dog.name = Dog.BaseClass.name -- Set the dog's name to it's parent's name
Dog:act() -- Dog uses it's new name from it's parent! |
Output | Polly flies
Fido barks
Smith acts
Max barks
Smith acts
Max barks
Joe barks |