Garry's Mod Wiki

Revision Difference

Meta_Tables#568315

<cat>Dev.Lua</cat> # MetaTables Meta tables allow you to add functions to all classes in the game at the same time. For example, adding a function to "Entity" meta table like so: ``` local meta = FindMetaTable( "Entity" ) function meta:ResetHealth() self:SetHealth( self:GetMaxHealth() ) end ``` Will allow you to use it on ALL entities like so: ``` local ply = Entity( 1 ) -- Gets the first player on the server ply:ResetHealth() -- We can call this function on any entity, including a player or an NPC. ``` However adding a function like this: ``` local ply = Entity( 1 ) function ply:ResetHealth() self:SetHealth( self:GetMaxHealth() ) end ``` Will not allow you to use that function on any other entity BUT <page>Global.Entity</page>( 1 ) A list of type meta tables that can be retrieved with <page>Global.FindMetaTable</page> can be found on <page>Enums/TYPE</page>. ⤶ # Derived Metatables⤶ ⤶ In GMod, any `C` class that is derived from another has the field `MetaBaseClass` defined in the metatable, which points at the derived metatable.⤶ An example for this would be:⤶ ```⤶ print(Player(2), Entity(1):GetActiveWeapon().MetaName, Entity(1):GetActiveWeapon().MetaBaseClass.MetaName)⤶ Player [1][Bot01] Weapon Entity⤶ ```⤶ ⤶ <validate>⤶ It seems like this was once intended to allow a class to have a chain of derived classes (example: `SpecialWeapon` -> `Weapon` -> `Entity`), though it was never completed?⤶ </validate>