table.Inherit

From GMod Wiki

Revision as of 12:31, 26 September 2009 by Lexi (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
Function
Syntax table.Inherit( Table child, Table parent )
Where is this used?
Description:
Causes one table (child) to inherit the contents of another table (parent)
Returns: Table child
Part of Library: Table
Realm: NewerShared.png
BBCode Link: [b][url=http://wiki.garrysmod.com/?title=Table.Inherit]Table.Inherit [img]http://wiki.garrysmod.com/favicon.ico[/img][/url][/b]



Example

DescriptionDemonstrates the use of Inheritance
Used onNewerShared.png
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!
OutputPolly flies

Fido barks
Smith acts
Max barks
Smith acts
Max barks

Joe barks


Additional Notes

See Also

Personal tools
Namespaces
Variants
Actions
Navigation
Lua Scripting
Functions
Hooks
Toolbox