Concepts - BaseClasses
Terms and Definitions
A Class is a collection of Functions and Variables defined in code that acts as a template for Instances.
Examples include The Player, Entities, Gamemodes, VGUI Elements, and more.
An Instance is a copy of a Class that is active in the game. There can be multiple Instances of a single Class active at the same time.
For example: When a prop is spawned from the Sandbox Spawn Menu, the game creates an Instance of the Class prop_physics
.
The Class prop_physics
is only defined in code once but it can be used to create any number of Instances.
To make efficient use of computer hardware, the logic of a Class is not duplicated to each Instance, but instead the Instances all refer back to the same definition in the Class. This is handled via Meta Tables.
A Base Class (or Parent Class) is the set of Functions and Variables that a Class (the Parent Class's Child Class) has by default. The behavior given by (or inherited from) the Parent Class is modified in the Child Class by overriding, replacing, and adding to the Functions and Variables Inherited from the Parent Class. This allows a Class to copy the behavior of another Class without needing to re-create the other Class's logic from scratch. To prevent unnecessary duplication of logic, a Child Class refers to its Parent Class's Meta Table in situations where the Child Class doesn't have an override defined for a Function or Variable.
Note: All Classes must have exactly one (1) Base Class, but can have any number of Child Classes.
How do you use Base Classes?
Example
The following example demonstrates how an Entity can be used as a Base Class for multiple Child Entities.
The Parent Class (sent_parentclass.lua
) handles all of the logic for setting up the Entity's model and physics, as well as the logic behind the Entity's unique behavior. In this case, the unique behavior is that some arbitrary visual effect is enabled before the entity draws and is disabled after it draws. In the Parent Class, this visual effect simply turns the Entity blue.
Because the Child Classes (sent_childclass_1.lua
and sent_childclass_2.lua
) retain the logic of their Base Class (sent_parentclass.lua
), they only need to include a very small amount of code to create different visual effects.
sent_childclass_1.lua
overrides the function to enable the visual effect and replaces the Parent Class's blue color effect with a rainbow color effect.
sent_childclass_2.lua
overrides both the enable and disable functions of the visual effect. They are replaced by functions that make the Entity (Which now looks like a tire) appear to always be rolling, even when stationary.
sent_parentclass.lua
sent_childclass_1.lua
sent_childclass_2.lua
1. The Parent Class
sent_parentclass
(The blue crate)2. The first Child Class
sent_childclass_1
(The rainbow crate)3. The second Child Class
sent_childclass_2
(The spinning tire)