This article is the documentation for the game "Team Fortress 2". Click here to go to the main page of the development documents.

Team Fortress 2/Scripting/Script Functions: Difference between revisions

From Valve Developer Community
Jump to navigation Jump to search
(→‎Methods: Change the StunPlayer note)
 
(348 intermediate revisions by 24 users not shown)
Line 1: Line 1:
{{Language subpage}} {{toc-right}}
{{LanguageBar}}
{{TF2 topicon|docs}}
{{toc-right}}
{{sq}} This list contains the engine-related Squirrel classes, functions and variables available for [[VScript]] in {{tf2|4|}}


{{sq}} This list contains the engine-related Squirrel classes, functions and variables available for [[VScript]] in {{game name|name=Team Fortress 2}}.  
The official documentation can be printed in the console by setting <code>developer</code> to non-zero, loading a map, and executing <code>script_help</code>. However, this documentation does not list everything, requiring them to be found by other means instead.


The official documentation can be printed in the console by setting <code>developer</code> to non-zero, loading a map, and executing <code>script_help</code>. However, this documentation is very incomplete and most methods are not listed, requiring them to be found by other means instead.
{{tip|[https://discord.com/invite/tf2maps TF2Maps.net Discord] has a dedicated VScript channel, which is a useful place to ask for help from other people.}}
 
{{tip|Tutorial on setting up Visual Studio Code (VSCode), including auto-completing of VScript functions, can be [[Setting_Up_VScript_in_Visual_Studio_Code|found here]].}}
{{ModernWarning|This page is still work-in-progress, many functions lack documentation and testing.}}
{{ModernNote|Most of these functions were dumped externally as they are not exposed by normal means. For these functions, the return is unknown and the arguments may not be fully correct.}}
{{ModernTip|Tutorial on setting up Visual Studio Code (VSCode), including auto-completing of VScript functions, can be [[Setting_Up_VScript_in_Visual_Studio_Code|found here]].}}
 
{| class = "standard-table" style = "width:40%"
! {{todo}} TODO TABLE {{todo}}
|-
| #1 {{todo|Names for function sigs's params, since params are mysterious magical properties otherwise.}}
|-
| #2 {{todo|Script debug functions have no info other than their names!}}
|-
| #3 {{todo|Consolidate script function subpages from {{l4d2}} together into a generic page that describes both {{tf2}} and {{l4d2}}, including any differences both branches have. E.g. [[Left 4 Dead 2/Script Functions/TraceLine|TraceLine]], [[Left 4 Dead 2/Script Functions/ClientPrint|ClientPrint]]...}}
|}


== Instances ==
== Instances ==
Line 25: Line 15:
! Description
! Description
|-
|-
|<code>Convars</code>
| <code>Convars</code>
|<code>[[#Convars|Convars]]</code>
| <code>[[#Convars|Convars ]]</code>
|Provides an interface to read and change the values of console variables.
| Provides an interface to read and change the values of console variables.
|-
|-
|<code>Entities</code>
| <code>Entities</code>
|<code>[[#CEntities|CEntities]]</code>
| <code>[[#CEntities|CEntities ]]</code>
|Provides access to currently spawned entities.
| Provides access to currently spawned entities.
|-
|-
|<code>EntityOutputs</code>
| <code>EntityOutputs</code>
|<code>[[#CScriptEntityOutputs|CScriptEntityOutputs]]</code>
| <code>[[#CScriptEntityOutputs|CScriptEntityOutputs ]]</code>
|Allows manipulation of entity output data
| Allows manipulation of entity output data.
|-
|-
|<code>NavMesh</code>
| <code>NavMesh</code>
|<code>[[#CNavMesh|CNavMesh]]</code>
| <code>[[#CNavMesh|CNavMesh ]]</code>
|Provides access to the maps NavMesh and NavAreas.
| Provides access to the maps NavMesh and NavAreas.
|-
|-
|<code>NetProps</code>
| <code>NetProps</code>
|<code>[[#CNetPropManager|CNetPropManager]]</code>
| <code>[[#CNetPropManager|CNetPropManager ]]</code>
|Allows reading and updating the network properties of an entity.
| Allows reading and updating the network properties of an entity.
|-
|-
|<code>PlayerVoiceListener</code>
| <code>PlayerVoiceListener</code>
|<code>[[#PlayerVoiceListener|PlayerVoiceListener]]</code>
| <code>[[#CPlayerVoiceListener|CPlayerVoiceListener ↓]]</code>
|Tracks if any player is using voice and for how long.
| Tracks if any player is using voice and for how long.
|}
|}


Line 56: Line 46:
! Value / Description
! Value / Description
|-
|-
|<code>Constants</code>
| <code>__FILE__</code>
|table
| string
| Enumerations for various function arguments or netprops. See [[Team_Fortress_2/Scripting/Script_Functions/Constants|this page]] for the list.
| File name of the currently executing script.
|-
|-
|<code>Documentation</code>
| <code>__LINE__</code>
|table
| integer
| Line number of the currently executing code.
|-
| <code>[[Team_Fortress_2/Scripting/Script_Functions/Constants|Constants]]</code>
| table
| Enumerations for various function arguments or netprops.
|-
| <code>Documentation</code>
| table
| Contains the printed strings from the <code>script_help</code> command.
| Contains the printed strings from the <code>script_help</code> command.
|-
|-
|<code>GameEventCallbacks</code>
| <code>GameEventCallbacks</code>
|table
| table
| Table of registered game event callbacks.
| Table of registered game event callbacks.
|-
|-
|<code>print_indent</code>
| <code>print_indent</code>
|integer
| integer
| 0. Spaces to indent prints by, except ones from <code>realPrint</code>.
| 0. Spaces to indent prints by, except ones from <code>realPrint</code>.
|-
|-
|<code>_PublishedHelp</code>
| <code>_PublishedHelp</code>
|table
| table
| NONE
| NONE
|-
|-
|<code>ScriptEventCallbacks</code>
| <code>ScriptEventCallbacks</code>
|table
| table
| Table of registered script event callbacks.
| Table of registered script event callbacks.
|-
|-
|<code>ScriptHookCallbacks</code>
| <code>ScriptHookCallbacks</code>
|table
| table
| Table of registered script hook callbacks.
| Table of registered script hook callbacks.
|}
|}
Line 91: Line 89:
! Value
! Value
|-
|-
|<code>ScriptDebugDefaultWatchColor</code>
| <code>ScriptDebugDefaultWatchColor</code>
|array
| array
| [0, 192, 0]
| [0, 192, 0]
|-
|-
|<code>ScriptDebugDrawTextEnabled</code>
| <code>ScriptDebugDrawTextEnabled</code>
|bool
| bool
| true
| true
|-
|-
|<code>ScriptDebugDrawWatchesEnabled</code>
| <code>ScriptDebugDrawWatchesEnabled</code>
|bool
| bool
| true
| true
|-
|-
|<code>ScriptDebugInDebugDraw</code>
| <code>ScriptDebugInDebugDraw</code>
|bool
| bool
| false
| false
|-
|-
|<code>ScriptDebugText</code>
| <code>ScriptDebugText</code>
|array
| array
| NONE
| NONE
|-
|-
|<code>ScriptDebugTextIndent</code>
| <code>ScriptDebugTextIndent</code>
|integer
| integer
| 0
| 0
|-
|-
|<code>ScriptDebugTextFilters</code>
| <code>ScriptDebugTextFilters</code>
|table
| table
| NONE
| NONE
|-
|-
|<code>ScriptDebugTraces</code>
| <code>ScriptDebugTraces</code>
|table
| table
| NONE
| NONE
|-
|-
|<code>ScriptDebugTraceAllOn</code>
| <code>ScriptDebugTraceAllOn</code>
|bool
| bool
| false
| false
|-
|-
|<code>ScriptDebugWatches</code>
| <code>ScriptDebugWatches</code>
|array
| array
| NONE
| NONE
|}
|}
Line 140: Line 138:
! Value
! Value
|-
|-
|<code>_charsize_</code>
| <code>_charsize_</code>
|integer
| integer
| 1
| 1
|-
|-
|<code>_floatsize_</code>
| <code>_floatsize_</code>
|integer
| integer
| 4
| 4
|-
|-
|<code>_intsize_</code>
| <code>_intsize_</code>
|integer
| integer
| 4
| 32-bit: 4
64-bit: 8
|-
|-
|<code>_version_</code>
| <code>_version_</code>
|string
| string
| "Squirrel 3.2 stable"
| "Squirrel 3.2 stable"
|-
|-
|<code>_versionnumber_</code>
| <code>_versionnumber_</code>
|integer
| integer
| 320
| 320
|-
|-
|<code>RAND_MAX</code>
| <code>RAND_MAX</code>
|integer
| integer
| 32767
| Windows: 32768
Linux: 2147483647
|-
|-
|<code>PI</code>
| <code>PI</code>
|float
| float
| 3.14159
| 3.14159
|}
|}
Line 175: Line 175:


== Classes ==
== Classes ==
{{note|All the parameters of type <code>string</code> imply that you can pass <code>null</code> in it's place as well and the result would be equal to passing in an empty string. <code>int</code> parameter can be substituted with <code>float</code> (the floating part will be cut off) and vice versa. <code>handle</code> or <code>table</code> parameters have a poor error detection since you can pass parameter of any type into them and VM wouldn't throw any errors, this however will obviously lead to wrong or most likely completely non-functional behaviour, the only other proper parameter is <code>null</code> depending on whether method description advocates for it.}}
=== CBaseEntity ===
=== CBaseEntity ===
This is a script handle class for entities. All entities have a script handle using this class, sometimes as one of its subclasses.
This is a script handle class for entities. All entities have a script handle using this class, sometimes as one of its subclasses.


An entity's own handle are accessed with:
An entity's own handle are accessed with:
* <code>[[#CEntities|Entities]]</code> instance.
* <code>[[#CEntities|Entities ]]</code> instance.
* <code>EntIndexToHScript</code> function.
* <code>EntIndexToHScript</code> function.
* [[Entity Scripts]] only - The <code>self</code> keyword.
* [[Entity Scripts]] only - The <code>self</code> keyword.
Line 190: Line 191:
! Description
! Description
|-
|-
| <code>__KeyValueFromFloat</code>
| {{obs}} <code>__KeyValueFromFloat (&rarr; KeyValueFromFloat)</code>
| <code>bool __KeyValueFromFloat(string ''key'', float ''value'')</code>
| <code>bool __KeyValueFromFloat(string ''key'', float ''value'')</code>
| Sets an entity [[keyvalue]] from a float. Returns true if successfully set, false if it fails such as the key not existing.
| Behaves the same as <code>KeyValueFromFloat</code>, use that instead.
 
This simply changes the value without executing any code that may be needed for the entity to process the keyvalue, so there may be unintended side effects.
{{warning|Does not update the internal network state of the entity, which can result in any desired visual changes being delayed for clients if used after spawning. [[Team_Fortress_2/Script_Functions#CNetPropManager|Netprops]] can be used instead which correctly updates the networking state and results in an immediate update.}}
|-
|-
| <code>__KeyValueFromInt</code>
| {{obs}} <code>__KeyValueFromInt (&rarr; KeyValueFromInt)</code>
| <code>bool __KeyValueFromInt(string ''key'', int ''value'')</code>
| <code>bool __KeyValueFromInt(string ''key'', int ''value'')</code>
| Sets an entity keyvalue from an integer. Returns true if successfully set, false if it fails such as the key not existing.
| Behaves the same as <code>KeyValueFromInt</code>, use that instead.
 
This simply changes the value without executing any code that may be needed for the entity to process the keyvalue, so there may be unintended side effects.
{{warning|See above.}}
|-
|-
| <code>__KeyValueFromString</code>
| {{obs}} <code>__KeyValueFromString (&rarr; KeyValueFromString)</code>
| <code>bool __KeyValueFromString(string ''key'', string ''value'')</code>
| <code>bool __KeyValueFromString(string ''key'', string ''value'')</code>
| Sets an entity keyvalue from a string. Returns true if successfully set, false if it fails such as the key not existing.
| Behaves the same as <code>KeyValueFromString</code>, use that instead.
 
This simply changes the value without executing any code that may be needed for the entity to process the Keyvalue, so there may be unintended side effects.
{{warning|See above.}}
|-
|-
| <code>__KeyValueFromVector</code>
| {{obs}} <code>__KeyValueFromVector (&rarr; KeyValueFromVector)</code>
| <code>bool __KeyValueFromVector(string ''key'', Vector ''value'')</code>
| <code>bool __KeyValueFromVector(string ''key'', Vector ''value'')</code>
| Sets an entity keyvalue from a [[#Vector|Vector]]. Returns true if successfully set, false if it fails such as the key not existing.
| Behaves the same as <code>KeyValueFromVector</code>, use that instead.
 
|-
This simply changes the value without executing any code that may be needed for the entity to process the Keyvalue, so there may be unintended side effects.
| <code>AcceptInput</code>
{{warning|See above.}}
| <code>bool AcceptInput(string ''input'', string ''param'', handle ''activator'', handle ''caller'')</code>
| Generate a synchronous I/O event. Unlike <code>EntFireByHandle</code>, this is processed immediately. Returns false if ''input'' is a null/empty string, or if the input wasn't handled.
|-
|-
| <code>AddEFlags</code>
| <code>AddEFlags</code>
| <code>void AddEFlags(int ''flags'')</code>
| <code>void AddEFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FEntityEFlags|FEntityEFlags]] ''flags'')</code>
| Adds the supplied ''flags'' to the '''Entity Flags''' in the entity. ''(m_iEFlags datamap)''
| Adds the supplied ''flags'' to the '''Entity Flags''' in the entity. ''(m_iEFlags datamap)''
See [[Team_Fortress_2/Scripting/Script_Functions/Constants#FEntityEFlags|Constants.FEntityEFlags]].
{{note|Adding <code>EFL_KILLME</code> will make the entity unkillable, even on round resets, until the flag is removed.}}
|-
|-
| <code>AddFlag</code>
| <code>AddFlag</code>
| <code>void AddFlag(int ''flags'')</code>
| <code>void AddFlag([[Team_Fortress_2/Scripting/Script_Functions/Constants#FPlayer|FPlayer]] ''flags'')</code>
| Adds the supplied ''flags'' to another separate player-related entity flags system in the entity. ''(m_fFlags datamap)''
| Adds the supplied ''flags'' to another separate player-related entity flags system in the entity. ''(m_fFlags datamap)''
See [[Team_Fortress_2/Scripting/Script_Functions/Constants#FPlayer|Constants.FPlayer]].
|-
|-
| <code>AddSolidFlags</code>
| <code>AddSolidFlags</code>
| <code>void AddSolidFlags(int ''flags'')</code>
| <code>void AddSolidFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FSolid|FSolid]] ''flags'')</code>
| Adds the supplied ''flags'' to the ''Solid Flags'' in the entity. ''(m_Collision.m_usSolidFlags datamap)''
| Adds the supplied ''flags'' to the ''Solid Flags'' in the entity. ''(m_Collision.m_usSolidFlags datamap)''
See [[Team_Fortress_2/Scripting/Script_Functions/Constants#FSolid|Constants.FSolid]].
|-
|-
| <code>ApplyAbsVelocityImpulse</code>
| <code>ApplyAbsVelocityImpulse</code>
Line 244: Line 235:
| <code>bool BecomeRagdollOnClient(Vector ''impulse'')</code>
| <code>bool BecomeRagdollOnClient(Vector ''impulse'')</code>
| Acts like the <code>BecomeRagdoll</code> input, with the required ''impulse'' value applied as a force on the ragdoll. Does NOT spawn a <code>[[prop_ragdoll]]</code> or any other entity.
| Acts like the <code>BecomeRagdoll</code> input, with the required ''impulse'' value applied as a force on the ragdoll. Does NOT spawn a <code>[[prop_ragdoll]]</code> or any other entity.
{{warning|These are a special group of ragdolls that never disappear by default. To limit them or force them to disappear, use the [[game_ragdoll_manager]] entity.}}
|-
|-
| <code>ClearFlags</code>
| <code>ClearFlags</code>
Line 254: Line 246:
|-
|-
| <code>ConnectOutput</code>
| <code>ConnectOutput</code>
| <code>void ConnectOutput(string ''output'', string ''function'')</code>
| <code>void ConnectOutput(string ''output_name'', string ''function_name'')</code>
| Adds an I/O connection that will call the named function when the specified output fires.
| Adds an I/O connection that will call the named function when the specified output fires.
{{note|If you are trying to access <code>activator</code> and <code>caller</code> in the called function and it doesn't exist, this means the entity has no script scope. Use <code>ValidateScriptScope</code> to fix this.}}
|-
|-
| <code>Destroy</code>
| <code>Destroy</code>
Line 266: Line 259:
|-
|-
| <code>DisconnectOutput</code>
| <code>DisconnectOutput</code>
| <code>void DisconnectOutput(string ''output'', string ''function'')</code>
| <code>void DisconnectOutput(string ''output_name'', string ''function_name'')</code>
| Removes a connected script function from an I/O event.
| Removes a connected script function from an I/O event.
|-
|-
Line 272: Line 265:
| <code>void DispatchSpawn()</code>
| <code>void DispatchSpawn()</code>
| Alternative dispatch spawn, same as the one in CEntities, for convenience.
| Alternative dispatch spawn, same as the one in CEntities, for convenience.
{{note|Calling this on players will cause them to respawn. In {{css}}, set the <code>m_iPlayerState</code> netprop to 0 before calling this to fully respawn.}}
|-
|-
| <code>EmitSound</code>
| <code>EmitSound</code>
| <code>void EmitSound(string)</code>
| <code>void EmitSound(string ''sound_name'')</code>
| Plays a sound from this entity.
| Plays a sound from this entity. The sound must be precached first for it to play (using <code>PrecacheSound</code> or <code>PrecacheScriptSound</code>).
{{warning|Looping sounds will not stop on the entity when it's destroyed and will persist forever! To workaround this, run <code>StopSound</code> in the <code>OnDestroy</code> callback.}}
|-
|-
| <code>EnableDraw</code>
| <code>EnableDraw</code>
Line 316: Line 311:
| <code>GetBaseVelocity</code>
| <code>GetBaseVelocity</code>
| <code>Vector GetBaseVelocity()</code>
| <code>Vector GetBaseVelocity()</code>
| Returns any constant velocity currently being imparted onto the entity. This includes being pushed by effects like {{ent|trigger_push}} and players standing on moving geometry like elevators. Should always returns a zero vector if the entity is not affected by any movement effects.  
| Returns any constant velocity currently being imparted onto the entity. This includes being pushed by effects like {{ent|trigger_push}} and players standing on moving geometry like elevators. Should always returns a zero vector if the entity is not affected by any movement effects.
|-
|-
| <code>GetBoundingMaxs</code>
| <code>GetBoundingMaxs</code>
| <code>Vector GetBoundingMaxs()</code>
| <code>Vector GetBoundingMaxs()</code>
| Get a vector containing max bounds, centered on object
| Get a vector containing max bounds, centered on object.
|-
|-
| <code>GetBoundingMaxsOriented</code>
| <code>GetBoundingMaxsOriented</code>
| <code>Vector GetBoundingMaxsOriented()</code>
| <code>Vector GetBoundingMaxsOriented()</code>
| Get a vector containing max bounds, centered on object, taking the object's orientation into account
| Get a vector containing max bounds, centered on object, taking the object's orientation into account.
{{bug|hidetested=1|This does not transform the bounds correctly and in some cases the bounding box will not cover the whole entity. As a workaround, use the non-oriented bounds and perform an AABB transformation using a matrix constructed from the entity's origin and angles.}}
|-
|-
| <code>GetBoundingMins</code>
| <code>GetBoundingMins</code>
| <code>Vector GetBoundingMins()</code>
| <code>Vector GetBoundingMins()</code>
| Get a vector containing min bounds, centered on object
| Get a vector containing min bounds, centered on object.
|-
|-
| <code>GetBoundingMinsOriented</code>
| <code>GetBoundingMinsOriented</code>
| <code>Vector GetBoundingMinsOriented()</code>
| <code>Vector GetBoundingMinsOriented()</code>
| Get a vector containing min bounds, centered on object, taking the object's orientation into account
| Get a vector containing min bounds, centered on object, taking the object's orientation into account.
{{bug|hidetested=1|This does not transform the bounds correctly and in some cases the bounding box will not cover the whole entity. As a workaround, use the non-oriented bounds and perform an AABB transformation using a matrix constructed from the entity's origin and angles.}}
|-
|-
| <code>GetCenter</code>
| <code>GetCenter</code>
| <code>Vector GetCenter()</code>
| <code>Vector GetCenter()</code>
| Get vector to center of object - absolute coords
| Gets center point of the entity in world coordinates.
|-
|-
| <code>GetClassname</code>
| <code>GetClassname</code>
| <code>string GetClassname()</code>
| <code>string GetClassname()</code>
|  
|
|-
|-
| <code>GetCollisionGroup</code>
| <code>GetCollisionGroup</code>
| <code>GetCollisionGroup()</code>
| <code>int GetCollisionGroup()</code>
| Gets the current collision group of the entity.  
| Gets the current collision group of the entity.
See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ECollisionGroup|Constants.ECollisionGroup]]
|-
|-
| <code>GetEFlags</code>
| <code>GetEFlags</code>
| <code>int GetEFlags()</code>
| <code>int GetEFlags()</code>
|
| Get the entity's engine flags.
See [[Team_Fortress_2/Scripting/Script_Functions/Constants#FEntityEFlags|Constants.FEntityEFlags]].
|-
|-
| <code>GetFlags</code>
| <code>GetFlags</code>
| <code>int GetFlags()</code>
| <code>int GetFlags()</code>
|
| Get the entity's flags.
See [[Team_Fortress_2/Scripting/Script_Functions/Constants#FPlayer|Constants.FPlayer]].
{{tip|Example usage:
<source lang=js>
if (entity.GetFlags() & Constants.FPlayer.FL_ONGROUND)
{
printl("Entity is on the ground!")
}
</source>
}}
|-
|-
| <code>GetEntityHandle</code>
| <code>GetEntityHandle</code>
| <code><unknown> GetEntityHandle()</code>
| <code>ehandle GetEntityHandle()</code>
| Get the entity as an EHANDLE
| Get the entity as an EHANDLE.
{{deprecated|Leftover from earlier versions of VScript.}}
|-
|-
| <code>GetEntityIndex</code>
| <code>GetEntityIndex</code>
| <code>int GetEntityIndex()</code>
| <code>int GetEntityIndex()</code>
|  
|
|-
|-
| <code>GetForwardVector</code>
| <code>GetForwardVector</code>
| <code>Vector GetForwardVector()</code>
| <code>Vector GetForwardVector()</code>
| Get the forward vector of the entity
| Get the forward vector of the entity.
{{note|If you intend to get a player's eye forward vector, use <code>EyeAngles().Forward()</code> instead as it's more accurate.}}
|-
|-
| <code>GetFriction</code>
| <code>GetFriction</code>
| <code>float GetFriction()</code>
| <code>float GetFriction()</code>
| Get PLAYER friction, ignored for objects
| Get PLAYER friction, ignored for objects.
|-
|-
| <code>GetGravity</code>
| <code>GetGravity</code>
Line 376: Line 386:
| <code>GetHealth</code>
| <code>GetHealth</code>
| <code>int GetHealth()</code>
| <code>int GetHealth()</code>
|  
|
|-
|-
|style=white-space:nowrap| {{obs}} <code>GetLeftVector (&rarr; GetRightVector)</code>
|style=white-space:nowrap| {{obs}} <code>GetLeftVector (&rarr; GetRightVector)</code>
Line 384: Line 394:
| <code>GetLocalAngles</code>
| <code>GetLocalAngles</code>
| <code>QAngle GetLocalAngles()</code>
| <code>QAngle GetLocalAngles()</code>
|  
|
|-
|-
| <code>GetLocalOrigin</code>
| <code>GetLocalOrigin</code>
| <code>Vector GetLocalOrigin()</code>
| <code>Vector GetLocalOrigin()</code>
|  
|
|-
|-
| <code>GetLocalVelocity</code>
| <code>GetLocalVelocity</code>
| <code>Vector GetLocalVelocity()</code>
| <code>Vector GetLocalVelocity()</code>
| Get Entity relative velocity
| Get Entity relative velocity.
|-
|-
| <code>GetMaxHealth</code>
| <code>GetMaxHealth</code>
| <code>int GetMaxHealth()</code>
| <code>int GetMaxHealth()</code>
|  
|
|-
|-
| <code>GetModelKeyValues</code>
| <code>GetModelKeyValues</code>
| <code>handle GetModelKeyValues()</code>
| <code>CScriptKeyValues GetModelKeyValues()</code>
| Get a KeyValue class instance on this entity's model
| Get a KeyValue class instance on this entity's model.
|-
|-
| <code>GetModelName</code>
| <code>GetModelName</code>
| <code>string GetModelName()</code>
| <code>string GetModelName()</code>
| Returns the name of the model
| Returns the name of the model.
{{note|When you try to call this method on weapons the returned model would be a player hand model. For naturally spawned weapons you can receive the model index from <code>m_iWorldModelIndex</code> netprop, however, artificially spawned weapons always have this netprop set to 0. Instead you can create a <code>tf_wearable</code> with the same definition index and get it's model:
{{ExpandBox|<source lang="js">
function DefinitionIndexModel(index)
{
local wearable = Entities.CreateByClassname("tf_wearable")
NetProps.SetPropInt(wearable, "m_AttributeManager.m_Item.m_iItemDefinitionIndex", index)
NetProps.SetPropBool(wearable, "m_AttributeManager.m_Item.m_bInitialized", true)
NetProps.SetPropBool(wearable, "m_bForcePurgeFixedupStrings", true)
wearable.DispatchSpawn()
 
local model = wearable.GetModelName()
 
wearable.Destroy()
 
return model
}
</source>}}
}}
|-
|-
| <code>GetMoveParent</code>
| <code>GetMoveParent</code>
| <code>handle GetMoveParent()</code>
| <code>handle GetMoveParent()</code>
| If in hierarchy, retrieves the entity's parent
| If in hierarchy, retrieves the entity's parent.
|-
|-
| <code>GetMoveType</code>
| <code>GetMoveType</code>
Line 416: Line 444:
| <code>GetName</code>
| <code>GetName</code>
| <code>string GetName()</code>
| <code>string GetName()</code>
|  
| Get entity's targetname.
|-
|-
| <code>GetOrigin</code>
| <code>GetOrigin</code>
Line 424: Line 452:
| <code>GetOwner</code>
| <code>GetOwner</code>
| <code>handle GetOwner()</code>
| <code>handle GetOwner()</code>
| Gets this entity's owner
| Gets this entity's owner.
{{note|This is a wrapper for <code>m_hOwnerEntity</code> netprop. To get <code>m_hOwner</code> you would need to use <code>NetProps.GetPropEntity(entity, "m_hOwner")</code>.}}
|-
|-
| <code>GetPhysAngularVelocity</code>
| <code>GetPhysAngularVelocity</code>
Line 436: Line 465:
| <code>GetPreTemplateName</code>
| <code>GetPreTemplateName</code>
| <code>string GetPreTemplateName()</code>
| <code>string GetPreTemplateName()</code>
| Get the entity name stripped of template unique decoration
| Get the entity name stripped of template unique decoration.
|-
|-
| <code>GetRightVector</code>
| <code>GetRightVector</code>
| <code>Vector GetRightVector()</code>
| <code>Vector GetRightVector()</code>
| Get the right vector of the entity
| Get the right vector of the entity.
|-
|-
| <code>GetRootMoveParent</code>
| <code>GetRootMoveParent</code>
| <code>handle GetRootMoveParent()</code>
| <code>handle GetRootMoveParent()</code>
| If in hierarchy, walks up the hierarchy to find the root parent
| If in hierarchy, walks up the hierarchy to find the root parent.
|-
|-
| <code>GetScriptId</code>
| <code>GetScriptId</code>
Line 451: Line 480:
|-
|-
| <code>GetScriptScope</code>
| <code>GetScriptScope</code>
| <code>handle GetScriptScope()</code>
| <code>table GetScriptScope()</code>
| Retrieve the script-side data associated with an entity
| Retrieve the script-side data associated with an entity.
|-
|-
| <code>GetScriptThinkFunc</code>
| <code>GetScriptThinkFunc</code>
| <code>string GetScriptThinkFunc()</code>
| <code>string GetScriptThinkFunc()</code>
| Retrieve the name of the current script think func
| Retrieve the name of the current script think func.
|-
|-
| <code>GetSolid</code>
| <code>GetSolid</code>
| <code>int GetSolid()</code>
| <code>int GetSolid()</code>
|
| See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ESolidType|ESolidType]].
|-
|-
| <code>GetSoundDuration</code>
| <code>GetSoundDuration</code>
| <code>float GetSoundDuration(string, string)</code>
| <code>float GetSoundDuration(string ''sound_name'', string ''actor_model_name'')</code>
| Returns float duration of the sound. Takes soundname and optional actormodelname.
| Returns float duration of the sound. Actor model name is optional and can be left null.
{{todo|Actor model name is likely a leftover from {{hl2|2}}}}
{{warning|Does not work on dedicated servers as they do not have audio libraries built-in to load sounds.}}
{{warning|Does not work on dedicated servers as they do not have audio libraries built-in to load sounds.}}
|-
|-
| <code>GetTeam</code>
| <code>GetTeam</code>
| <code>int GetTeam()</code>
| <code>int GetTeam()</code>
|  
| See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]].
|-
|-
| <code>GetUpVector</code>
| <code>GetUpVector</code>
| <code>Vector GetUpVector()</code>
| <code>Vector GetUpVector()</code>
| Get the up vector of the entity
| Get the up vector of the entity.
|-
|-
| {{obs}} <code>GetVelocity (&rarr; GetAbsVelocity)</code>
| {{obs}} <code>GetVelocity (&rarr; GetAbsVelocity)</code>
| <code>Vector GetVelocity()</code>
| <code>Vector GetVelocity()</code>
|  
|
|-
|-
| <code>GetWaterLevel</code>
| <code>GetWaterLevel</code>
| <code>int GetWaterLevel()</code>
| <code>int GetWaterLevel()</code>
|  
| This function tells you how much of the entity is underwater. It returns a value of 0 if not underwater, 1 if the feet are (touching water brush), 2 if the waist is (center of the hull of the entity), and 3 if the head is (eyes position).
{{note|Some entities might not return 1 despite touching water. In some cases you might get 0 and 3 only, or sometimes 0, 2 and 3.}}
|-
|-
| <code>GetWaterType</code>
| <code>GetWaterType</code>
| <code>int GetWaterType()</code>
| <code>int GetWaterType()</code>
|  
| It returns the type of water the entity is currently submerged in. 32 for water and 16 for slime.
|-
| <code>IsAlive</code>
| <code>bool IsAlive()</code>
| Am I alive?
|-
|-
| <code>IsEFlagSet</code>
| <code>IsEFlagSet</code>
| <code>bool IsEFlagSet(int)</code>
| <code>bool IsEFlagSet([[Team_Fortress_2/Scripting/Script_Functions/Constants#FEntityEFlags|FEntityEFlags]] ''flag'')</code>
|
|
|-
|-
| <code>IsPlayer</code>
| <code>IsPlayer</code>
| <code>bool IsPlayer()</code>
| <code>bool IsPlayer()</code>
|  
| Checks whether the entity is a player or not.
|-
|-
| <code>IsSolid</code>
| <code>IsSolid</code>
| <code>bool IsSolid()</code>
| <code>bool IsSolid()</code>
|  
|
|-
|-
| <code>IsSolidFlagSet</code>
| <code>IsSolidFlagSet</code>
| <code>bool IsSolidFlagSet(int)</code>
| <code>bool IsSolidFlagSet([[Team_Fortress_2/Scripting/Script_Functions/Constants#FSolid|FSolid]] ''flag'')</code>
|
|
|-
|-
Line 509: Line 544:
|-
|-
| <code>KeyValueFromFloat</code>
| <code>KeyValueFromFloat</code>
| <code>bool KeyValueFromFloat(string, float)</code>
| <code>bool KeyValueFromFloat(string ''key'', float ''value'')</code>
| Executes KeyValue with a float
| Executes KeyValue with a float.
{{warning|Does not update the internal network state of the entity, which can result in any desired visual changes being delayed for clients if used after spawning. [[Team_Fortress_2/Script_Functions#CNetPropManager|Netprops]] can be used instead which correctly updates the networking state and results in an immediate update.}}
{{warning|Does not update the internal network state of the entity, which can result in any desired visual changes being delayed for clients if used after spawning. [[#CNetPropManager|Netprops ]] can be used instead which correctly updates the networking state and results in an immediate update. An exception is the <code>origin</code> keyvalue, which does update network state immediately.}}
|-
|-
| <code>KeyValueFromInt</code>
| <code>KeyValueFromInt</code>
| <code>bool KeyValueFromInt(string, int)</code>
| <code>bool KeyValueFromInt(string ''key'', int ''value'')</code>
| Executes KeyValue with an int
| Executes KeyValue with an int.
{{warning|See above.}}
{{warning|See above.}}
|-
|-
| <code>KeyValueFromString</code>
| <code>KeyValueFromString</code>
| <code>bool KeyValueFromString(string, string)</code>
| <code>bool KeyValueFromString(string ''key'', string ''value'')</code>
| Executes KeyValue with a string
| Executes KeyValue with a string.
{{warning|See above.}}
{{warning|See above.}}
|-
|-
| <code>KeyValueFromVector</code>
| <code>KeyValueFromVector</code>
| <code>bool KeyValueFromVector(string, Vector)</code>
| <code>bool KeyValueFromVector(string ''key'', Vector ''value'')</code>
| Executes KeyValue with a vector
| Executes KeyValue with a vector.
{{warning|See above.}}
{{warning|See above.}}
|-
|-
Line 531: Line 566:
| <code>void Kill()</code>
| <code>void Kill()</code>
| Removes the entity. Equivalent of firing the <code>Kill</code> I/O input, but instantaneous.
| Removes the entity. Equivalent of firing the <code>Kill</code> I/O input, but instantaneous.
{{warning|This clears the owner entity (<code>m_hOwnerEntity</code> netprop) before removing, this may cause unexpected problems with entities that rely on cleaning up data related to their owner, such as Medigun healing targets. In those cases, use <code>Destroy</code> instead.}}
|-
|-
| <code>LocalEyeAngles</code>
| <code>LocalEyeAngles</code>
| <code>handle LocalEyeAngles()</code>
| <code>QAngle LocalEyeAngles()</code>
| Returns the entity's local eye angles
| Returns the entity's local eye angles.
|-
|-
| <code>NextMovePeer</code>
| <code>NextMovePeer</code>
Line 541: Line 577:
|-
|-
| <code>PrecacheModel</code>
| <code>PrecacheModel</code>
| <code>void PrecacheModel(string)</code>
| <code>void PrecacheModel(string ''model_name'')</code>
|  
| Precache a model (<code>.mdl</code>) or sprite (<code>.vmt</code>). The extension must be specified.
{{note|This has no return, unlike the global <code>PrecacheModel</code> function. Use the latter if you need the model index.}}
{{note|Does not precache gibs. See <code>PrecacheEntityFromTable</code> instead.}}
|-
|-
| <code>PrecacheScriptSound</code>
| <code>PrecacheScriptSound</code>
| <code>void PrecacheScriptSound(string)</code>
| <code>void PrecacheScriptSound(string ''sound_script'')</code>
|  
| Precache a sound script. Same as <code>PrecacheSoundScript</code>.
|-
|-
| <code>PrecacheSoundScript</code>
| <code>PrecacheSoundScript</code>
| <code>void PrecacheSoundScript(string)</code>
| <code>void PrecacheSoundScript(string ''sound_script'')</code>
| Precache a sound for later playing.
| Precache a sound script. Same as <code>PrecacheScriptSound</code>.
|-
|-
| <code>RemoveEFlags</code>
| <code>RemoveEFlags</code>
| <code>void RemoveEFlags(int)</code>
| <code>void RemoveEFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FEntityEFlags|FEntityEFlags]] ''flags'')</code>
|  
|
|-
|-
| <code>RemoveFlag</code>
| <code>RemoveFlag</code>
| <code>void RemoveFlag(int)</code>
| <code>void RemoveFlag([[Team_Fortress_2/Scripting/Script_Functions/Constants#FPlayer|FPlayer]] ''flags'')</code>
|  
|
|-
|-
| <code>RemoveSolidFlags</code>
| <code>RemoveSolidFlags</code>
| <code>void RemoveSolidFlags(int)</code>
| <code>void RemoveSolidFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FSolid|FSolid]] ''flags'')</code>
|
|
|-
|-
| <code>SetAbsAngles</code>
| <code>SetAbsAngles</code>
| <code>void SetAbsAngles(QAngle)</code>
| <code>void SetAbsAngles(QAngle ''angles'')</code>
| Set entity pitch, yaw, roll as QAngles
| Set entity pitch, yaw, roll as QAngles. Does not work on players, use <code>SnapEyeAngles</code> instead.
{{note|Does not work on players, use <code>SnapEyeAngles</code> instead.}}
|-
|-
| <code>SetAbsVelocity</code>
| <code>SetAbsVelocity</code>
| <code>void SetAbsVelocity(Vector)</code>
| <code>void SetAbsVelocity(Vector ''velocity'')</code>
| Sets the current absolute velocity of the entity
| Sets the current absolute velocity of the entity. Does nothing on [[VPhysics]] objects (such as <code>prop_physics</code>). For those, use <code>SetPhysVelocity</code> instead.
|-
|-
| <code>SetAbsOrigin</code>
| <code>SetAbsOrigin</code>
| <code>void SetAbsOrigin(Vector)</code>
| <code>void SetAbsOrigin(Vector ''origin'')</code>
| SetAbsOrigin
| Sets the absolute origin of the entity.
{{note|On some entities, this won't interpolate positions and therefore moving entities might look jittery. In those cases, use <code>KeyValueFromVector("origin", pos)</code> instead.}}
|-
|-
| {{obs}} <code>SetAngles (&rarr; SetAbsAngles)</code>
| {{obs}} <code>SetAngles (&rarr; SetAbsAngles)</code>
| <code>void SetAngles(float, float, float)</code>
| <code>void SetAngles(float ''pitch'', float ''yaw'', float ''roll'')</code>
| Set entity pitch, yaw, roll.
| Set entity angles.
|-
|-
| <code>SetAngularVelocity</code>
| <code>SetAngularVelocity</code>
| <code>void SetAngularVelocity(float, float, float)</code>
| <code>void SetAngularVelocity(float ''pitch'', float ''yaw'', float ''roll'')</code>
| Set the local angular velocity - takes float pitch,yaw,roll velocities
| Set the local angular velocity.
|-
|-
| <code>SetCollisionGroup</code>
| <code>SetCollisionGroup</code>
| <code>void SetCollisionGroup(int)</code>
| <code>void SetCollisionGroup([[Team_Fortress_2/Scripting/Script_Functions/Constants#ECollisionGroup|ECollisionGroup]] ''group'')</code>
| Set the current collision group of the entity.
| Set the current collision group of the entity.
See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ECollisionGroup|Constants.ECollisionGroup]]
|-
|-
| <code>SetDrawEnabled</code>
| <code>SetDrawEnabled</code>
| <code>void SetDrawEnabled(bool)</code>
| <code>void SetDrawEnabled(bool ''toggle'')</code>
| Enables drawing if you pass true, disables drawing if you pass false.
| Enables drawing if you pass true, disables drawing if you pass false.
|-
|-
| <code>SetEFlags</code>
| <code>SetEFlags</code>
| <code>void SetEFlags(int)</code>
| <code>void SetEFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FEntityEFlags|FEntityEFlags]] ''flags'')</code>
|
|
|-
|-
| <code>SetForwardVector</code>
| <code>SetForwardVector</code>
| <code>void SetForwardVector(Vector)</code>
| <code>void SetForwardVector(Vector ''forward'')</code>
| Set the orientation of the entity to have this forward vector
| Set the orientation of the entity to have this forward vector.
{{note|If used on the players the resulting orientation will not be normalized which can lead to console warnings in some cases. To avoid this convert the vector to an angle with the following function and pass the result into <code>SnapEyeAngles</code>:
{{ExpandBox|<source lang=js>
function VectorAngles(forward)
{
local yaw, pitch
if (forward.y == 0.0 && forward.x == 0.0)
{
yaw = 0.0
if (forward.z > 0.0)
pitch = 270.0
else
pitch = 90.0
}
else
{
yaw = (atan2(forward.y, forward.x) * 180.0 / Constants.Math.Pi)
if (yaw < 0.0)
yaw += 360.0
pitch = (atan2(-forward.z, forward.Length2D()) * 180.0 / Constants.Math.Pi)
if (pitch < 0.0)
pitch += 360.0
}
 
return QAngle(pitch, yaw, 0.0)
}
</source>}}
}}
{{note|If used on the players consider the note on <code>SnapEyeAngles</code> in [[#CBasePlayer|CBasePlayer ↓]].}}
|-
|-
| <code>SetFriction</code>
| <code>SetFriction</code>
| <code>void SetFriction(float)</code>
| <code>void SetFriction(float ''friction'')</code>
|
|
|-
|-
| <code>SetGravity</code>
| <code>SetGravity</code>
| <code>void SetGravity(float)</code>
| <code>void SetGravity(float ''gravity'')</code>
|
| Sets a multiplier for gravity. 1 is default gravity.
{{note|0 gravity will not work. Instead, set it to something like <code>0.000001</code> as a workaround.}}
|-
|-
| <code>SetHealth</code>
| <code>SetHealth</code>
| <code>void SetHealth(int)</code>
| <code>void SetHealth(int ''health'')</code>
|  
|
|-
|-
| <code>SetLocalAngles</code>
| <code>SetLocalAngles</code>
| <code>void SetLocalAngles(QAngle)</code>
| <code>void SetLocalAngles(QAngle ''angles'')</code>
|  
|
|-
|-
| <code>SetLocalOrigin</code>
| <code>SetLocalOrigin</code>
| <code>void SetLocalOrigin(Vector)</code>
| <code>void SetLocalOrigin(Vector ''origin'')</code>
|  
|
|-
|-
| <code>SetMaxHealth</code>
| <code>SetMaxHealth</code>
| <code>void SetMaxHealth(int)</code>
| <code>void SetMaxHealth(int ''health'')</code>
|  
| Sets the maximum health this entity can have. Does not update the current health, so <code>SetHealth</code> should be used afterwards.
{{note|Does nothing on players.}}
{{workaround|Instead, use <code>AddCustomAttribute</code> to add an attribute like <code>max health additive bonus</code> or <code>hidden maxhealth non buffed</code>. The latter attribute works like the max health gained from the Heavy's [http://wiki.teamfortress.com/wiki/Dalokohs_Bar Dalokohs Bar], which doesn't affect max overheal amount.}}
|-
|-
| <code>SetModel</code>
| <code>SetModel</code>
| <code>void SetModel(string)</code>
| <code>void SetModel(string ''model_name'')</code>
| Set a model for this entity
| Set a model for this entity.
{{note|Does nothing on players. Use <code>SetCustomModel</code> in that case.}}
{{warning|Make sure the model was already precached before using this function or otherwise the game will crash! Alternatively, <code>SetModelSimple</code> will precache the entity for you.}}
|-
|-
| <code>SetMoveType</code>
| <code>SetMoveType</code>
Line 635: Line 705:
|-
|-
| {{obs}} <code>SetOrigin (&rarr; SetAbsOrigin)</code>
| {{obs}} <code>SetOrigin (&rarr; SetAbsOrigin)</code>
| <code>void SetOrigin(Vector)</code>
| <code>void SetOrigin(Vector ''origin'')</code>
|  
|
|-
|-
| <code>SetOwner</code>
| <code>SetOwner</code>
| <code>void SetOwner(handle)</code>
| <code>void SetOwner(handle ''entity'')</code>
| Sets this entity's owner
| Sets this entity's owner.
{{note|This is a wrapper for <code>m_hOwnerEntity</code> netprop. To set <code>m_hOwner</code> you would need to use <code>NetProps.SetPropEntity(entity, "m_hOwner", owner)</code>.}}
|-
|-
| <code>SetPhysAngularVelocity</code>
| <code>SetPhysAngularVelocity</code>
| <code>void SetPhysAngularVelocity(Vector)</code>
| <code>void SetPhysAngularVelocity(Vector ''angular_velocity'')</code>
|
|
|-
|-
| <code>SetPhysVelocity</code>
| <code>SetPhysVelocity</code>
| <code>void SetPhysVelocity(Vector)</code>
| <code>void SetPhysVelocity(Vector ''velocity'')</code>
|  
|
|-
|-
| <code>SetSize</code>
| <code>SetSize</code>
| <code>void SetSize(Vector mins, Vector maxs)</code>
| <code>void SetSize(Vector ''mins'', Vector ''maxs'')</code>
| Sets the bounding box's scale for this entity.
| Sets the bounding box's scale for this entity.
{{warning|If any component of mins/maxs is backwards (i.e. mins.x > maxs.x), the engine will exit with a fatal error.}}
|-
|-
| <code>SetSolid</code>
| <code>SetSolid</code>
| <code>SetSolid(int)</code>
| <code>void SetSolid([[Team_Fortress_2/Scripting/Script_Functions/Constants#ESolidType|ESolidType]] ''solid'')</code>
|  
|
|-
|-
| <code>SetSolidFlags</code>
| <code>SetSolidFlags</code>
| <code>SetSolidFlags(int)</code>
| <code>void SetSolidFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FSolid|FSolid]] ''flags'')</code>
|
|
|-
|-
| <code>SetTeam</code>
| <code>SetTeam</code>
| <code>void SetTeam(int)</code>
| <code>void SetTeam([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'')</code>
|  
| Sets entity team.
{{note|Use <code>ForceChangeTeam</code> on players instead.}}
|-
|-
| <code>SetVelocity</code>
| {{obs}} <code>SetVelocity (&rarr; SetAbsVelocity)</code>
| <code>void SetVelocity(Vector)</code>
| <code>void SetVelocity(Vector ''velocity'')</code>
|  
|
|-
|-
| <code>SetWaterLevel</code>
| <code>SetWaterLevel</code>
| <code>SetWaterLevel(int)</code>
| <code>void SetWaterLevel(int ''water_level'')</code>
|  
| This sets how much of the entity is underwater. Setting it to 0 means it is not underwater, 1 if the feet are (touching water brush), 2 if the waist is (center of the hull of the entity), and 3 if the head is (eyes position).
|-
|-
| <code>SetWaterType</code>
| <code>SetWaterType</code>
| <code>SetWaterType(int)</code>
| <code>void SetWaterType(int ''water_type'')</code>
|
| Set the type of water the entity is currently submerged in. Generic values to use are 32 for water and 16 for slime.
|-
|-
| <code>StopSound</code>
| <code>StopSound</code>
| <code>void StopSound(string)</code>
| <code>void StopSound(string ''sound_name'')</code>
| Stops a sound on this entity.
| Stops a sound on this entity.
|-
|-
| <code>TakeDamage</code>
| <code>TakeDamage</code>
| <code>void TakeDamage(float ''flDamage'', int ''nDamageType'', handle ''hAttacker'')</code>
| <code>void TakeDamage(float ''damage'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#FDmgType|FDmgType]] ''damage_type'', handle ''attacker'')</code>
|  
| Deals damage to the entity.
|-
| <code>TakeDamageEx</code>
| <code>void TakeDamageEx(handle ''inflictor'', handle ''attacker'', handle ''weapon'', Vector ''damage_force'', Vector ''damage_position'', float ''damage'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#FDmgType|FDmgType]] ''damage_type'')</code>
| Extended version of <code>TakeDamage</code>.
{{note|If ''damage_force'' is Vector(0, 0, 0), the game will automatically calculate it from ''damage_position'' and ''damage''. However, specifying a custom damage force requires a really, really big value to have visible effect (in the hundreds of thousands).}}
|-
| <code>TakeDamageCustom</code>
| <code>void TakeDamageCustom(handle ''inflictor'', handle ''attacker'', handle ''weapon'', Vector ''damage_force'', Vector ''damage_position'', float ''damage'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#FDmgType|FDmgType]] ''damage_type'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFDmgCustom|ETFDmgCustom]] ''custom_damage_type'')</code>
| Extended version of <code>TakeDamageEx</code> that can apply a custom damage type.
|-
|-
| <code>Teleport</code>
| <code>Teleport</code>
Line 692: Line 774:
| <code>TerminateScriptScope</code>
| <code>TerminateScriptScope</code>
| <code>void TerminateScriptScope()</code>
| <code>void TerminateScriptScope()</code>
| Clear the current script scope for this entity
| Clear the current script scope for this entity.
|-
|-
| <code>ToggleFlag</code>
| <code>ToggleFlag</code>
| <code>ToggleFlag(int)</code>
| <code>void ToggleFlag([[Team_Fortress_2/Scripting/Script_Functions/Constants#FPlayer|FPlayer]] ''flags'')</code>
|
|-
| <code>TakeDamageEx</code>
| <code>void TakeDamageEx(handle ''hInflictor'', handle ''hAttacker'', handle ''hWeapon'', Vector ''vecDamageForce'', Vector ''vecDamagePosition'', float ''flDamage'', int ''nDamageType'')</code>
|  
|-
| <code>TakeDamageCustom</code>
| <code>void TakeDamageCustom(handle ''hInflictor'', handle ''hAttacker'', handle ''hWeapon'', Vector ''vecDamageForce'', Vector ''vecDamagePosition'', float ''flDamage'', int ''nDamageType'', int ''nCustomDamageType'')</code>
|
|
|-
|-
| <code>ValidateScriptScope</code>
| <code>ValidateScriptScope</code>
| <code>bool ValidateScriptScope()</code>
| <code>bool ValidateScriptScope()</code>
| Ensure that an entity's script scope has been created
| Create a script scope for an entity if it doesn't already exist. The return value is always true, unless the script VM is disabled in launch options.
{{note|This is unnecessary to run on entities that have an entity script assigned. Entity scripts will already create the script scope themselves.}}
{{tip|On players, this only needs to be called once. Script scopes remain permanent on players until their entity is removed, i.e. disconnected. The best place to call this is in the <code>player_spawn</code> event when <code>params.team</code> equals 0 (unassigned). The event is always fired once for team unassigned when the player entity spawns. Similarly, for engineer buildings, this function can also be called once. The <code>player_builtobject</code> is fired when an engineer building is created (or re-placed after moving, but this shouldn't matter).}}
|}
|}


Line 720: Line 796:
! Description
! Description
|-
|-
| <code>Input_''name''</code>
| <code>Input<''name''></code>
| <code>bool Input_''name''()</code>
| <code>bool Input<''name''>()</code>
| Called when the entity receives an input from the I/O system that matches the function's name. The name of the function needs to be<code>Input</code>followed by the name of the input. E.g. for the FireUser1 input, it would be<code>InputFireUser1</code>.
| Called right before an entity receives a valid input from the I/O system that matches the function's name. The name of the function needs to be<code>Input</code>followed by the name of the input. E.g. for the FireUser1 input, it would be<code>InputFireUser1</code>. When the function is called, Script Handles of the activator and caller entities are accessible to the function under the variables<code>activator</code>and<code>caller</code>. The function needs to return a boolean value: returning<code>true</code>processes the input, while<code>false</code>cancels it.
{{note|There is an inconsistency with the naming scheme of the inputs. Certain inputs are required in PascalCase format, others in lowercase format. For example, <code>ForceDrop</code> input on [[item_teamflag]] must be specified in lowercase, i.e. <code>Inputforcedrop</code>, but another input such as <code>Kill</code> input must be in PascalCase, i.e. <code>InputKill</code>. However it appears this inconsistency varies between different entity classes as well. It is currently unknown what causes this inconsistency.}}
{{bug|hidetested=1|There is an inconsistency with the naming scheme of the inputs. Certain inputs are required in PascalCase format, others in lowercase format. For example, <code>ForceDrop</code> input on [[item_teamflag]] must be specified in lowercase, i.e. <code>Inputforcedrop</code>, but another input such as <code>Kill</code> input must be in PascalCase, i.e. <code>InputKill</code>. However, this inconsistency also varies between different entity classes as well. The cause of this is string caching in the game (I/O is case-insensitive so it normally doesn't matter, but Squirrel is case-sensitive).}}
{{tip|It may be best to define both variants of these function and have one be a wrapper for the other if the entity class is unknown.}}
{{tip|It is best to define both variants of these function and have one be a wrapper for the other, i.e. <code>Inputfireuser1 <- InputFireUser1</code>.}}
{{tip|This hook is fired ''before'' the game processes the input internally. If a hook is required that runs ''after'' the game processes it, there is two options:
* Asynchronous: Use a EntFire with a 0 delay to run code at the end of the frame. This is not instantly executed which may cause issues if multiple inputs get processed at once.
* Synchronous: Using a quirk, it's possible to synchronously detect when the input has been processed. The game wipes the <code>activator</code> and <code>caller</code> variables from the root table after processing an input. A [https://developer.electricimp.com/resources/metamethods metamethod] that overrides the slot deletion operator can be used to detect this. The following example demonstrates a system to conveniently define pre- and post- input hooks using a <code>SetInputHook</code> function:
{{ExpandBox|<source lang=js>
// Implementation


When the function is called, Script Handles of the activator and caller entities are accessible to the function under the variables<code>activator</code>and<code>caller</code>. The function needs to return a boolean value; Returning<code>true</code>processes the input, while<code>false</code>cancels it.
local PostInputFunc = null
|-
 
| <code>OnGameEvent_''name''</code>
::SetInputHook <- function(entity, input, pre_func, post_func)
| <code>void OnGameEvent_''name''(table ''params'')</code>
{
| Called each time a game event with the specified name occurs. The name of the function needs to be <code>OnGameEvent_</code> followed by the name of the game event. E.g. for the player_spawn input, it would be <code>OnGameEvent_player_spawn</code>.
entity.ValidateScriptScope()
local scope = entity.GetScriptScope()


When the function is called, a table is passed to the function with keys that vary depending on the event. For example, the player_spawn event passes a table with the keys <code>userid, team, class</code>, while the deadringer_cheat_death event passes a table with the keys <code>spy, attacker</code>.
if (post_func)
{
post_func = post_func.bindenv(scope)
local wrapper_func
if (pre_func)
{
pre_func = pre_func.bindenv(scope)
wrapper_func = function()
{
PostInputFunc = post_func
return pre_func()
}
}
else
{
wrapper_func = function()
{
PostInputFunc = post_func
return true
}
}


See [https://wiki.alliedmods.net/Team_Fortress_2_Events this page] for a list of game events as well as the table passed on each event.
scope["Input" + input]          <- wrapper_func
scope["Input" + input.tolower()] <- wrapper_func
}
else if (pre_func)
{
scope["Input" + input]          <- pre_func
scope["Input" + input.tolower()] <- pre_func
}
}


''Scripts containing OnGameEvent should also issue a call to the function __CollectGameEventCallbacks in order to work properly''
getroottable().setdelegate(
|-
{
| <code>OnPostSpawn</code>
_delslot = function(key) {
| <code>void OnPostSpawn()</code>
if (!(key in this))
| Called after the entity spawns, which is after scripts and players have loaded. This could be used to have an entity register itself with a master script, or adjusting the entity parameters in a programmatic way.
throw format("the index '%s' does not exist", key)
|-
 
| <code>Precache</code>
if (PostInputFunc && key == "activator")
{
PostInputFunc()
PostInputFunc = null
}
 
return rawdelete(key)
}
})
 
// Example that hooks the RunScriptCode input on worldspawn
 
function PreInputRunScriptCode()
{
printl("INPUT PRE: RunScriptCode")
printl("\tself: " + self)
printl("\tactivator: " + activator)
return true
}
 
function PostInputRunScriptCode()
{
printl("INPUT POST: RunScriptCode")
printl("\tself: " + self)
printl("\tactivator: " + activator)
}
 
local world = Entities.FindByClassname(null, "worldspawn")
SetInputHook(world, "RunScriptCode", PreInputRunScriptCode, PostInputRunScriptCode)
 
EntFire("worldspawn", "RunScriptCode", "printl(`RunScriptCode executed`)", 0, GetListenServerHost())
</source>}}
|}
}}
|-
| <code>OnGameEvent_<''name''></code>
| <code>void OnGameEvent_<''name''>(table ''params'')</code>
| Called each time a game event with the specified name occurs. The name of the function needs to be <code>OnGameEvent_</code> followed by the name of the game event. E.g. for the player_spawn input, it would be <code>OnGameEvent_player_spawn</code>.
 
When the function is called, a table is passed to the function with keys that vary depending on the event. For example, the player_spawn event passes a table with the keys <code>userid, team, class</code>, while the deadringer_cheat_death event passes a table with the keys <code>spy, attacker</code>.
 
A call to <code>__CollectGameEventCallbacks</code> is required to register this hook. See the [[Source_SDK_Base_2013/Scripting/VScript_Examples#Listening_for_Events|examples page]].
 
See [[Team_Fortress_2/Scripting/Game_Events|this page for a list of game events]] as well as the table passed on each event.
|-
| <code>Precache</code>
| <code>void Precache()</code>
| <code>void Precache()</code>
| Called after the script executes. Can be used to call precache functions for models and sounds on map load.
| Entity function that is called after the script executes, but before the entity is initialized. Can be used to call precache functions for models and sounds on map load.
{{tip|This can also be used to modify keyvalues on the entity, and it will use the new values when initializing.}}
|-
|-
| <code>OnTakeDamage</code>
| <code>ConnectOutputs</code>
| <code>void OnTakeDamage(handle ''params'')</code>
| <code>void ConnectOutputs(table ''scope'')</code>
| Called each time an entity takes damage. The script can modify the table entries not suffixed with ''const'', and these will be sent back to the game code.  
| Global function called after an entity with an script assigned spawns (i.e. <code>vscripts</code> keyvalue is not blank). Unlike <code>OnPostSpawn</code>, this is called immediately and therefore on map respawn, some entities may not exist during this point.
{{ModernNote|This is a special "entity hook" and works differently than the other hooks, see the example below for how to set it up.}}
{{note|This is a ''global'' hook and therefore will only work in global scope, unlike <code>Precache</code> and <code>OnPostSpawn</code>.}}
{{ModernNote|The [[worldspawn|world]] entity (brushes, static props etc) will not trigger this function by default as it normally can't 'receive' damage. However, the world can be made to 'allow' damage using the following code: <code>NetProps.SetPropInt(Entities.FindByClassname(null, "worldspawn"), "m_takedamage", 1)</code>. This does not appear to have any adverse side effects, and allows detecting when the world has been hit.}}
|-
{{ModernWarning|This is called before any actual damage processing is done. Certain entries might not be calculated or have different values compared to what ''will'' be calculated.}}
| <code>OnPostSpawn</code>
{{tip|Listen for the <code>player_hurt</code> or <code>npc_hurt</code> [[TF2_VScript_Examples#Listening_for_Events|event]] to effectively have an OnTakeDamage callback ''after'' final damage calculations are done.}}
| <code>void OnPostSpawn()</code>
| Entity function called after the entity is spawned and initialized, at the ''end'' of the frame. When map entities are respawned, this effectively runs after all scripts, players etc have been loaded. This could be used to have an entity register itself with a master script, or adjusting the entity parameters in a programmatic way.
|-
| <code>OnScriptHook_OnTakeDamage</code>
| <code>void OnScriptHook_OnTakeDamage(table ''params'')</code>
| Called each time an entity takes damage. The script can modify the table entries not prefixed with ''const'', and these will be sent back to the game code.
 
A call to <code>__CollectGameEventCallbacks</code> is required to register this hook. Internally, this hook is processed the same as a game event, but with the <code>OnScriptHook</code> prefix instead of <code>OnGameEvent</code>. Therefore, see the [[Source_2013_MP/Scripting/VScript_Examples#Listening_for_Events|example page for an explanation of how to register the hook]].
Example:
{{ExpandBox|<source lang=js>
local EventsID = UniqueString()
getroottable()[EventsID] <-
{
OnScriptHook_OnTakeDamage = function(params)
{
printl("OnScriptHook_OnTakeDamage")
if (params.const_entity.IsPlayer())
{
__DumpScope(1, params) // show parameters
params.damage = 0
}
}
 
// Cleanup events on round restart
OnGameEvent_scorestats_accumulated_update = function(_) { delete getroottable()[EventsID] }
}
local EventsTable = getroottable()[EventsID]
foreach (name, callback in EventsTable) EventsTable[name] = callback.bindenv(this)
__CollectGameEventCallbacks(EventsTable)
</source>}}
{{note|The [[worldspawn|world]] entity (brushes, static props etc) will not trigger this function by default as it normally can't 'receive' damage. However, the world can be made to 'allow' damage using the following code: <code>NetProps.SetPropInt(Entities.FindByClassname(null, "worldspawn"), "m_takedamage", 1)</code>. This does not appear to have any adverse side effects, and allows detecting when the world has been hit.}}
{{note|If called where the damage source is a player's hitscan weapon, player positions or angles fetched within the [[lag compensation]] "cone" of the attacker will be using lag compensated positions rather than their real positions.}}
{{note|Drowning damage does not trigger this hook. As a workaround, it can be detected in <code>player_hurt</code> event or disabled by setting <code>m_PainFinished</code> netprop to a very high value.}}
{{warning|This is called before any actual damage processing is done. Certain entries might not be calculated or have different values compared to what ''will'' be calculated.}}
{{tip|Listen for the <code>player_hurt</code> or <code>npc_hurt</code> (nextbots) [[TF2_VScript_Examples#Listening_for_Events|event]] to effectively have an OnTakeDamage callback ''after'' final damage calculations are done.}}
{{tip|<code>DMG_ACID</code> is set in <code>damage_type</code> for critical damage, and <code>DMG_SLOWBURN</code> for falloff. These flags can be toggled to add/remove crits or falloff respectively.}}
{{tip|The hitbox that got hit can be retrieved using the <code>m_LastHitGroup</code> netprop on [[player]] entities or [[generic_actor]]. The number corresponds to [[Team_Fortress_2/Scripting/Script_Functions/Constants#EHitGroup|Constants.EHitGroup]].}}
The table contains the following keys:
The table contains the following keys:
{| class="standard-table" style="width:100%"
{| class="standard-table" style="width:100%"
Line 761: Line 954:
| <code>const_entity</code>
| <code>const_entity</code>
| <code>handle</code>
| <code>handle</code>
| The entity which took damage
| The entity which took damage.
|-
|-
| <code>inflictor</code>
| <code>inflictor</code>
| <code>handle</code>
| <code>handle</code>
| The entity which dealt the damage, can be null
| The entity which dealt the damage, can be null.
|-
|-
| <code>weapon</code>
| <code>weapon</code>
| <code>handle</code>
| <code>handle</code>
| The weapon which dealt the damage, can be null
| The weapon which dealt the damage, can be null.
|-
|-
| <code>attacker</code>
| <code>attacker</code>
| <code>handle</code>
| <code>handle</code>
| The owner of the damage, can be null
| The owner of the damage, can be null.
|-
|-
| <code>damage</code>
| <code>damage</code>
| <code>float</code>
| <code>float</code>
| Damage amount
| Damage amount.
|-
|-
| <code>max_damage</code>
| <code>max_damage</code>
| <code>float</code>
| <code>float</code>
| Damage cap
| Damage cap.
|-
|-
| <code>damage_bonus</code>
| <code>damage_bonus</code>
| <code>float</code>
| <code>float</code>
| Additional damage (e.g. from crits)
| Additional damage (e.g. from crits).
{{warning|Always 0 because this hook is run before this is calculated.}}
|-
|-
| <code>damage_bonus_provider</code>
| <code>damage_bonus_provider</code>
| <code>handle</code>
| <code>handle</code>
| Owner of the damage bonus
| Owner of the damage bonus.
{{warning|Always 0 because this hook is run before this is calculated.}}
|-
|-
| <code>base_damage_const</code>
| <code>const_base_damage</code>
| <code>float</code>
| <code>float</code>
| Base damage
| Base damage.
|-
|-
| <code>damage_force</code>
| <code>damage_force</code>
| <code>Vector</code>
| <code>Vector</code>
| Damage force
| Damage force.
|-
|-
| <code>damage_for_force_calc</code>
| <code>damage_for_force_calc</code>
| <code>float</code>
| <code>float</code>
| If non-zero, this damage is used for force calculations
| {{bug|hidetested=1|This value does not seem to do anything.}}
|-
|-
| <code>damage_position</code>
| <code>damage_position</code>
| <code>Vector</code>
| <code>Vector</code>
| Where the damage actually came from
| World position of where the damage came from. E.g. end position of a bullet or a rocket.
|-
|-
| <code>reported_position</code>
| <code>reported_position</code>
| <code>Vector</code>
| <code>Vector</code>
| Where the damage supposedly came from
| World position of where the damage supposedly came from.
|-
|-
| <code>damage_type</code>
| <code>damage_type</code>
| <code>int</code>
| <code>int</code>
| Damage type. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#FDmgType|Constants.FDmgType]]
| Combination of damage types. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#FDmgType|Constants.FDmgType]]
|-
|-
| <code>damage_custom</code>
| <code>damage_custom</code>
| <code>int</code>
| <code>int</code>
| Special damage type. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFDmgCustom|Constants.ETFDmgCustom]]
| {{bug|hidetested=1|Because of a code oversight, this value is read-only. Use <code>damage_stats</code> instead which can be read and written.}}
|-
|-
| <code>damage_stats</code>
| <code>damage_stats</code>
| <code>int</code>
| <code>int</code>
| Unused
| Special damage type. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFDmgCustom|Constants.ETFDmgCustom]]. Unlike <code>damage_type</code>, only one custom damage type can be set.
|-
|-
| <code>force_friendly_fire</code>
| <code>force_friendly_fire</code>
| <code>bool</code>
| <code>bool</code>
| If true, force the damage to friendlyfire, regardless of this entity's and attacker's team
| If true, force the damage to friendlyfire, regardless of this entity's and attacker's team.
{{note|Hitscan/melee will not run OnTakeDamage unless the <code>mp_friendlyfire</code> convar is set to 1.}}
|-
|-
| <code>ammo_type</code>
| <code>ammo_type</code>
| <code>int</code>
| <code>int</code>
| Unused
| Unused.
|-
|-
| <code>player_penetration_count</code>
| <code>player_penetration_count</code>
| <code>int</code>
| <code>int</code>
| How many players the damage has penetrated so far
| How many players the damage has penetrated so far.
|-
|-
| <code>damaged_other_players</code>
| <code>damaged_other_players</code>
| <code>int</code>
| <code>int</code>
| How many players other than the attacker has the damage been applied to. Used for rocket jump damage reduction
| How many players other than the attacker has the damage been applied to. Used for rocket jump damage reduction.
|-
|-
| <code>crit_type</code>
| <code>crit_type</code>
| <code>int</code>
| <code>int</code>
| Type of crit damage. 0 - None, 1 - Mini, 2 - Full
| Type of crit damage. 0 - None, 1 - Mini, 2 - Full. The numbers correspond to [[Team_Fortress_2/Scripting/Script_Functions/Constants#ECritType|Constants.ECritType]].
|-
{{warning|Always 0 because this hook is run before this is set. You can check for <code>DMG_ACID</code> in <code>damage_type</code>, which is set when the shot will be critical, however, it doesn't show ordinary hits which would be converted to critical ones like Neon Annihilator hitting a soaked target or a Bushwacka hitting with a mini-crit. Alternative would be to check whether the damage is crit in <code>player_hurt</code> event, which also works for mini-crits as well, the downside is that this event happens only after the damage has been dealt so no changes inside the hook are possible.
 
If you want to force the damage to be critical you need to set <code>DMG_ACID</code> to be included in <code>damage_type</code>:
<source lang="js">
params.damage_type = params.damage_type | Constants.FDmgType.DMG_ACID
</source>
For players, if you want to force the damage to be a mini-crit you can add a mini-crit cond to the attacker inside this hook and remove it in <code>player_hurt</code> or <code>npc_hurt</code> respective events afterwards. Example:
{{ExpandBox|<source lang=js>
function RemoveBuff(player)
{
local scope = player.GetScriptScope()
if ("remove_buff" in scope && scope.remove_buff)
{
player.RemoveCond(Constants.ETFCond.TF_COND_OFFENSEBUFF)
scope.remove_buff = false
}
}
 
events <-
{
function OnScriptHook_OnTakeDamage(params)
{
local attacker = params.attacker
if (!attacker)
return
 
local scope = attacker.GetScriptScope()
if (!("force_minicrit" in scope) || !scope.force_minicrit)
return
 
if (attacker.InCond(Constants.ETFCond.TF_COND_OFFENSEBUFF))
return
 
if (params.const_entity.IsPlayer() ||
params.const_entity instanceof NextBotCombatCharacter)
{
attacker.AddCond(Constants.ETFCond.TF_COND_OFFENSEBUFF)
scope.remove_buff = true
}
}
 
function OnGameEvent_player_hurt(params)
{
local attacker = GetPlayerFromUserID(params.attacker)
if (!attacker)
return
 
RemoveBuff(attacker)
}
 
function OnGameEvent_npc_hurt(params)
{
local attacker = GetPlayerFromUserID(params.attacker_player)
if (!attacker)
return
 
RemoveBuff(attacker)
}
}
__CollectGameEventCallbacks(events)
 
 
local player = GetListenServerHost()
player.ValidateScriptScope()
local scope = player.GetScriptScope()
 
scope.force_minicrit <- true
scope.remove_buff <- false
</source>
{{bug|hidetested=1|Only mini-crits if the owner was alive during the hit, e.g. firing a rocket and dying before the rocket lands will not result in a mini-crit. When hitting the players you can apply TF_COND_MARKEDFORDEATH on them instead which would fix this issue, however, any hits to the victim from other sources that were dealt in the same tick as your intended mini-crit hit will also turn into the mini-crits.The addconds cannot be applied on nextbots making this solution completely irrelevant to them.}}
}}
}}
{{note|Setting this to 1 makes the damage act as a mini-crit, while producing full crit sounds and visuals, this can be used for cases where the attacker is not a player since only physical aspect of the damage would matter. Setting it to 2 has no effect.}}
|-
| <code>early_out</code>
| <code>early_out</code>
| <code>bool</code>
| <code>bool</code>
Line 848: Line 1,117:
|-
|-
|}
|}
Example:
|}
 
==== Callbacks ====
===== OnDestroy =====
It is possible to setup an asynchronous hook which is fired when the entity is deleted, as shown below. It is processed at the end of the frame after the entity's own destroy callback, but before the entity is about to be removed from memory. The caveats are that it is not possible to rescue an entity nor its children in this callback, and the targetname of the entity is cleared (this can be workarounded by storing the name in the script scope if needed). A useful application of this hook is to stop looping sounds on an entity so they don't persist.
{{ExpandBox|<source lang=js>
{{ExpandBox|<source lang=js>
function OnScriptHook_OnTakeDamage(params)
// Implementation
function SetDestroyCallback(entity, callback)
{
{
    printl("OnScriptHook_OnTakeDamage");
entity.ValidateScriptScope()
local scope = entity.GetScriptScope()
scope.setdelegate({}.setdelegate({
parent  = scope.getdelegate()
id      = entity.GetScriptId()
index    = entity.entindex()
callback = callback
_get = function(k)
{
return parent[k]
}
_delslot = function(k)
{
if (k == id)
{
entity = EntIndexToHScript(index)
local scope = entity.GetScriptScope()
scope.self <- entity
callback.pcall(scope)
}
delete parent[k]
}
})
)
}


    if (params.const_entity.IsPlayer())
// Example
    {
local entity = SpawnEntityFromTable("prop_dynamic",
        printl(params);
{
        params.damage = 0;
model = "models/player/heavy.mdl"
    }
origin = Vector(1, 2, 3)
}
})
__CollectGameEventCallbacks(this)
 
SetDestroyCallback(entity, function()
{
printf("Entity %s at %s was destroyed\n", self.GetClassname(), self.GetOrigin().ToKVString())
})
</source>}}
</source>}}
|}
 
{{note|All handles to the entity are destroyed when inside the callback. You must access the entity by using <code>self</code> only.}}
 
Alternatively: if entities need to be rescued from a deletion on a round restart, for example a player parented to a vehicle, the <code>scorestats_accumulated_update</code> event can be used. This event is fired on round restart right before all entities are removed. Add the <code>EFL_KILLME</code> eflag to the entities to rescue, then remove it after entities have spawned.


=== CBaseAnimating ===
=== CBaseAnimating ===
Extends [[#CBaseEntity|CBaseEntity]]
Extends [[#CBaseEntity|CBaseEntity ]]


Script handle class for animatable entities, such as props.
Script handle class for animatable entities, such as props.
Line 877: Line 1,182:
|-
|-
| <code>DispatchAnimEvents</code>
| <code>DispatchAnimEvents</code>
| <code>void DispatchAnimEvents(handle ''entity'')</code>
| <code>void DispatchAnimEvents(CBaseAnimating ''entity'')</code>
| Dispatch animation events to a CBaseAnimating entity.
| Dispatch animation events to a CBaseAnimating entity.
|-
|-
Line 885: Line 1,190:
|-
|-
| <code>GetAttachmentAngles</code>
| <code>GetAttachmentAngles</code>
| <code>QAngle GetAttachmentAngles(int ''ID'')</code>
| <code>QAngle GetAttachmentAngles(int ''id'')</code>
| Get an attachment's angles as a QAngle, by ID.
| Get an attachment's angles as a QAngle, by ID.
|-
|-
| <code>GetAttachmentBone</code>
| <code>GetAttachmentBone</code>
| <code>int GetAttachmentBone(int ''ID'')</code>
| <code>int GetAttachmentBone(int ''id'')</code>
| Get an attachment's parent bone index by ID.
| Get an attachment's parent bone index by ID.
|-
|-
| <code>GetAttachmentOrigin</code>
| <code>GetAttachmentOrigin</code>
| <code>Vector GetAttachmentOrigin(int ''ID'')</code>
| <code>Vector GetAttachmentOrigin(int ''id'')</code>
| Get an attachment's origin as a Vector, by ID.
| Get an attachment's origin as a Vector, by ID.
|-
|-
| <code>GetBodygroup</code>
| <code>GetBodygroup</code>
| <code>int GetBodygroup(int ''ID'')</code>
| <code>int GetBodygroup(int ''id'')</code>
| Get the bodygroup value by bodygroup ID.
| Get the bodygroup value by bodygroup ID.
|-
|-
| <code>GetBodygroupName</code>
| <code>GetBodygroupName</code>
| <code>string GetBodygroupName(int ''ID'')</code>
| <code>string GetBodygroupName(int ''id'')</code>
| Get the bodygroup's name by ID.
| Get the bodygroup's name by ID.
|-
|-
Line 909: Line 1,214:
|-
|-
| <code>GetBoneAngles</code>
| <code>GetBoneAngles</code>
| <code>QAngle GetBoneAngles(int ''ID'')</code>
| <code>QAngle GetBoneAngles(int ''id'')</code>
| Get the bone's angles as a QAngle, by ID.
| Get the bone's angles as a QAngle, by ID.
{{warning|For performance, bone transforms are cached by the game. The cache is updated once per frame. Setting new sequences, cycles etc may cause this to access stale bone data. If this is a problem, then call <code>SetModelSimple</code> first, which will update the bone cache.}}
|-
|-
| <code>GetBoneOrigin</code>
| <code>GetBoneOrigin</code>
| <code>Vector GetBoneOrigin(int ''ID'')</code>
| <code>Vector GetBoneOrigin(int ''id'')</code>
| Get the bone's origin Vector by ID.
| Get the bone's origin Vector by ID.
{{warning|See above.}}
|-
|-
| <code>GetCycle</code>
| <code>GetCycle</code>
| <code>float GetCycle()</code>
| <code>float GetCycle()</code>
| Gets the model's current animation cycle rate.
| Gets the model's current animation cycle rate. Ranges from 0.0 to 1.0.
|-
|-
| <code>GetModelScale</code>
| <code>GetModelScale</code>
Line 933: Line 1,240:
|-
|-
| <code>GetSequenceActivityName</code>
| <code>GetSequenceActivityName</code>
| <code>string GetSequenceActivityName(int ''ID'')</code>
| <code>string GetSequenceActivityName(int ''id'')</code>
| Get the activity name for a sequence by sequence ID.
| Get the activity name for a sequence by sequence ID.
|-
|-
| <code>GetSequenceDuration</code>
| <code>GetSequenceDuration</code>
| <code>float GetSequenceDuration(int ''ID'')</code>
| <code>float GetSequenceDuration(int ''id'')</code>
| Get a sequence duration in seconds by sequence ID.
| Get a sequence duration in seconds by sequence ID.
|-
|-
| <code>GetSequenceName</code>
| <code>GetSequenceName</code>
| <code>string GetSequenceName(int ''ID'')</code>
| <code>string GetSequenceName(int ''id'')</code>
| Get a sequence name by sequence ID.
| Get a sequence name by sequence ID. Returns "Not Found!" if ID is -1, "Unknown" if the sequence doesn't exist or "No model!" if no model is assigned.
|-
|-
| <code>GetSkin</code>
| <code>GetSkin</code>
Line 963: Line 1,270:
| <code>int LookupBone(string ''bone'')</code>
| <code>int LookupBone(string ''bone'')</code>
| Get the named bone index. Returns -1 if the bone does not exist.
| Get the named bone index. Returns -1 if the bone does not exist.
|-
| <code>LookupPoseParameter</code>
| <code>int LookupPoseParameter(string ''name'')</code>
| Gets the pose parameter's index. Returns -1 if the pose parameter does not exist.
|-
|-
| <code>LookupSequence</code>
| <code>LookupSequence</code>
Line 969: Line 1,280:
|-
|-
| <code>ResetSequence</code>
| <code>ResetSequence</code>
| <code>void ResetSequence(int ''ID'')</code>
| <code>void ResetSequence(int ''id'')</code>
| Reset a sequence by sequence ID. If the ID is different than the current sequence, switch to the new sequence.
| Reset a sequence by sequence ID. If the ID is different than the current sequence, switch to the new sequence.
|-
|-
| <code>SetBodygroup</code>
| <code>SetBodygroup</code>
| <code>void SetBodygroup(int ''ID'', int ''value'')</code>
| <code>void SetBodygroup(int ''id'', int ''value'')</code>
| Set the bodygroup by ID.
| Set the bodygroup by ID.
|-
|-
| <code>SetCycle</code>
| <code>SetCycle</code>
| <code>void SetCycle(float)</code>
| <code>void SetCycle(float ''cycle'')</code>
| Sets the model's current animation cycle
| Sets the model's current animation cycle from 0 to 1.
{{note|This only works if the entity has <code>m_bClientSideAnimation</code> set to false. Some entities such as [[prop_dynamic]] have this true by default and therefore SetCycle will visually not do anything until that netprop is turned off.}}
|-
|-
| <code>SetModelSimple</code>
| <code>SetModelSimple</code>
| <code>void SetModelSimple(string)</code>
| <code>void SetModelSimple(string ''model_name'')</code>
| Set a model for this entity. Matches easier behaviour of the SetModel input, automatically precaches, maintains sequence/cycle if possible.
| Set a model for this entity. Matches easier behaviour of the SetModel input, automatically precaches, maintains sequence/cycle if possible. Also clears the bone cache.
{{note|Does nothing on players. Use <code>SetCustomModel</code> in that case.}}
|-
|-
| <code>SetModelScale</code>
| <code>SetModelScale</code>
Line 993: Line 1,306:
|-
|-
| <code>SetPoseParameter</code>
| <code>SetPoseParameter</code>
| <code>float SetPoseParameter(int ''ID'', float ''value'')</code>
| <code>float SetPoseParameter(int ''id'', float ''value'')</code>
| Sets a pose parameter value. Returns the effective value after clamping or looping.
| Sets a pose parameter value. Returns the effective value after clamping or looping.
{{note|Does nothing on players. Pose parameters aren't networked on players.}}
{{bug|hidetested=1|[[prop_dynamic]] will have visual glitches with server-sided pose parameters. Use [[point_posecontroller]], or another entity like [[base_boss]] or [[funCBaseFlex]].}}
|-
|-
| <code>SetSequence</code>
| <code>SetSequence</code>
| <code>void SetSequence(int ''ID'')</code>
| <code>void SetSequence(int ''id'')</code>
| Plays a sequence by sequence ID.
| Plays a sequence by sequence ID.
{{warning|This can hause animation stutters when transitioning between sequences. Using <code>ResetSequence</code> instead will prevent this. Only tested on [[base_boss]].}}
{{warning|This can cause animation stutters when transitioning between sequences, or sequences to not be set at all on some entities (such as [[obj_sentrygun]]). Using <code>ResetSequence</code> instead will prevent this. Only tested on [[base_boss]].}}
{{note|Does nothing on players. Players use a different animation system.}}
|-
|-
| <code>SetSkin</code>
| <code>SetSkin</code>
Line 1,007: Line 1,323:
| <code>StopAnimation</code>
| <code>StopAnimation</code>
| <code>void StopAnimation()</code>
| <code>void StopAnimation()</code>
| Stop the current animation (same as SetPlaybackRate 0.0)
| Stop the current animation (same as SetPlaybackRate 0.0).
|-
|-
| <code>StudioFrameAdvance</code>
| <code>StudioFrameAdvance</code>
| <code>void StudioFrameAdvance()</code>
| <code>void StudioFrameAdvance()</code>
| Advance animation frame to some time in the future with an automatically calculated interval
| Advance animation frame to some time in the future with an automatically calculated interval.
|-
|-
| <code>StudioFrameAdvanceManual</code>
| <code>StudioFrameAdvanceManual</code>
| <code>void StudioFrameAdvanceManual(float)</code>
| <code>void StudioFrameAdvanceManual(float ''dt'')</code>
| Advance animation frame to some time in the future with a manual interval
| Advance animation frame to some time in the future with a manual interval.
|}
|}


=== CBaseCombatWeapon ===
=== CBaseCombatWeapon ===
Extends [[#CBaseAnimating|CBaseAnimating]]
Extends [[#CBaseAnimating|CBaseAnimating ]]


Script handle class for any weapon entities that can be part of a player's inventory.<br>
Script handle class for any weapon entities that can be part of a player's inventory.<br>
Line 1,032: Line 1,348:
| <code>CanBeSelected</code>
| <code>CanBeSelected</code>
| <code>bool CanBeSelected()</code>
| <code>bool CanBeSelected()</code>
| Can this weapon be selected
| Can this weapon be selected.
|-
|-
| <code>Clip1</code>
| <code>Clip1</code>
| <code>int Clip1()</code>
| <code>int Clip1()</code>
| Current ammo in clip1
| Current ammo in clip1.
|-
|-
| <code>Clip2</code>
| <code>Clip2</code>
| <code>int Clip2()</code>
| <code>int Clip2()</code>
| Current ammo in clip2
| Current ammo in clip2.
|-
|-
| <code>GetDefaultClip1</code>
| <code>GetDefaultClip1</code>
| <code>int GetDefaultClip1()</code>
| <code>int GetDefaultClip1()</code>
| Default size of clip1
| Default size of clip1.
|-
|-
| <code>GetDefaultClip2</code>
| <code>GetDefaultClip2</code>
| <code>int GetDefaultClip2()</code>
| <code>int GetDefaultClip2()</code>
| Default size of clip2
| Default size of clip2.
|-
|-
| <code>GetMaxClip1</code>
| <code>GetMaxClip1</code>
| <code>int GetMaxClip1()</code>
| <code>int GetMaxClip1()</code>
| Max size of clip1
| Max size of clip1.
|-
|-
| <code>GetMaxClip2</code>
| <code>GetMaxClip2</code>
| <code>int GetMaxClip2()</code>
| <code>int GetMaxClip2()</code>
| Max size of clip2
| Max size of clip2.
|-
|-
| <code>GetName</code>
| <code>GetName</code>
| <code>string GetName()</code>
| <code>string GetName()</code>
| Gets the weapon's name
| Gets the weapon's internal name (not the targetname!)
{{warning|This conflicts with CBaseEntity's <code>GetName</code> function. To get the targetname of the weapon, call it like this instead <code>CBaseEntity.GetName.call(weapon)</code>. Alternatively you can fetch the property directly <code>NetProps.GetPropString(weapon, "m_iName")</code>.}}
|-
|-
| <code>GetPosition</code>
| <code>GetPosition</code>
| <code>int GetPosition()</code>
| <code>int GetPosition()</code>
| Gets the weapon's current position
| Gets the weapon's current position.
|-
|-
| <code>GetPrimaryAmmoCount</code>
| <code>GetPrimaryAmmoCount</code>
| <code>int GetPrimaryAmmoCount()</code>
| <code>int GetPrimaryAmmoCount()</code>
| Current primary ammo count if no clip is used or to give a player if they pick up this weapon legacy style (not TF)
| Current primary ammo count if no clip is used or to give a player if they pick up this weapon legacy style (not TF).
|-
|-
| <code>GetPrimaryAmmoType</code>
| <code>GetPrimaryAmmoType</code>
| <code>int GetPrimaryAmmoType()</code>
| <code>int GetPrimaryAmmoType()</code>
| Returns the primary ammo type
| Returns the primary ammo type.
|-
|-
| <code>GetPrintName</code>
| <code>GetPrintName</code>
| <code>string GetPrintName()</code>
| <code>string GetPrintName()</code>
| Gets the weapon's print name
| Gets the weapon's print name.
|-
|-
| <code>GetSecondaryAmmoCount</code>
| <code>GetSecondaryAmmoCount</code>
| <code>int GetSecondaryAmmoCount()</code>
| <code>int GetSecondaryAmmoCount()</code>
| Current secondary ammo count if no clip is used or to give a player if they pick up this weapon legacy style (not TF)
| Current secondary ammo count if no clip is used or to give a player if they pick up this weapon legacy style (not TF).
|-
|-
| <code>GetSecondaryAmmoType</code>
| <code>GetSecondaryAmmoType</code>
| <code>int GetSecondaryAmmoType()</code>
| <code>int GetSecondaryAmmoType()</code>
| Returns the secondary ammo type
| Returns the secondary ammo type.
|-
|-
| <code>GetSlot</code>
| <code>GetSlot</code>
| <code>int GetSlot()</code>
| <code>int GetSlot()</code>
| Gets the weapon's current slot
| Gets the weapon's current slot.
|
|-
|-
| <code>GetSubType</code>
| <code>GetSubType</code>
| <code>int GetSubType()</code>
| <code>int GetSubType()</code>
| Get the weapon subtype
| Get the weapon subtype.
|-
|-
| <code>GetWeaponFlags</code>
| <code>GetWeaponFlags</code>
| <code>int GetWeaponFlags()</code>
| <code>int GetWeaponFlags()</code>
| Get the weapon flags
| Get the weapon flags.
|-
|-
| <code>GetWeight</code>
| <code>GetWeight</code>
| <code>int GetWeight()</code>
| <code>int GetWeight()</code>
| Get the weapon weighting/importance
| Get the weapon weighting/importance.
|-
|-
| <code>HasAnyAmmo</code>
| <code>HasAnyAmmo</code>
Line 1,121: Line 1,437:
| <code>IsMeleeWeapon</code>
| <code>IsMeleeWeapon</code>
| <code>bool IsMeleeWeapon()</code>
| <code>bool IsMeleeWeapon()</code>
| Returns whether this is a melee weapon
| Returns whether this is a melee weapon.
{{note|<code>tf_weapon_buff_item</code> (entity for Soldier's banner items), are considered melee in the code.}}
|-
|-
| <code>PrimaryAttack</code>
| <code>PrimaryAttack</code>
| <code>void PrimaryAttack()</code>
| <code>void PrimaryAttack()</code>
| Force a primary attack
| Force a primary attack.
{{ModernWarning|Hitscan and melee weapons require [[lag compensation]] information to be present, or the game will crash! Calling this from a player's think function is sufficient. Alternatively, lag compensation can be temporarily disabled which allows calling this function from anywhere, with the side effect of poor hit registration for high latency players. This can be achieved by setting the <code>m_bLagCompensation</code> [[#CNetPropManager|netprop]] on the player to to false, calling this function, and reverting it back to true.}}
{{tip|This allows arbitrarily firing weapons that do not actually belong to any player. This can be useful for creating entities that might not fully work on their own, for example rockets. Most weapons will work as long as the <code>m_hOwner</code> netprop on the weapon is set to an existing player. Weapons spawned manually might also need <code>SetClip(-1)</code>, and <code>m_flNextPrimaryAttack</code> (or <code>m_flSecondaryPrimaryAttack</code>) set to 0 before calling this function to always allow firing without delays.}}
{{warning|Hitscan and melee weapons require [[lag compensation]] information to be present, or the game will crash! Calling this from a player's think function or OnTakeDamage hook (whose source is a player's hitscan weapon) is sufficient. Alternatively, lag compensation can be temporarily disabled which allows calling this function from anywhere, with the side effect of poor hit registration for high latency players. This can be achieved by setting the <code>m_bLagCompensation</code> [[#CNetPropManager|netprop ]] on the player to to false, calling this function, and reverting it back to true.}}
{{warning|This will play the weapon's fire sound to everyone except the owner. If the sound is desired, the sound can be played to the owner exclusively via <code>EmitSoundEx</code>. If the sound is not desired, it can be stopped by calling <code>StopSound</code> after this function.}}
|-
|-
| <code>SecondaryAttack</code>
| <code>SecondaryAttack</code>
| <code>void SecondaryAttack()</code>
| <code>void SecondaryAttack()</code>
| Force a secondary attack
| Force a secondary attack.
{{ModernWarning|See above.}}
{{warning|See above.}}
|-
|-
| <code>SetClip1</code>
| <code>SetClip1</code>
Line 1,142: Line 1,461:
|-
|-
| <code>SetCustomViewModel</code>
| <code>SetCustomViewModel</code>
| <code>void SetCustomViewModel(string ''modelName'')</code>
| <code>void SetCustomViewModel(string ''model_name'')</code>
| Sets a custom view model for this weapon by model name.
| Sets a custom view model for this weapon by model name.
|-
|-
| <code>SetCustomViewModelModelIndex</code>
| <code>SetCustomViewModelModelIndex</code>
| <code>void SetCustomViewModelModelIndex(int ''modelIndex'')</code>
| <code>void SetCustomViewModelModelIndex(int ''model_index'')</code>
| Sets a custom view model for this weapon by modelindex.
| Sets a custom view model for this weapon by modelindex.
|-
|-
| <code>SetSubType</code>
| <code>SetSubType</code>
| <code>void SetSubType(int ''subtype'')</code>
| <code>void SetSubType(int ''subtype'')</code>
| Set the weapon subtype
| Set the weapon subtype.
|-
|-
| <code>UsesClipsForAmmo1</code>
| <code>UsesClipsForAmmo1</code>
Line 1,171: Line 1,490:
| <code>VisibleInWeaponSelection</code>
| <code>VisibleInWeaponSelection</code>
| <code>bool VisibleInWeaponSelection()</code>
| <code>bool VisibleInWeaponSelection()</code>
| Is this weapon visible in weapon selection
| Is this weapon visible in weapon selection?
|}
|}


=== CBaseFlex ===
=== CBaseFlex ===
Extends [[#CBaseAnimating|CBaseAnimating]]
Extends [[#CBaseAnimating|CBaseAnimating ]]


Animated characters who have vertex flex capability (e.g., facial expressions).  
Animated characters who have vertex flex capability (e.g., facial expressions).


==== Methods ====
==== Methods ====
Line 1,186: Line 1,505:
|-
|-
| <code>PlayScene</code>
| <code>PlayScene</code>
| <code>float PlayScene(string ''sceneFile'', float ''delay'')</code>
| <code>float PlayScene(string ''scene_file'', float ''delay'')</code>
| Play the specified .vcd file, causing the related characters to speak and subtitles to play.  
| Play the specified .vcd file, causing the related characters to speak and subtitles to play.
{{tip|Open <code>tf2_misc_dir.vpk</code> and browse the files in <code>scripts/talker/...</code> to find .vcd files. Alternatively, use the <code>rr_debugresponses 1</code> command with <code>developer 1</code> to find .vcds from in-game voicelines.}}
|}
|}


=== CBaseCombatCharacter ===
=== CBaseCombatCharacter ===
Extends [[#CBaseFlex|CBaseFlex]]
Extends [[#CBaseFlex|CBaseFlex ]]


Combat entities with similar movement capabilities to a player.
Combat entities with similar movement capabilities to a player.
Line 1,203: Line 1,523:
| <code>handle GetLastKnownArea()</code>
| <code>handle GetLastKnownArea()</code>
| Return the last nav area occupied, NULL if unknown.
| Return the last nav area occupied, NULL if unknown.
 
See [[#CTFNavArea|CTFNavArea ]].
See [[#CTFNavArea|CTFNavArea]].
|}
|}


=== CBasePlayer ===
=== CBasePlayer ===
Extends [[#CBaseCombatCharacter|CBaseCombatCharacter]]
Extends [[#CBaseCombatCharacter|CBaseCombatCharacter ]]


Script handle class for player entities.
Script handle class for player entities.
Line 1,240: Line 1,559:
|-
|-
| <code>SetForceLocalDraw</code>
| <code>SetForceLocalDraw</code>
| <code>void SetForceLocalDraw(bool ''forceDraw'')</code>
| <code>void SetForceLocalDraw(bool ''toggle'')</code>
| Forces the player to be drawn as if they were in thirdperson.
| Forces the player to be drawn as if they were in thirdperson.
|-
|-
Line 1,250: Line 1,569:
| <code>void SnapEyeAngles(QAngle ''angles'')</code>
| <code>void SnapEyeAngles(QAngle ''angles'')</code>
| Snap the player's eye angles to this.
| Snap the player's eye angles to this.
{{note|Do not use this if you are setting the angles temporarily and reverting it in the same frame (for example if firing projectiles at a specific angle). This will cause camera jitter in multiplayer. Instead, modify the <code>pl.v_angle</code> netprop and then revert that (which is what the game reads for eye angles internally). Example:
{{ExpandBox|<source lang=js>
local eye_angles = player.LocalEyeAngles()
NetProps.SetPropVector(player, "pl.v_angle", angles + Vector())
NetProps.SetPropEntity(flaregun, "m_hOwner", player)
NetProps.SetPropFloat(flaregun, "m_flNextPrimaryAttack", 0)
flaregun.PrimaryAttack()
NetProps.SetPropVector(player, "pl.v_angle", eye_angles + Vector())
</source>}}}}
|-
|-
| <code>ViewPunch</code>
| <code>ViewPunch</code>
| <code>void ViewPunch(QAngle ''angleOffset'')</code>
| <code>void ViewPunch(QAngle ''angle_offset'')</code>
| Ow! Punches the player's view.
| Ow! Punches the player's view.
|-
|-
Line 1,261: Line 1,591:


=== CBaseMultiplayerPlayer ===
=== CBaseMultiplayerPlayer ===
Extends [[#CBasePlayer|CBasePlayer]]
Extends [[#CBasePlayer|CBasePlayer ]]


Script handle sub-class for player entities in multiplayer games. No additional methods.
Script handle sub-class for player entities in multiplayer games. No additional methods.
Line 1,269: Line 1,599:


=== CEconEntity ===
=== CEconEntity ===
Extends [[#CBaseAnimating|CBaseAnimating]]
Extends [[#CBaseAnimating|CBaseAnimating ]]


Script handle class for economic exquisite equippables, meaning hats and weapons.
Script handle class for economic exquisite equippables, meaning hats and weapons.
Line 1,280: Line 1,610:
|-
|-
| <code>AddAttribute</code>
| <code>AddAttribute</code>
| <code>void AddAttribute(string ''name'', float ''value'', float ''delay'')</code>
| <code>void AddAttribute(string ''name'', float ''value'', float ''duration'')</code>
| Add an attribute to the entity. Set delay to -1 for the attributeto be applied instanteously.
| Add an attribute to the entity. <s>Set duration to 0 or lower for the attribute to be applied forever</s> See the bug below. The attribute must be one that exists in the game, invalid ones will not be added.
{{note|For players the attribute functions are named <code>AddCustomAttribute</code>, <code>GetCustomAttribute</code>, and <code>RemoveCustomAttribute</code>.}}
{{bug|hidetested=1|This method will always produce attributes with infinite duration, making the <code>duration</code> parameter non-functional.}}
{{warning|Some integer-valued attributes aren't being casted from floating point input number to an integer correctly. The game doesn't do a smart conversion from float to an integer (e.g. 230.0 -> 230), instead it just takes a bit representation of the input value and simply does a data type change (so 230.0 would actually become 1130758144, while they look a lot different in decimal, the bit representation of both numbers is the exact same). You're not allowed to pass in an integer as a value and the Squirrel does smart conversion to a float if you try to do so. The workaround is to wrap your integer value into <code>casti2f</code> which would do the same literal type change, but now from integer to the float, allowing the game to read it properly afterwards.
<source lang="js">
weapon.AddAttribute("paintkit_proto_def_index", casti2f(230), 0)
</source>
}}
|-
| <code>GetAttribute</code>
| <code>float GetAttribute(string ''name'', float ''default_value'')</code>
| Get an attribute float from the entity. If the attribute does not exist, returns <code>default_value</code>.
{{warning|See above, but in this case to receive the proper integer value use <code>castf2i</code>. Also make sure to restrict the number to 32 bit:
<source lang="js">
castf2i(weapon.GetAttribute("paintkit_proto_def_index", 0.0)) & 0xFFFFFFFF
</source>
}}
|-
|-
| <code>RemoveAttribute</code>
| <code>RemoveAttribute</code>
| <code>void RemoveAttribute(string ''name'')</code>
| <code>void RemoveAttribute(string ''name'')</code>
| Remove an attribute from the entity.
| Remove an attribute from the entity.
{{note|Static attributes (i.e. attributes that exist by default on the item) cannot be removed with this method.}}
{{Workaround|Instead, set <code>m_AttributeManager.m_Item.m_bOnlyIterateItemViewAttributes</code> [[#CNetPropManager|netprop ↓]] to true to remove all static attributes from the item. This allows for re-application of attributes.}}
|-
|-
| <code>ReapplyProvision</code>
| <code>ReapplyProvision</code>
Line 1,293: Line 1,641:


=== CTFPlayer ===
=== CTFPlayer ===
Extends [[#CBaseMultiplayerPlayer|CBaseMultiplayerPlayer]]
Extends [[#CBaseMultiplayerPlayer|CBaseMultiplayerPlayer ]]


Script handle class for [[player]] entities of Team Fortress 2.
Script handle class for [[player]] entities of Team Fortress 2.
Line 1,305: Line 1,653:
|-
|-
| <code>AddCond</code>
| <code>AddCond</code>
| <code>void AddCond(ETFCond ''cond'')</code>
| <code>void AddCond([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFCond|ETFCond]] ''cond'')</code>
|  
|
|-
|-
| <code>AddCondEx</code>
| <code>AddCondEx</code>
| <code>void AddCondEx(ETFCond ''cond'', float ''duration'', handle ''provider'')</code>
| <code>void AddCondEx([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFCond|ETFCond]] ''cond'', float ''duration'', handle ''provider'')</code>
|  
|
|-
|-
| <code>AddCurrency</code>
| <code>AddCurrency</code>
| <code>void AddCurrency(int)</code>
| <code>void AddCurrency(int ''amount'')</code>
| Kaching! Give the player some cash for game modes with upgrades, ie. MvM
| Kaching! Give the player some cash for game modes with upgrades, ie. MvM. The new value is bounded between 0-30000.
{{note|Using <code>RemoveCurrency</code>/<code>SetCurrency</code> instead or setting the <code>m_nCurrency</code> netprop directly will bypass the bounds checking.}}
|-
|-
| <code>AddCustomAttribute</code>
| <code>AddCustomAttribute</code>
| <code>void AddCustomAttribute(string ''name'', float ''value'', float ''delay'')</code>
| <code>void AddCustomAttribute(string ''name'', float ''value'', float ''duration'')</code>
| Add a custom attribute to the player. Set delay to -1 for the attribute to be applied instanteously.
| Add a custom attribute to the player. Set duration to 0 or lower for the attribute to be applied forever. The attribute must be one that exists in the game, invalid ones will not be added.
{{note|This does not work when applied in the <code>player_spawn</code> event, because custom attributes are cleared immediately after the event. As a workaround, it can be applied with a delay. See the [[Team_Fortress_2/Scripting/VScript_Examples#Adding_attributes_to_player_on_spawn|example]] code.}}
{{note|For weapons and cosmetics, the attribute functions are named <code>AddAttribute</code>, <code>GetAttribute</code>, and <code>RemoveAttribute</code>.}}
|-
| <code>AddHudHideFlags</code>
| <code>void AddHudHideFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FHideHUD|FHideHUD]] ''flags'')</code>
| Hides a hud element(-s).
|-
|-
| <code>ApplyPunchImpulseX</code>
| <code>ApplyPunchImpulseX</code>
| <code>bool ApplyPunchImpulseX(float)</code>
| <code>bool ApplyPunchImpulseX(float ''impulse'')</code>
|  
| Apply a view punch along the pitch angle. Used to flinch players when hit. If the player is a fully charged scoped-in sniper and the weapon has the <code>aiming_no_flinch</code> attribute, the punch will not apply. Returns true if the punch was applied.
|-
|-
| <code>BleedPlayer</code>
| <code>BleedPlayer</code>
| <code>void BleedPlayer(float)</code>
| <code>void BleedPlayer(float ''duration'')</code>
|  
| Make a player bleed for a set duration of time.
|-
|-
| <code>BleedPlayerEx</code>
| <code>BleedPlayerEx</code>
| <code>void BleedPlayerEx(float, int, bool, int)</code>
| <code>void BleedPlayerEx(float ''duration'', int ''damage'', bool ''endless'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFDmgCustom|ETFDmgCustom]] ''custom_damage_type'')</code>
|  
| Make a player bleed for a set duration of time, or forever, with specific damage per tick and damage_custom index.
|-
| <code>CancelTaunt</code>
| <code>void CancelTaunt()</code>
| Cancels any taunt in progress.
|-
|-
| <code>CanAirDash</code>
| <code>CanAirDash</code>
| <code>bool CanAirDash()</code>
| <code>bool CanAirDash()</code>
|  
| Can the player air dash/double jump?
|-
|-
| <code>CanBeDebuffed</code>
| <code>CanBeDebuffed</code>
| <code>bool CanBeDebuffed()</code>
| <code>bool CanBeDebuffed()</code>
|  
|
|-
|-
| <code>CanBreatheUnderwater</code>
| <code>CanBreatheUnderwater</code>
| <code>bool CanBreatheUnderwater()</code>
| <code>bool CanBreatheUnderwater()</code>
|  
|
|-
|-
| <code>CanDuck</code>
| <code>CanDuck</code>
Line 1,350: Line 1,709:
| <code>CanGetWet</code>
| <code>CanGetWet</code>
| <code>bool CanGetWet()</code>
| <code>bool CanGetWet()</code>
|  
| Can the player get wet by jarate/milk?
|-
|-
| <code>CanJump</code>
| <code>CanJump</code>
| <code>bool CanJump()</code>
| <code>bool CanJump()</code>
| Can the player jump?
| Can the player jump? Returns false if the player is taunting or if the <code>no_jump</code> attribute is present and non-zero. There is other conditions that prevent jumping but this function by itself doesn't check those.
|-
|-
| <code>ClearCustomModelRotation</code>
| <code>ClearCustomModelRotation</code>
Line 1,363: Line 1,722:
| <code>void ClearSpells()</code>
| <code>void ClearSpells()</code>
|
|
|-
| <code>ClearTauntAttack</code>
| <code>void ClearTauntAttack()</code>
| Stops active taunt from damaging or cancels Rock-Paper-Scissors result.
|-
|-
| <code>CanPlayerMove</code>
| <code>CanPlayerMove</code>
| <code>bool CanPlayerMove()</code>
| <code>bool CanPlayerMove()</code>
| Can the player move?
| Can the player move?
|-
| <code>DoTauntAttack</code>
| <code>void DoTauntAttack()</code>
| Performs taunts attacks if available. Player must be already taunting and taunt must have a valid attack assigned (<code>taunt attack name</code> attribute).
|-
|-
| <code>DropFlag</code>
| <code>DropFlag</code>
| <code>void DropFlag(bool)</code>
| <code>void DropFlag(bool ''silent'')</code>
| Force player to drop the flag.
| Force player to drop the flag (intelligence).
|-
|-
| <code>DropRune</code>
| <code>DropRune</code>
| <code>void DropRune(bool, int)</code>
| <code>void DropRune(bool ''apply_force'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'')</code>
| Force player to drop the rune.
| Force player to drop the rune.
{{tip|This can be abused to spawn arbitrary Mannpower powerups. See [[Team_Fortress_2/Scripting/VScript_Examples#Creating_Mannpower_powerups|the example]].}}
|-
| <code>EndLongTaunt</code>
| <code>void EndLongTaunt()</code>
| Stops a looping taunt (obeys minimum time rules and plays outro animation if available).
|-
|-
| <code>EquipWearableViewModel</code>
| <code>EquipWearableViewModel</code>
| <code>void EquipWearableViewModel(handle ''ent'')</code>
| <code>void EquipWearableViewModel(handle ''entity'')</code>
| Equips a wearble on the viewmodel. Intended to be used with ''tf_wearable_vm'' entities.
| Equips a wearable on the viewmodel. Intended to be used with [[tf_wearable_vm]] entities.
|-
|-
| <code>ExtinguishPlayerBurning</code>
| <code>ExtinguishPlayerBurning</code>
Line 1,387: Line 1,759:
| <code>void FiringTalk()</code>
| <code>void FiringTalk()</code>
| Makes eg. a heavy go AAAAAAAAAAaAaa like they are firing their minigun.
| Makes eg. a heavy go AAAAAAAAAAaAaa like they are firing their minigun.
{{note|This only works in a few situations as it requires certain gameplay conditions to be true. An example of when this will work: when the player is invulnerable.}}
{{bug|hidetested=1|Unfortunately does not work for Heavy's minigun due to the above quirk.}}
{{workaround|The input <code>SpeakResponseConcept</code> can be used to play voicelines by supplying a [[Team_Fortress_2/Scripting/Script_Functions/Constants#MP_CONCEPT|Concept]].}}
|-
|-
| <code>ForceChangeTeam</code>
| <code>ForceChangeTeam</code>
| <code>void ForceChangeTeam(int ''team'', bool ''full_team_switch'')</code>
| <code>void ForceChangeTeam([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'', bool ''full_team_switch'')</code>
| Force player to change their team. Setting the bool to true will not remove nemesis relationships or reset the player's class, aswell as not slaying the player.
| Force player to change their team. Setting the bool to true will not remove nemesis relationships or reset the player's class, as well as not slaying the player.
  {{note|This will not work if a player is in a duel. Setting the <code>m_bIsCoaching</code> [[Team_Fortress_2/Script_Functions#CNetPropManager|netprop]] to true on the player and reverting it afterwards is a workaround.}}
  {{note|This will not work if a player is in a duel. Setting the <code>m_bIsCoaching</code> [[#CNetPropManager|netprop ]] to true on the player and reverting it afterwards is a workaround.}}
|-
|-
| <code>ForceRegenerateAndRespawn</code>
| <code>ForceRegenerateAndRespawn</code>
| <code>void ForceRegenerateAndRespawn()</code>
| <code>void ForceRegenerateAndRespawn()</code>
| Force regenerates and respawns the player
| Force regenerates and respawns the player.
{{note|This will not work if the player does not have a desired class set. This can be worked around by setting the <code>m_Shared.m_iDesiredPlayerClass</code> netprop to a class index.}}
|-
|-
| <code>ForceRespawn</code>
| <code>ForceRespawn</code>
| <code>void ForceRespawn()</code>
| <code>void ForceRespawn()</code>
| Force respawns the player
| Force respawns the player.
{{note|This will not work if the player does not have a desired class set. This can be worked around by setting the <code>m_Shared.m_iDesiredPlayerClass</code> netprop to a class index.}}
|-
|-
| <code>GetActiveWeapon</code>
| <code>GetActiveWeapon</code>
| <code>handle GetActiveWeapon()</code>
| <code>CTFWeapon GetActiveWeapon()</code>
| Get the player's current weapon
| Get the player's current weapon.
|-
|-
| <code>GetBackstabs</code>
| <code>GetBackstabs</code>
| <code>int GetBackstabs()</code>
| <code>int GetBackstabs()</code>
|  
|
|-
|-
| <code>GetBonusPoints</code>
| <code>GetBonusPoints</code>
Line 1,419: Line 1,796:
| <code>GetBuildingsDestroyed</code>
| <code>GetBuildingsDestroyed</code>
| <code>int GetBuildingsDestroyed()</code>
| <code>int GetBuildingsDestroyed()</code>
|  
|
|-
|-
| <code>GetCaptures</code>
| <code>GetCaptures</code>
| <code>int GetCaptures()</code>
| <code>int GetCaptures()</code>
|  
|
|-
|-
| <code>GetClassEyeHeight</code>
| <code>GetClassEyeHeight</code>
| <code>Vector GetClassEyeHeight()</code>
| <code>Vector GetClassEyeHeight()</code>
| Gets the eye height of the player
| Gets the eye height of the player.
|-
|-
| <code>GetCondDuration</code>
| <code>GetCondDuration</code>
| <code>float GetCondDuration(ETFCond ''cond'')</code>
| <code>float GetCondDuration([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFCond|ETFCond]] ''cond'')</code>
|  
| Returns duration of the condition. Returns 0 if the cond is not applied. Returns -1 if the cond is infinite.
|-
| <code>GetCustomAttribute</code>
| <code>float GetCustomAttribute(string ''name'', float ''default_value'')</code>
| Get an attribute float from the player. If the attribute does not exist, returns <code>default_value</code>.
|-
|-
| <code>GetCurrency</code>
| <code>GetCurrency</code>
| <code>int GetCurrency()</code>
| <code>int GetCurrency()</code>
| Get player's cash for game modes with upgrades, ie. MvM
| Get player's cash for game modes with upgrades, ie. MvM.
|-
|-
| <code>GetCurrentTauntMoveSpeed</code>
| <code>GetCurrentTauntMoveSpeed</code>
| <code>float GetCurrentTauntMoveSpeed()</code>
| <code>float GetCurrentTauntMoveSpeed()</code>
|  
|
|-
|-
| <code>GetDefenses</code>
| <code>GetDefenses</code>
| <code>int GetDefenses()</code>
| <code>int GetDefenses()</code>
|  
|
|-
|-
| <code>GetDisguiseAmmoCount</code>
| <code>GetDisguiseAmmoCount</code>
| <code>int GetDisguiseAmmoCount()</code>
| <code>int GetDisguiseAmmoCount()</code>
|  
|
|-
|-
| <code>GetDisguiseTarget</code>
| <code>GetDisguiseTarget</code>
| <code>handle GetDisguiseTarget()</code>
| <code>CTFPlayer GetDisguiseTarget()</code>
|  
|
|-
|-
| <code>GetDisguiseTeam</code>
| <code>GetDisguiseTeam</code>
| <code>int GetDisguiseTeam()</code>
| <code>int GetDisguiseTeam()</code>
|  
|
|-
|-
| <code>GetDominations</code>
| <code>GetDominations</code>
| <code>int GetDominations()</code>
| <code>int GetDominations()</code>
|  
|
|-
|-
| <code>GetGrapplingHookTarget</code>
| <code>GetGrapplingHookTarget</code>
Line 1,467: Line 1,848:
| <code>GetHeadshots</code>
| <code>GetHeadshots</code>
| <code>int GetHeadshots()</code>
| <code>int GetHeadshots()</code>
|  
|
|-
|-
| <code>GetHealPoints</code>
| <code>GetHealPoints</code>
| <code>int GetHealPoints()</code>
| <code>int GetHealPoints()</code>
|  
|
|-
|-
| <code>GetHealTarget</code>
| <code>GetHealTarget</code>
| <code>handle GetHealTarget()</code>
| <code>handle GetHealTarget()</code>
| Who is the medic healing?
| Who is the medic healing?
|-
| <code>GetHudHideFlags</code>
| <code>int GetHudHideFlags()</code>
| Gets current hidden hud elements.
See [[Team_Fortress_2/Scripting/Script_Functions/Constants#FHideHUD|Constants.FHideHUD]].
|-
|-
| <code>GetInvulns</code>
| <code>GetInvulns</code>
| <code>int GetInvulns()</code>
| <code>int GetInvulns()</code>
|  
|
|-
|-
| <code>GetKillAssists</code>
| <code>GetKillAssists</code>
| <code>int GetKillAssists()</code>
| <code>int GetKillAssists()</code>
|  
|
|-
|-
| <code>GetLastWeapon</code>
| <code>GetLastWeapon</code>
| <code>GetLastWeapon()</code>
| <code>CTFWeapon GetLastWeapon()</code>
|
|
|-
|-
Line 1,507: Line 1,893:
| <code>GetRageMeter</code>
| <code>GetRageMeter</code>
| <code>float GetRageMeter()</code>
| <code>float GetRageMeter()</code>
|  
|
|-
|-
| <code>GetResupplyPoints</code>
| <code>GetResupplyPoints</code>
| <code>int GetResupplyPoints()</code>
| <code>int GetResupplyPoints()</code>
|  
|
|-
|-
| <code>GetRevenge</code>
| <code>GetRevenge</code>
| <code>int GetRevenge()</code>
| <code>int GetRevenge()</code>
|  
|
|-
|-
| <code>GetScoutHypeMeter</code>
| <code>GetScoutHypeMeter</code>
| <code>float GetScoutHypeMeter()</code>
| <code>float GetScoutHypeMeter()</code>
|  
|
|-
|-
| <code>GetSpyCloakMeter</code>
| <code>GetSpyCloakMeter</code>
| <code>float GetSpyCloakMeter()</code>
| <code>float GetSpyCloakMeter()</code>
|  
|
|-
|-
| <code>GetTeleports</code>
| <code>GetTeleports</code>
| <code>int GetTeleports()</code>
| <code>int GetTeleports()</code>
|  
|
|-
| <code>GetTauntAttackTime</code>
| <code>float GetTauntAttackTime()</code>
| Timestamp until a taunt attack "lasts". 0 if unavailable.
|-
| <code>GetTauntRemoveTime</code>
| <code>float GetTauntRemoveTime()</code>
| Timestamp until taunt is stopped.
|-
| <code>GetVehicleReverseTime</code>
| <code>float GetVehicleReverseTime()</code>
| Timestamp when kart was reversed.
|-
|-
| <code>GetTimeSinceCalledForMedic</code>
| <code>GetTimeSinceCalledForMedic</code>
| <code>float GetTimeSinceCalledForMedic()</code>
| <code>float GetTimeSinceCalledForMedic()</code>
| When did the player last call medic
| When did the player last call medic.
|-
|-
| <code>GrantOrRemoveAllUpgrades</code>
| <code>GrantOrRemoveAllUpgrades</code>
| <code>GrantOrRemoveAllUpgrades(bool, bool)</code>
| <code>void GrantOrRemoveAllUpgrades(bool ''remove'', bool ''refund'')</code>
|
|
|-
|-
| <code>HasItem</code>
| <code>HasItem</code>
| <code>bool HasItem()</code>
| <code>bool HasItem()</code>
| Currently holding an item? Eg. capture flag
| Currently holding an item? Eg. capture flag.
{{tip|Fetch the <code>m_hItem</code> netprop to get the entity handle.}}
|-
| <code>HandleTauntCommand</code>
| <code>void HandleTauntCommand(int ''taunt_slot'')</code>
| Spoofs a taunt command from the player, as if they selected this taunt. This can be abused to give the player any taunt, see the [[Team_Fortress_2/Scripting/VScript_Examples#Giving a taunt|examples page]].
|-
|-
| <code>IgnitePlayer</code>
| <code>IgnitePlayer</code>
| <code>void IgnitePlayer()</code>
| <code>void IgnitePlayer()</code>
|
| Supposed to set the player on fire, but... {{bug|hidetested=1|Does nothing except play on-fire sound and voicelines. {{workaround|Create a [[trigger_ignite]] and EntFire <code>StartTouch</code> input on it.}}}}
|-
|-
| <code>InAirDueToExplosion</code>
| <code>InAirDueToExplosion</code>
| <code>bool InAirDueToExplosion()</code>
| <code>bool InAirDueToExplosion()</code>
|  
|
|-
|-
| <code>InAirDueToKnockback</code>
| <code>InAirDueToKnockback</code>
| <code>bool InAirDueToKnockback()</code>
| <code>bool InAirDueToKnockback()</code>
|  
|
|-
|-
| <code>InCond</code>
| <code>InCond</code>
| <code>bool InCond(ETFCond ''cond'')</code>
| <code>bool InCond([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFCond|ETFCond]] ''cond'')</code>
|  
|
|-
|-
| <code>IsAirDashing</code>
| <code>IsAirDashing</code>
| <code>bool IsAirDashing()</code>
| <code>bool IsAirDashing()</code>
|  
|
|-
| <code>IsAllowedToRemoveTaunt</code>
| <code>bool IsAllowedToRemoveTaunt()</code>
| Returns true if the taunt will be stopped.
|-
|-
| <code>IsAllowedToTaunt</code>
| <code>IsAllowedToTaunt</code>
| <code>bool IsAllowedToTaunt()</code>
| <code>bool IsAllowedToTaunt()</code>
|  
|
|-
|-
| <code>IsBotOfType</code>
| <code>IsBotOfType</code>
| <code>bool IsBotOfType(int)</code>
| <code>bool IsBotOfType([[Team_Fortress_2/Scripting/Script_Functions/Constants#EBotType|EBotType]] ''type'')</code>
|
| Returns true if the player matches this bot type. Only one type of bot exists which is reserved for AI bots (not [https://wiki.teamfortress.com/wiki/Bots#Puppet_bots puppet bots]). 0 is used for real players or puppet bots. Use <code>IsFakeClient</code> to check for a puppet bot instead.
|-
|-
| <code>IsCallingForMedic</code>
| <code>IsCallingForMedic</code>
Line 1,575: Line 1,982:
| <code>IsCarryingRune</code>
| <code>IsCarryingRune</code>
| <code>bool IsCarryingRune()</code>
| <code>bool IsCarryingRune()</code>
|  
|
|-
|-
| <code>IsControlStunned</code>
| <code>IsControlStunned</code>
| <code>bool IsControlStunned()</code>
| <code>bool IsControlStunned()</code>
|  
|
|-
|-
| <code>IsCritBoosted</code>
| <code>IsCritBoosted</code>
| <code>bool IsCritBoosted()</code>
| <code>bool IsCritBoosted()</code>
|  
|
|-
|-
| <code>IsFakeClient</code>
| <code>IsFakeClient</code>
| <code>bool IsFakeClient()</code>
| <code>bool IsFakeClient()</code>
|
| Returns true if the player is a puppet or AI bot. To check if the player is a AI bot (<code>CTFBot</code>) specifically, use <code>IsBotOfType</code> instead.
|-
|-
| <code>IsFireproof</code>
| <code>IsFireproof</code>
| <code>bool IsFireproof()</code>
| <code>bool IsFireproof()</code>
|  
|
|-
|-
| <code>IsFullyInvisible</code>
| <code>IsFullyInvisible</code>
| <code>bool IsFullyInvisible()</code>
| <code>bool IsFullyInvisible()</code>
|  
|
|-
|-
| <code>IsHypeBuffed</code>
| <code>IsHypeBuffed</code>
| <code>bool IsHypeBuffed()</code>
| <code>bool IsHypeBuffed()</code>
|  
|
|-
|-
| <code>IsImmuneToPushback</code>
| <code>IsImmuneToPushback</code>
| <code>bool IsImmuneToPushback()</code>
| <code>bool IsImmuneToPushback()</code>
|  
|
|-
|-
| <code>IsInspecting</code>
| <code>IsInspecting</code>
| <code>bool IsInspecting()</code>
| <code>bool IsInspecting()</code>
|  
|
|-
|-
| <code>IsInvulnerable</code>
| <code>IsInvulnerable</code>
| <code>bool IsInvulnerable()</code>
| <code>bool IsInvulnerable()</code>
|  
|
|-
|-
| <code>IsJumping</code>
| <code>IsJumping</code>
| <code>bool IsJumping()</code>
| <code>bool IsJumping()</code>
|  
|
|-
|-
| <code>IsMiniBoss</code>
| <code>IsMiniBoss</code>
Line 1,623: Line 2,030:
| <code>IsParachuteEquipped</code>
| <code>IsParachuteEquipped</code>
| <code>bool IsParachuteEquipped()</code>
| <code>bool IsParachuteEquipped()</code>
|  
|
|-
|-
| <code>IsPlacingSapper</code>
| <code>IsPlacingSapper</code>
| <code>bool IsPlacingSapper()</code>
| <code>bool IsPlacingSapper()</code>
| Returns true if we placed a sapper in the last few moments
| Returns true if we placed a sapper in the last few moments.
|-
| <code>IsPlayer</code>
| <code>IsPlayer()</code>
|
|-
|-
| <code>IsRageDraining</code>
| <code>IsRageDraining</code>
| <code>bool IsRageDraining()</code>
| <code>bool IsRageDraining()</code>
|  
|
|-
|-
| <code>IsRegenerating</code>
| <code>IsRegenerating</code>
| <code>bool IsRegenerating()</code>
| <code>bool IsRegenerating()</code>
|  
|
|-
|-
| <code>IsSapping</code>
| <code>IsSapping</code>
| <code>bool IsSapping()</code>
| <code>bool IsSapping()</code>
| Returns true if we are currently sapping
| Returns true if we are currently sapping.
|-
|-
| <code>IsSnared</code>
| <code>IsSnared</code>
| <code>bool IsSnared()</code>
| <code>bool IsSnared()</code>
|  
|
|-
|-
| <code>IsStealthed</code>
| <code>IsStealthed</code>
| <code>bool IsStealthed()</code>
| <code>bool IsStealthed()</code>
|  
|
|-
| <code>IsTaunting</code>
| <code>bool IsTaunting()</code>
|
|-
|-
| <code>IsUsingActionSlot</code>
| <code>IsUsingActionSlot</code>
| <code>bool IsUsingActionSlot()</code>
| <code>bool IsUsingActionSlot()</code>
|  
|
|-
|-
| <code>IsViewingCYOAPDA</code>
| <code>IsViewingCYOAPDA</code>
| <code>bool IsViewingCYOAPDA()</code>
| <code>bool IsViewingCYOAPDA()</code>
|
|
|-
| <code>IsViewingCYOAPDA</code>
| <code>bool IsViewingCYOAPDA()</code>
|  
|-
|-
| <code>Regenerate</code>
| <code>Regenerate</code>
| <code>void Regenerate(bool)</code>
| <code>void Regenerate(bool ''refill_health_ammo'')</code>
| Resupplies a player. If regen health/ammo is set, clears negative conds, gives back player health/ammo
| Resupplies a player. If refill health/ammo is set, clears negative conds, gives back player health/ammo.
|-
|-
| <code>RemoveAllItems</code>
| <code>RemoveAllItems</code>
| <code>void RemoveAllItems(bool)</code>
| <code>void RemoveAllItems(bool ''unused'')</code>
|
| {{bug|hidetested=1|This does not actually remove all items. It only drops the passtime ball, intelligence, disables radius healing, and hides the Spy invis watch.
{{workaround|Iterate through player's children, and destroy subclass instances of CEconEntity.
{{ExpandBox|<source lang=js>
function RemoveAllItems(player)
{
// If you destroy an entity it becomes invalid
// It will not longer keep a track of the next child and .NextMovePeer method becomes unavailable so the next iteration will fail
// To prevent this you can store a reference the next child
for (local next, current = player.FirstMoveChild(); current != null; current = next)
{
NetProps.SetPropBool(current, "m_bForcePurgeFixedupStrings", true)
// Store the next handle
next = current.NextMovePeer()
if (current instanceof CEconEntity)
current.Destroy()
}
}
 
//Example
RemoveAllItems(GetListenServerHost())
</source>}}
}}
}}
|-
|-
| <code>RemoveAllObjects</code>
| <code>RemoveAllObjects</code>
| <code>void RemoveAllObjects(bool)</code>
| <code>void RemoveAllObjects(bool ''explode'')</code>
| Remove all player objects. Eg. dispensers/sentries.
| Remove all player objects. Eg. dispensers/sentries.
|-
|-
| <code>RemoveCond</code>
| <code>RemoveCond</code>
| <code>void RemoveCond(ETFCond ''cond'')</code>
| <code>void RemoveCond([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFCond|ETFCond]] ''cond'')</code>
|  
| Removes a condition. Does not remove a condition if the minimum duration has not passed. Does nothing if the condition isn't added (interally does <code>InCond</code> check).
|-
|-
| <code>RemoveCondEx</code>
| <code>RemoveCondEx</code>
| <code>void RemoveCondEx(ETFCond ''cond'', bool ''ignoreDuration'')</code>
| <code>void RemoveCondEx([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFCond|ETFCond]] ''cond'', bool ''ignore_duration'')</code>
|
| Extended version of above function. Allows forcefully removing the condition even if minimum duration is not met.
|-
|-
| <code>RemoveCurrency</code>
| <code>RemoveCurrency</code>
| <code>void RemoveCurrency(int)</code>
| <code>void RemoveCurrency(int ''amount'')</code>
| Take away money from a player for reasons such as ie. spending.
| Take away money from a player for reasons such as ie. spending. Lower bounded to 0.
{{note|Unlike <code>AddCurrency</code>, negative values will go past the 30000 limit.}}
|-
|-
| <code>RemoveCustomAttribute</code>
| <code>RemoveCustomAttribute</code>
| <code>void RemoveCustomAttribute(string)</code>
| <code>void RemoveCustomAttribute(string ''name'')</code>
| Remove a custom attribute to the player
| Remove a custom attribute to the player.
|-
|-
| <code>RemoveDisguise</code>
| <code>RemoveDisguise</code>
| <code>void RemoveDisguise()</code>
| <code>void RemoveDisguise()</code>
| Undisguise a spy.
| Undisguise a spy.
|-
| <code>RemoveHudHideFlags</code>
| <code>void RemoveHudHideFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FHideHUD|FHideHUD]] ''flags'')</code>
| Unhides a hud element(-s).
|-
|-
| <code>RemoveInvisibility</code>
| <code>RemoveInvisibility</code>
Line 1,707: Line 2,137:
| <code>ResetScores</code>
| <code>ResetScores</code>
| <code>void ResetScores()</code>
| <code>void ResetScores()</code>
|  
|
|-
|-
| <code>RollRareSpell</code>
| <code>RollRareSpell</code>
Line 1,714: Line 2,144:
|-
|-
| <code>SetCondDuration</code>
| <code>SetCondDuration</code>
| <code>void SetCondDuration(ETFCond ''cond'', float ''duration'')</code>
| <code>void SetCondDuration([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFCond|ETFCond]] ''cond'', float ''duration'')</code>
|  
|
|-
|-
| <code>SetCurrency</code>
| <code>SetCurrency</code>
| <code>void SetCurrency(int)</code>
| <code>void SetCurrency(int ''amount'')</code>
| Set player's cash for game modes with upgrades, ie. MvM
| Set player's cash for game modes with upgrades, ie. MvM. Does not have any bounds checking.
|-
|-
| <code>SetCurrentTauntMoveSpeed</code>
| <code>SetCurrentTauntMoveSpeed</code>
| <code>void SetCurrentTauntMoveSpeed(float)</code>
| <code>void SetCurrentTauntMoveSpeed(float ''speed'')</code>
|  
|
|-
|-
| <code>SetCustomModel</code>
| <code>SetCustomModel</code>
| <code>void SetCustomModel(string)</code>
| <code>void SetCustomModel(string ''model_name'')</code>
|  
| Sets a custom player model without animations (model will T-pose). To enable animations, use <code>SetCustomModelWithClassAnimations</code> instead.
|-
|-
| <code>SetCustomModelOffset</code>
| <code>SetCustomModelOffset</code>
| <code>void SetCustomModelOffset(Vector)</code>
| <code>void SetCustomModelOffset(Vector ''offset'')</code>
|  
|
|-
|-
| <code>SetCustomModelRotates</code>
| <code>SetCustomModelRotates</code>
| <code>void SetCustomModelRotates(bool)</code>
| <code>void SetCustomModelRotates(bool ''toggle'')</code>
|  
|
|-
|-
| <code>SetCustomModelRotation</code>
| <code>SetCustomModelRotation</code>
| <code>void SetCustomModelRotation(QAngle)</code>
| <code>void SetCustomModelRotation(QAngle ''angles'')</code>
|  
|
|-
|-
| <code>SetCustomModelVisibleToSelf</code>
| <code>SetCustomModelVisibleToSelf</code>
| <code>void SetCustomModelVisibleToSelf(bool)</code>
| <code>void SetCustomModelVisibleToSelf(bool ''toggle'')</code>
|  
|
|-
|-
| <code>SetCustomModelWithClassAnimations</code>
| <code>SetCustomModelWithClassAnimations</code>
| <code>void SetCustomModelWithClassAnimations(string)</code>
| <code>void SetCustomModelWithClassAnimations(string ''model_name'')</code>
|
| Sets a custom player model with full animations.
|-
|-
| <code>SetDisguiseAmmoCount</code>
| <code>SetDisguiseAmmoCount</code>
| <code>void SetDisguiseAmmoCount(int)</code>
| <code>void SetDisguiseAmmoCount(int ''count'')</code>
|  
|
|-
|-
| <code>SetForcedTauntCam</code>
| <code>SetForcedTauntCam</code>
| <code>void SetForcedTauntCam(int)</code>
| <code>void SetForcedTauntCam(int ''toggle'')</code>
|  
|
|-
|-
| <code>SetGrapplingHookTarget</code>
| <code>SetGrapplingHookTarget</code>
| <code>void SetGrapplingHookTarget(handle, bool)</code>
| <code>void SetGrapplingHookTarget(handle ''entity'', bool ''bleed'')</code>
| Set the player's target grapple entity
| Set the player's target grapple entity.
|-
| <code>SetHudHideFlags</code>
| <code>void SetHudHideFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FHideHUD|FHideHUD]] ''flags'')</code>
| Force hud hide flags to a value.
|-
|-
| <code>SetIsMiniBoss</code>
| <code>SetIsMiniBoss</code>
| <code>void SetIsMiniBoss(bool)</code>
| <code>void SetIsMiniBoss(bool ''toggle'')</code>
| Make this player an MvM mini-boss.
| Make this player an MvM mini-boss.
|-
|-
| <code>SetNextChangeClassTime</code>
| <code>SetNextChangeClassTime</code>
| <code>void SetNextChangeClassTime(float)</code>
| <code>void SetNextChangeClassTime(float ''time'')</code>
| Set next change class time.
| Set next change class time.
|-
|-
| <code>SetNextChangeTeamTime</code>
| <code>SetNextChangeTeamTime</code>
| <code>void SetNextChangeTeamTime(float)</code>
| <code>void SetNextChangeTeamTime(float ''time'')</code>
| Set next change team time.
| Set next change team time.
|-
|-
| <code>SetNextRegenTime</code>
| <code>SetNextRegenTime</code>
| <code>void SetNextRegenTime(float)</code>
| <code>void SetNextRegenTime(float ''time'')</code>
| Set next health regen time.
| Set next available resupply time.
|-
|-
| <code>SetPlayerClass</code>
| <code>SetPlayerClass</code>
| <code>void SetPlayerClass(int)</code>
| <code>void SetPlayerClass([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFClass|ETFClass]] ''class_index'')</code>
| Sets the player class. Updates the player's visuals and model.
| Sets the player class. Updates the player's visuals and model.
{{note|Does not force the class to be changed and can be buggy for server-side scripts. This can be resolved by calling <code>NetProps.SetPropInt(player, "m_Shared.m_iDesiredPlayerClass", class_index)</code> after <code>SetPlayerClass</code> and before <code>ForceRegenerateAndRespawn</code>. This resolves issues like the player respawning as their "desired" class instead or loadout showing the desired class rather than what they are.}}
{{note|Does not regenerate class properties, such as health or weapons. This can be done by calling <code>ForceRegenerateAndRespawn</code> afterwards.}}
{{note|Does not regenerate class properties, such as health or weapons. This can be done by calling <code>ForceRegenerateAndRespawn</code> afterwards.}}
{{warning|If the player is not respawned, the hitbox set will be used from the old class! Calling <code>SetCustomModel</code> with a blank parameter is sufficient to update it.}}
{{warning|If the player is not respawned, the hitbox set will be used from the old class! Calling <code>SetCustomModel</code> with a blank parameter is sufficient to update it.}}
|-
|-
| <code>SetRageMeter</code>
| <code>SetRageMeter</code>
| <code>void SetRageMeter(float)</code>
| <code>void SetRageMeter(float ''percent'')</code>
|  
| Sets rage meter from 0 - 100.
|-
| <code>SetRPSResult</code>
| <code>void SetRPSResult(int ''result'')</code>
| Rig the result of Rock-Paper-Scissors (0 - rock, 1 - paper, 2 - scissors).
|-
|-
| <code>SetScoutHypeMeter</code>
| <code>SetScoutHypeMeter</code>
| <code>void SetScoutHypeMeter(float)</code>
| <code>void SetScoutHypeMeter(float ''percent'')</code>
|  
| Sets hype meter from 0 - 100.
|-
|-
| <code>SetSpyCloakMeter</code>
| <code>SetSpyCloakMeter</code>
| <code>void SetSpyCloakMeter(float)</code>
| <code>void SetSpyCloakMeter(float)</code>
|  
| Sets cloakmeter from 0 - 100.
|-
| <code>SetVehicleReverseTime</code>
| <code>void SetVehicleReverseTime(float ''time'')</code>
| Set the timestamp when kart was reversed.
|-
|-
| <code>SetUseBossHealthBar</code>
| <code>SetUseBossHealthBar</code>
| <code>void SetUseBossHealthBar(bool)</code>
| <code>void SetUseBossHealthBar(bool ''toggle'')</code>
|  
|
|-
| <code>StopTaunt</code>
| <code>void StopTaunt(bool ''remove_prop'')</code>
| Stops current taunt. If ''remove_prop'' is true, the taunt prop will be immediately deleted instead of potentially delaying.
|-
| <code>StunPlayer</code>
| <code>void StunPlayer(float ''duration'', float ''move_speed_reduction'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#TF_STUN|TF_STUN]] ''flags'', handle ''attacker'')</code>
| Stuns the player for a specified duration. Move speed reduction is a fraction (0 = no reduction. 1 = total reduction, no movement). Flag combinations control the stun type and behavior. {{tip|To produce "scared" particle effects and sounds use the combination <code>TF_STUN_LOSER_STATE&#124;TF_STUN_BY_TRIGGER</code> as stun flags.}}
|-
| <code>Taunt</code>
| <code>void Taunt([[Team_Fortress_2/Scripting/Script_Functions/Constants#FTaunts|FTaunts]] ''taunt_index'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#MP_CONCEPT|MP_CONCEPT]] ''taunt_concept'')</code>
| Performs a taunt if allowed. Concept is the "voiceline" index to use with the taunt. For <code>TAUNT_SHOW_ITEM</code> and <code>TAUNT_BASE_WEAPON</code> this is set automatically. <code>TAUNT_LONG</code> is not supported.
{{tip|TAUNT_MISC_ITEM with a concept of <code>MP_CONCEPT_TAUNT_LAUGH</code> will make the player laugh. Concept <code>MP_CONCEPT_TAUNT_REPLAY</code> will play the replay taunt.}}
{{tip|To perform any taunt such as conga, see the [[Team_Fortress_2/Scripting/VScript_Examples#Giving a taunt|examples page]].}}
|-
|-
| <code>TryToPickupBuilding</code>
| <code>TryToPickupBuilding</code>
| <code>bool TryToPickupBuilding()</code>
| <code>bool TryToPickupBuilding()</code>
| Make the player attempt to pick up a building in front of them
| Make the player attempt to pick up a building in front of them.
|-
|-
| <code>UpdateSkin</code>
| <code>UpdateSkin</code>
| <code>UpdateSkin(num)</code>
| <code>void UpdateSkin(int ''skin'')</code>
|
|
|-
|-
| <code>WasInCond</code>
| <code>WasInCond</code>
| <code>bool WasInCond(ETFCond ''cond'')</code>
| <code>bool WasInCond([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFCond|ETFCond]] ''cond'')</code>
|  
|
|-
|-
| <code>Weapon_CanUse</code>
| <code>Weapon_CanUse</code>
| <code>bool Weapon_CanUse(handle ''weapon'')</code>
| <code>bool Weapon_CanUse(CTFWeapon ''weapon'')</code>
|  
|
|-
|-
| <code>Weapon_Drop</code>
| <code>Weapon_Drop</code>
| <code>void Weapon_Drop(handle ''weapon'')</code>
| <code>void Weapon_Drop(CTFWeapon ''weapon'')</code>
| Does nothing!
| Does nothing!
|-
|-
| <code>Weapon_DropEx</code>
| <code>Weapon_DropEx</code>
| <code>void Weapon_DropEx(handle ''weapon'', Vector ''target'', Vector ''velocity'')</code>
| <code>void Weapon_DropEx(CTFWeapon ''weapon'', Vector ''target'', Vector ''velocity'')</code>
|  
| Does nothing!
|-
|-
| <code>Weapon_Equip</code>
| <code>Weapon_Equip</code>
| <code>void Weapon_Equip(handle ''weapon'')</code>
| <code>void Weapon_Equip(CTFWeapon ''weapon'')</code>
|  
| Equips a weapon in the player. This places it inside the <code>m_hMyWeapons</code> array.
|-
|-
| <code>Weapon_SetLast</code>
| <code>Weapon_SetLast</code>
| <code>void Weapon_SetLast(handle ''weapon'')</code>
| <code>void Weapon_SetLast(CTFWeapon ''weapon'')</code>
|  
|
|-
|-
| <code>Weapon_ShootPosition</code>
| <code>Weapon_ShootPosition</code>
| <code>Vector Weapon_ShootPosition()</code>
| <code>Vector Weapon_ShootPosition()</code>
|  
| The same as calling <code>EyePosition</code>.
{{note|While the weapon shoot position matches with eye position for hitscan and melee weapons, it does not reflect the actual shoot position of most projectile weapons since they have an additional offset from the eye location. To get the exact shoot position you can use the following function:
{{ExpandBox|<source lang=js>
function GetWeaponShootPosition(player)
{
local weapon = player.GetActiveWeapon()
local offset = null
 
switch (NetProps.GetPropInt(weapon, "m_AttributeManager.m_Item.m_iItemDefinitionIndex"))
{
case 441: // The Cow Mangler
offset = Vector(23.5, 8.0, player.GetFlags() & Constants.FPlayer.FL_DUCKING ? 8.0 : -3.0)
break
case 513: // The Original
offset = Vector(23.5, 0.0, player.GetFlags() & Constants.FPlayer.FL_DUCKING ? 8.0 : -3.0)
break
case 18: // Rocket Launcher
case 127: // The Direct Hit
case 1104: // The Air Strike
case 205: // Rocket Launcher (Renamed/Strange)
case 228: // The Black Box
case 237: // Rocket Jumper
case 414: // The Liberty Launcher
case 658: // Festive Rocket Launcher
case 730: // The Beggar's Bazooka
case 800: // Silver Botkiller Rocket Launcher Mk.I
case 809: // Gold Botkiller Rocket Launcher Mk.I
case 889: // Rust Botkiller Rocket Launcher Mk.I
case 898: // Blood Botkiller Rocket Launcher Mk.I
case 907: // Carbonado Botkiller Rocket Launcher Mk.I
case 916: // Diamond Botkiller Rocket Launcher Mk.I
case 965: // Silver Botkiller Rocket Launcher Mk.II
case 974: // Gold Botkiller Rocket Launcher Mk.II
case 1085: // Festive Black Box
case 15006: // Woodland Warrior
case 15014: // Sand Cannon
case 15028: // American Pastoral
case 15043: // Smalltown Bringdown
case 15052: // Shell Shocker
case 15057: // Aqua Marine
case 15081: // Autumn
case 15104: // Blue Mew
case 15105: // Brain Candy
case 15129: // Coffin Nail
case 15130: // High Roller's
case 15150: // Warhawk
case 39: // The Flare Gun
case 351: // The Detonator
case 595: // The Manmelter
case 740: // The Scorch Shot
case 1081: // Festive Flare Gun
offset = Vector(23.5, 12.0, player.GetFlags() & Constants.FPlayer.FL_DUCKING ? 8.0 : -3.0)
break
case 56: // Hunstman
case 1005: // Festive Huntsman
case 1092: // The Fortified Compound
case 997: // Rescue Ranger
case 305: // Crusader's Crossbow
case 1079: // Festive Crusader's Crossbow
offset = Vector(23.5, 12.0, -3.0)
break
case 442: // The Righteous Bison
case 588: // The Pomson 6000
offset = Vector(23.5, 8.0, player.GetFlags() & Constants.FPlayer.FL_DUCKING ? 8.0 : -3.0)
break
case 222: // The Mad Milk
case 1121: // Mutated Milk
case 1180: // Gas Passer
case 58: // Jarate
case 751: // Festive Jarate
case 1105: // The Self-Aware Beauty Mark
case 19: // Grenade Launcher
case 206: // Grenade Launcher (Renamed/Strange)
case 308: // The Loch-n-Load
case 996: // The Loose Cannon
case 1007: // Festive Grenade Launcher
case 1151: // The Iron Bomber
case 15077: // Autumn
case 15079: // Macabre Web
case 15091: // Rainbow
case 15092: // Sweet Dreams
case 15116: // Coffin Nail
case 15117: // Top Shelf
case 15142: // Warhawk
case 15158: // Butcher Bird
case 20: // Stickybomb Launcher
case 207: // Stickybomb Launcher (Renamed/Strange)
case 130: // The Scottish Resistance
case 265: // Sticky Jumper
case 661: // Festive Stickybomb Launcher
case 797: // Silver Botkiller Stickybomb Launcher Mk.I
case 806: // Gold Botkiller Stickybomb Launcher Mk.I
case 886: // Rust Botkiller Stickybomb Launcher Mk.I
case 895: // Blood Botkiller Stickybomb Launcher Mk.I
case 904: // Carbonado Botkiller Stickybomb Launcher Mk.I
case 913: // Diamond Botkiller Stickybomb Launcher Mk.I
case 962: // Silver Botkiller Stickybomb Launcher Mk.II
case 971: // Gold Botkiller Stickybomb Launcher Mk.II
case 1150: // The Quickiebomb Launcher
case 15009: // Sudden Flurry
case 15012: // Carpet Bomber
case 15024: // Blasted Bombardier
case 15038: // Rooftop Wrangler
case 15045: // Liquid Asset
case 15048: // Pink Elephant
case 15082: // Autumn
case 15083: // Pumpkin Patch
case 15084: // Macabre Web
case 15113: // Sweet Dreams
case 15137: // Coffin Nail
case 15138: // Dressed to Kill
case 15155: // Blitzkrieg
offset = Vector(16.0, 8.0, -6.0)
break
case 17: // Syringe Gun
case 204: // Syringe Gun (Renamed/Strange)
case 36: // The Blutsauger
case 412: // The Overdose
offset = Vector(16.0, 6.0, -8.0)
break
case 812: // The Flying Guillotine
case 833: // The Flying Guillotine (Genuine)
offset = Vector(32.0, 0.0, 15.0)
break
case 528: // The Short Curcuit
offset = Vector(40.0, 15.0, -10.0)
break
case 44: // Sandman
case 648: // The Wrap Assassin
return player.GetOrigin() + player.GetModelScale() *
(player.EyeAngles().Forward() * 32.0 + Vector(0.0, 0.0, 50.0))
default:
return player.EyePosition()
}
 
if (Convars.GetClientConvarValue("cl_flipviewmodels", player.entindex()) == "1")
offset.y *= -1
 
local eye_angles = player.EyeAngles()
return player.EyePosition() +
eye_angles.Up() * offset.z +
eye_angles.Left() * offset.y +
eye_angles.Forward() * offset.x
}
 
// Example usage
// Works only for the rocket launchers
local player = GetListenServerHost()
local eye_position = player.EyePosition()
local shoot_position = GetWeaponShootPosition(player)
local eye_vector = player.EyeAngles().Forward()
 
local trace =
{
start = shoot_position
end = eye_position + eye_vector * 32768.0
ignore = player
hullmin = Vector(-1.0, -1.0, -1.0)
hullmax = Vector(1.0, 1.0, 1.0)
}
TraceHull(trace)
 
DebugDrawLine(shoot_position, trace.pos, 255, 255, 255, false, 5.0)
DebugDrawBox(trace.pos, Vector(-2.0, -2.0, -2.0), Vector(2.0, 2.0, 2.0), 255, 0, 0, 255, 5.0)
</source>}}
}}
|-
|-
| <code>Weapon_Switch</code>
| <code>Weapon_Switch</code>
| <code>void Weapon_Switch(handle ''weapon'')</code>
| <code>void Weapon_Switch(CTFWeapon ''weapon'')</code>
|  
| Attempts a switch to the given weapon, if present in the player's inventory (<code>m_hMyWeapons</code> array).
{{note|Most of the time a weapon switch will succeed, except in these circumstances. Workarounds are provided in each case to allow a forced switch.
* Revved with a minigun
* Just fired with a sniper rifle
* Blowing the horn of a banner item
* Holding Half-Zatoichi and under 50 health
* Backstab stun from a Razorback
-> Set <code>m_hActiveWeapon</code> netprop on the player to null. {{warning|Do not take the lazy way out and run this workaround for every weapon, it will break other weapons like the Huntsman. Only run this workaround for the specific class of weapons above.}}
 
* Player has <code>TF_COND_CANNOT_SWITCH_FROM_MELEE</code> condition (from eating Buffalo Steak Sandvich) and is holding a melee
-> Remove <code>TF_COND_CANNOT_SWITCH_FROM_MELEE</code> condition.
 
* Using the Thermal Thruster:
<source lang=js>
// assuming "weapon" is the thermal thruster
NetProps.SetPropEntity(player, "m_hActiveWeapon", null)
if (player.InCond(Constants.ETFCond.TF_COND_ROCKETPACK))
{
// needed to stop air sound
SendGlobalGameEvent("rocketpack_landed", { userid = GetPlayerUserID(player) })
player.RemoveCond(Constants.ETFCond.TF_COND_ROCKETPACK)
}
 
</source>
}}
|}
|}


=== CTFBot ===
=== CTFBot ===
Extends [[#CTFPlayer|CTFPlayer]] and [[#NextBotCombatCharacter|NextBotCombatCharacter]]
Extends [[#CTFPlayer|CTFPlayer ]] and [[#NextBotCombatCharacter|NextBotCombatCharacter ]]


Script handle class for bot-controlled players aka [[tf_bot]]. Beep boop.
Script handle class for bot-controlled players aka [[tf_bot]]. Beep boop.
{{note|[https://wiki.teamfortress.com/wiki/Bots#Puppet_bots Puppet bots] do ''not'' inherit from this class.}}


==== Methods ====
==== Methods ====
Line 1,853: Line 2,501:
|-
|-
| <code>AddBotAttribute</code>
| <code>AddBotAttribute</code>
| <code>void AddBotAttribute(int)</code>
| <code>void AddBotAttribute([[Team_Fortress_2/Scripting/Script_Functions/Constants#FTFBotAttributeType|FTFBotAttributeType]] ''attribute'')</code>
| Sets attribute flags on this TFBot
| Sets attribute flags on this TFBot.
|-
|-
| <code>AddBotTag</code>
| <code>AddBotTag</code>
| <code>void AddBotTag(string)</code>
| <code>void AddBotTag(string ''tag'')</code>
| Adds a bot tag
| Adds a bot tag.
|-
|-
| <code>AddWeaponRestriction</code>
| <code>AddWeaponRestriction</code>
| <code>void AddWeaponRestriction(int)</code>
| <code>void AddWeaponRestriction([[Team_Fortress_2/Scripting/Script_Functions/Constants#TFBotWeaponRestrictionType|TFBotWeaponRestrictionType]] ''flags'')</code>
| Adds weapon restriction flags
| Adds weapon restriction flags.
|-
|-
| <code>ClearAllBotAttributes</code>
| <code>ClearAllBotAttributes</code>
| <code>void ClearAllBotAttributes()</code>
| <code>void ClearAllBotAttributes()</code>
| Clears all attribute flags on this TFBot
| Clears all attribute flags on this TFBot.
|-
|-
| <code>ClearAllBotTags</code>
| <code>ClearAllBotTags</code>
| <code>void ClearAllBotTags()</code>
| <code>void ClearAllBotTags()</code>
| Clears bot tags
| Clears bot tags.
|-
|-
| <code>ClearAllWeaponRestrictions</code>
| <code>ClearAllWeaponRestrictions</code>
| <code>void ClearAllWeaponRestrictions()</code>
| <code>void ClearAllWeaponRestrictions()</code>
| Removes all weapon restriction flags
| Removes all weapon restriction flags.
|-
|-
| <code>ClearAttentionFocus</code>
| <code>ClearAttentionFocus</code>
| <code>void ClearAttentionFocus()</code>
| <code>void ClearAttentionFocus()</code>
| Clear current focus
| Clear current focus.
|-
| <code>ClearBehaviorFlag</code>
| <code>void ClearBehaviorFlag([[Team_Fortress_2/Scripting/Script_Functions/Constants#TFBOT_BEHAVIOR|TFBOT_BEHAVIOR]] ''flags'')</code>
| Clear the given behavior flag(s) for this bot.
|-
|-
| <code>DelayedThreatNotice</code>
| <code>DelayedThreatNotice</code>
| <code>void DelayedThreatNotice(handle, float)</code>
| <code>void DelayedThreatNotice(handle ''threat'', float ''delay'')</code>
| Notice the threat after a delay in seconds.
|-
|-
| <code>DisbandCurrentSquad</code>
| <code>DisbandCurrentSquad</code>
| <code>void DisbandCurrentSquad()</code>
| <code>void DisbandCurrentSquad()</code>
| Forces the current squad to be entirely disbanded by everyone
| Forces the current squad to be entirely disbanded by everyone.
|-
|-
| <code>FindVantagePoint</code>
| <code>FindVantagePoint</code>
| <code>handle FindVantagePoint(float)</code>
| <code>CTFNavArea FindVantagePoint(float ''max_distance'')</code>
| Get the nav area of the closest vantage point (within distance)
| Get the nav area of the closest vantage point (within distance).
|-
|-
| <code>GenerateAndWearItem</code>
| <code>GenerateAndWearItem</code>
| <code>void GenerateAndWearItem(string)</code>
| <code>void GenerateAndWearItem(string ''item_name'')</code>
| Give me an item!
| Give me an item!
|-
| <code>GetActionPoint</code>
| <code>handle GetActionPoint()</code>
| Get the given action point for this bot.
|-
| <code>GetAllBotTags</code>
| <code>void GetAllBotTags(table ''result'')</code>
| Get all bot tags. The key is the index, and the value is the tag.
|-
|-
| <code>GetHomeArea</code>
| <code>GetHomeArea</code>
| <code>handle GetHomeArea()</code>
| <code>CTFNavArea GetHomeArea()</code>
| Sets the home nav area of the bot
| Sets the home nav area of the bot.
|-
|-
| <code>GetDifficulty</code>
| <code>GetDifficulty</code>
| <code>[[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotDifficultyType|ETFBotDifficultyType]] GetDifficulty()</code>
| <code>int GetDifficulty()</code>
| Returns the bot's difficulty level
| Returns the bot's difficulty level. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotDifficultyType|Constants.ETFBotDifficultyType]].
|-
|-
| <code>GetMaxVisionRangeOverride</code>
| <code>GetMaxVisionRangeOverride</code>
| <code>float GetMaxVisionRangeOverride()</code>
| <code>float GetMaxVisionRangeOverride()</code>
| Gets the max vision range override for the bot {{warning|MaxVisionRange overrides, as well as certain other bot modifiers, can persist after a bot has been moved to spectator and assigned a new class/loadout in MvM! Identifying MvM bots by the MaxVisionRange override set in a popfile may not be reliable.}}  
| Gets the max vision range override for the bot {{warning|MaxVisionRange overrides, as well as certain other bot modifiers, can persist after a bot has been moved to spectator and assigned a new class/loadout in MvM! Identifying MvM bots by the MaxVisionRange override set in a popfile may not be reliable.}}
|-
| <code>GetMission</code>
| <code>int GetMission()</code>
| Get this bot's current mission. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotMissionType|ETFBotMissionType]].
|-
| <code>GetMissionTarget</code>
| <code>handle GetMissionTarget()</code>
| Get this bot's current mission target.
|-
|-
| <code>GetNearestKnownSappableTarget</code>
| <code>GetNearestKnownSappableTarget</code>
| <code>handle GetNearestKnownSappableTarget()</code>
| <code>handle GetNearestKnownSappableTarget()</code>
| Gets the nearest known sappable target
| Gets the nearest known sappable target.
|-
| <code>GetPrevMission</code>
| <code>int GetPrevMission()</code>
| Get this bot's previous mission. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotMissionType|ETFBotMissionType]].
|-
|-
| <code>GetSpawnArea</code>
| <code>GetSpawnArea</code>
| <code>handle GetSpawnArea()</code>
| <code>CTFNavArea GetSpawnArea()</code>
| Return the nav area of where we spawned
| Return the nav area of where we spawned.
|-
|-
| <code>GetSquadFormationError</code>
| <code>GetSquadFormationError</code>
Line 1,920: Line 2,593:
|-
|-
| <code>HasBotAttribute</code>
| <code>HasBotAttribute</code>
| <code>bool HasBotAttribute(int)</code>
| <code>bool HasBotAttribute([[Team_Fortress_2/Scripting/Script_Functions/Constants#FTFBotAttributeType|FTFBotAttributeType]] ''attribute'')</code>
| Checks if this TFBot has the given attributes
| Checks if this TFBot has the given attributes.
|-
|-
| <code>HasBotTag</code>
| <code>HasBotTag</code>
| <code>bool HasBotTag(string)</code>
| <code>bool HasBotTag(string ''tag'')</code>
| Checks if this TFBot has the given bot tag
| Checks if this TFBot has the given bot tag.
|-
| <code>HasMission</code>
| <code>bool HasMission([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotMissionType|ETFBotMissionType]] ''mission'')</code>
| Return true if the given mission is this bot's current mission.
|-
|-
| <code>HasWeaponRestriction</code>
| <code>HasWeaponRestriction</code>
| <code>bool HasWeaponRestriction(int)</code>
| <code>bool HasWeaponRestriction([[Team_Fortress_2/Scripting/Script_Functions/Constants#TFBotWeaponRestrictionType|TFBotWeaponRestrictionType]] ''flags'')</code>
| Checks if this TFBot has the given weapon restriction flags
| Checks if this TFBot has the given weapon restriction flags.
|-
|-
| <code>IsAmmoFull</code>
| <code>IsAmmoFull</code>
| <code>bool IsAmmoFull()</code>
| <code>bool IsAmmoFull()</code>
|  
|
|-
|-
| <code>IsAmmoLow</code>
| <code>IsAmmoLow</code>
| <code>bool IsAmmoLow()</code>
| <code>bool IsAmmoLow()</code>
|  
|
|-
|-
| <code>IsAttentionFocused</code>
| <code>IsAttentionFocused</code>
Line 1,944: Line 2,621:
|-
|-
| <code>IsAttentionFocusedOn</code>
| <code>IsAttentionFocusedOn</code>
| <code>bool IsAttentionFocusedOn(handle)</code>
| <code>bool IsAttentionFocusedOn(handle ''entity'')</code>
| Is our attention focused on this entity
| Is our attention focused on this entity.
|-
| <code>IsBehaviorFlagSet</code>
| <code>bool IsBehaviorFlagSet([[Team_Fortress_2/Scripting/Script_Functions/Constants#TFBOT_BEHAVIOR|TFBOT_BEHAVIOR]] ''flags'')</code>
| Return true if the given behavior flag(s) are set for this bot.
|-
|-
| <code>IsDifficulty</code>
| <code>IsDifficulty</code>
| <code>bool IsDifficulty(int)</code>
| <code>bool IsDifficulty([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotDifficultyType|ETFBotDifficultyType]] ''difficulty'')</code>
| Returns true/false if the bot's difficulty level matches.
| Returns true/false if the bot's difficulty level matches.
|-
|-
| <code>IsInASquad</code>
| <code>IsInASquad</code>
| <code>bool IsInASquad()</code>
| <code>bool IsInASquad()</code>
| Checks if we are in a squad
| Checks if we are in a squad.
|-
| <code>IsOnAnyMission</code>
| <code>bool IsOnAnyMission()</code>
| Return true if this bot has a current mission.
|-
|-
| <code>IsWeaponRestricted</code>
| <code>IsWeaponRestricted</code>
| <code>bool IsWeaponRestricted(handle)</code>
| <code>bool IsWeaponRestricted(handle ''weapon'')</code>
| Checks if the given weapon is restricted for use on the bot
| Checks if the given weapon is restricted for use on the bot.
|-
|-
| <code>LeaveSquad</code>
| <code>LeaveSquad</code>
| <code>void LeaveSquad()</code>
| <code>void LeaveSquad()</code>
| Makes us leave the current squad (if any)
| Makes us leave the current squad (if any).
|-
|-
| <code>PressAltFireButton</code>
| <code>PressAltFireButton</code>
| <code>void PressAltFireButton(float ''duration'')</code>
| <code>void PressAltFireButton(float ''duration'' = -1)</code>
|  
|  
|-
|-
| <code>PressFireButton</code>
| <code>PressFireButton</code>
| <code>void PressFireButton(float ''duration'')</code>
| <code>void PressFireButton(float ''duration'' = -1)</code>
|  
|
|-
|-
| <code>PressSpecialFireButton</code>
| <code>PressSpecialFireButton</code>
| <code>void PressSpecialFireButton(float ''duration'')</code>
| <code>void PressSpecialFireButton(float ''duration'' = -1)</code>
|
|-
|-
| <code>RemoveBotAttribute</code>
| <code>RemoveBotAttribute</code>
| <code>void RemoveBotAttribute(int)</code>
| <code>void RemoveBotAttribute([[Team_Fortress_2/Scripting/Script_Functions/Constants#FTFBotAttributeType|FTFBotAttributeType]] ''attribute'')</code>
| Removes attribute flags on this TFBot
| Removes attribute flags on this TFBot.
|-
|-
| <code>RemoveBotTag</code>
| <code>RemoveBotTag</code>
| <code>void RemoveBotTag(string)</code>
| <code>void RemoveBotTag(string ''tag'')</code>
| Removes a bot tag
| Removes a bot tag.
|-
|-
| <code>RemoveWeaponRestriction</code>
| <code>RemoveWeaponRestriction</code>
| <code>void RemoveWeaponRestriction(int)</code>
| <code>void RemoveWeaponRestriction([[Team_Fortress_2/Scripting/Script_Functions/Constants#TFBotWeaponRestrictionType|TFBotWeaponRestrictionType]] ''flags'')</code>
| Removes weapon restriction flags
| Removes weapon restriction flags.
|-
| <code>SetActionPoint</code>
| <code>void SetActionPoint(handle ''entity'')</code>
| Set the given action point for this bot.
|-
|-
| <code>SetAttentionFocus</code>
| <code>SetAttentionFocus</code>
| <code>void SetAttentionFocus(handle)</code>
| <code>void SetAttentionFocus(handle ''entity'')</code>
| Sets our current attention focus to this entity
| Sets our current attention focus to this entity.
|-
|-
| <code>SetAutoJump</code>
| <code>SetAutoJump</code>
| <code>void SetAutoJump(float ''minTime'', float ''maxTime'')</code>
| <code>void SetAutoJump(float ''min_time'', float ''max_time'')</code>
| Sets if the bot should automatically jump, and how often.
| Sets if the bot should automatically jump, and how often.
|-
| <code>SetBehaviorFlag</code>
| <code>void SetBehaviorFlag([[Team_Fortress_2/Scripting/Script_Functions/Constants#TFBOT_BEHAVIOR|TFBOT_BEHAVIOR]] ''flags'')</code>
| Set the given behavior flag(s) for this bot.
|-
|-
| <code>SetDifficulty</code>
| <code>SetDifficulty</code>
| <code>void SetDifficulty(int)</code>
| <code>void SetDifficulty([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotDifficultyType|ETFBotDifficultyType]] ''difficulty'')</code>
| Sets the bots difficulty level
| Sets the bots difficulty level.
|-
|-
| <code>SetHomeArea</code>
| <code>SetHomeArea</code>
| <code>void SetHomeArea(handle)</code>
| <code>void SetHomeArea(CTFNavArea ''area'')</code>
| Returns the home nav area of the bot -- may be nil.
| Set the home nav area of the bot, may be null.
|-
|-
| <code>SetMaxVisionRangeOverride</code>
| <code>SetMaxVisionRangeOverride</code>
| <code>void SetMaxVisionRangeOverride(float)</code>
| <code>void SetMaxVisionRangeOverride(float ''range'')</code>
| Sets max vision range override for the bot
| Sets max vision range override for the bot.
|-
| <code>SetMission</code>
| <code>void SetMission([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotMissionType|ETFBotMissionType]] ''mission'', bool ''reset_behavior'')</code>
| Set this bot's current mission to the given mission.
|-
| <code>SetMissionTarget</code>
| <code>void SetMissionTarget(handle ''entity'')</code>
| Set this bot's mission target to the given entity.
|-
| <code>SetPrevMission</code>
| <code>void SetPrevMission([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotMissionType|ETFBotMissionType]] ''mission'')</code>
| Set this bot's previous mission to the given mission.
|-
|-
| <code>SetScaleOverride</code>
| <code>SetScaleOverride</code>
| <code>void SetScaleOverride(float)</code>
| <code>void SetScaleOverride(float ''scale'')</code>
| Sets the scale override for the bot
| Sets the scale override for the bot.
|-
|-
| <code>SetShouldQuickBuild</code>
| <code>SetShouldQuickBuild</code>
| <code>void SetShouldQuickBuild(bool)</code>
| <code>void SetShouldQuickBuild(bool ''toggle'')</code>
| Sets if the bot should build instantly
| Sets if the bot should build instantly.
|-
|-
| <code>SetSquadFormationError</code>
| <code>SetSquadFormationError</code>
| <code>void SetSquadFormationError(float)</code>
| <code>void SetSquadFormationError(float ''coefficient'')</code>
| Sets our formation error coefficient.
| Sets our formation error coefficient.
|-
|-
| <code>ShouldAutoJump</code>
| <code>ShouldAutoJump</code>
| <code>bool ShouldAutoJump()</code>
| <code>bool ShouldAutoJump()</code>
| Returns if the bot should automatically jump
| Returns if the bot should automatically jump.
|-
|-
| <code>ShouldQuickBuild</code>
| <code>ShouldQuickBuild</code>
| <code>bool ShouldQuickBuild()</code>
| <code>bool ShouldQuickBuild()</code>
| Returns if the bot should build instantly
| Returns if the bot should build instantly.
|-
|-
| <code>UpdateDelayedThreatNotices</code>
| <code>UpdateDelayedThreatNotices</code>
| <code>void UpdateDelayedThreatNotices()</code>
| <code>void UpdateDelayedThreatNotices()</code>
|
|}
|}
=== CTFBaseBoss ===
Extends [[#NextBotCombatCharacter|NextBotCombatCharacter ↓]]
Base class intended for custom NPCs. Officially this is only used as part of [[tank_boss|MvM tank]].
==== Methods ====
{| class="standard-table" style="width:100%"
! Function
! Signature
! Description
|-
| <code>SetResolvePlayerCollisions</code>
| <code>void SetResolvePlayerCollisions(bool ''toggle'')</code>
| Sets whether the entity should push away players intersecting its bounding box. On by default.
|}
{{note|There's more methods in input form. See [[base_boss]] page.}}


=== Convars ===
=== Convars ===
Line 2,035: Line 2,759:
An interface to manipulate the [[ConVar|convars]] on the server.
An interface to manipulate the [[ConVar|convars]] on the server.


{{ModernNote|Protected convars (e.g. <code>rcon_password</code>) cannot be accessed.}}
{{note|Protected convars (e.g. <code>rcon_password</code>) cannot be accessed.}}
<!--
<!--
The class for this isn't directly available but is <code>CScriptConvarAccessor</code>. Not that it's important.
The class for this isn't directly available but is <code>CScriptConvarAccessor</code>. Not that it's important.
Line 2,048: Line 2,772:
|-
|-
| <code>GetBool</code>
| <code>GetBool</code>
| <code>bool GetClientConvarValue(string ''name'')</code>
| <code>bool GetBool(string ''name'')</code>
| Returns the convar as a bool. May return null if no such convar.
| Returns the convar as a bool. May return null if no such convar.
|-
|-
| <code>GetClientConvarValue</code>
| <code>GetClientConvarValue</code>
| <code>string GetClientConvarValue(string ''name'', int ''entindex'')</code>
| <code>string GetClientConvarValue(string ''name'', int ''entindex'')</code>
| Returns the convar value for the entindex as a string. Only works on client convars with the FCVAR_USERINFO flag.  
| Returns the convar value for the entindex as a string. Only works on client convars with the FCVAR_USERINFO flag.
{{tip|The list of available client convars can be printed in console using the <code>findflags USERINFO</code> command.}}
{{note|Notable client convars available:
* cl_autoreload : Whether the client wants autoreload after each shot
* cl_autorezoom : Whether the client wants auto scope-in after firing a sniper rifle
* cl_connectmethod : How the client joined the server. E.g. ''listenserver'', ''serverbrowser_internet'', ''serverbrowser_favorites'' {{todo|List all of them}}
* cl_flipviewmodels : Whether the client has flipped viewmodels
* cl_language : The client's language setting
* cl_spec_mode : Currently observer mode, corresponds to the [[Team_Fortress_2/Scripting/Script_Functions/Constants#ESpectatorMode|ESpectatorMode]].
* fov_desired : The client's FOV
* hud_classautokill : If the client wants to suicide after choosing a new class
* hud_combattext : Whether damage numbers are enabled
* name : The client's name
* closecaption : Whether the client has [[closed caption]]s enabled.
}}
|-
|-
| <code>GetInt</code>
| <code>GetInt</code>
| <code>int GetInt(string ''name'')</code>
| <code>int GetInt(string ''name'')</code>
| Returns the convar as an int. May return null if no such convar.
| Returns the convar as an int. May return null if no such convar.
{{warning|The entire convar list is searched each time this is called (which is slow!). If you are going to be using it several times per frame, cache off the result.}}
|-
|-
| <code>GetStr</code>
| <code>GetStr</code>
| <code>string GetStr(string ''name'')</code>
| <code>string GetStr(string ''name'')</code>
| Returns the convar as a string. May return null if no such convar.  
| Returns the convar as a string. May return null if no such convar. Returns <code>hunter2</code> if a protected convar is accessed.
{{warning|See above.}}
|-
|-
| <code>GetFloat</code>
| <code>GetFloat</code>
| <code>float GetFloat(string ''name'')</code>
| <code>float GetFloat(string ''name'')</code>
| Returns the convar as a float. May return null if no such convar.
| Returns the convar as a float. May return null if no such convar.
{{warning|See above.}}
|-
|-
| <code>IsConVarOnAllowList</code>
| <code>IsConVarOnAllowList</code>
Line 2,073: Line 2,814:
| <code>SetValue</code>
| <code>SetValue</code>
| <code>void SetValue(string ''name'', any ''value'')</code>
| <code>void SetValue(string ''name'', any ''value'')</code>
| Sets the value of the convar. The convar must be in cfg/vscript_convar_allowlist.txt to be set. Convars marked as cheat-only can be set even if ''sv_cheats'' is off. Convars marked as dev-only (i.e. not visible in console) can also be set. Supported types are bool, int, float, string.
| Sets the value of the convar. The convar must be in cfg/vscript_convar_allowlist.txt to be set. Convars marked as cheat-only can be set even if ''sv_cheats'' is off. Convars marked as dev-only (i.e. not visible in console) can also be set. Supported types are bool, int, float, string. The original value of the convar is saved and is reset on map change, in other words convar changes will not persist across maps.
{{warning|For changes intended to persist for the whole map, set these at the start of each round instead of only once. Otherwise, custom server configs may load after the initial script and not use the correct settings.}}
|}
|}


Line 2,087: Line 2,829:
|
|
<source lang=js>
<source lang=js>
local ent = null;
local ent = null
while ( ent = Entities.FindByClassname(ent, "tf_weapon_*") )
while ( ent = Entities.FindByClassname(ent, "tf_weapon_*") )
{
{
Line 2,102: Line 2,844:
|}
|}


{{ModernNote |
{{note |
* The variable name <code>ent</code> is arbitrary.
* The variable name <code>ent</code> is arbitrary.
* Indeed, we mean "{{=}}" and not "{{=}}{{=}}" in the loop conditions! The loops end if <code>ent</code> becomes <code>null</code>, which happens when no matching entities have an [[entity index]] higher to the one in ''previous'' parameter.
* Indeed, we mean "{{=}}" and not "{{=}}{{=}}" in the loop conditions! The loops end if <code>ent</code> becomes <code>null</code>, which happens when no matching entities have an [[entity index]] higher to the one in ''previous'' parameter.
Line 2,118: Line 2,860:
| <code>CreateByClassname</code>
| <code>CreateByClassname</code>
| <code>handle CreateByClassname(string ''classname'')</code>
| <code>handle CreateByClassname(string ''classname'')</code>
| Creates an entity by classname
| Creates an entity by classname.
{{tip|Example usage: <source lang=js>local prop = Entities.CreateByClassname("prop_dynamic")</source>}}
|-
|-
| <code>DispatchSpawn</code>
| <code>DispatchSpawn</code>
| <code>void DispatchSpawn(handle ''entity'')</code>
| <code>void DispatchSpawn(handle ''entity'')</code>
| Dispatches spawn of an entity!
| Dispatches spawn of an entity! Use this on entities created via <code>CreateByClassname</code> to actually spawn them into the world.
{{note|Calling this on players will cause them to respawn. In {{css}}, set the <code>m_iPlayerState</code> netprop to 0 before calling this to fully respawn.}}
|-
|-
| <code>FindByClassname</code>
| <code>FindByClassname</code>
| <code>handle FindByClassname(handle ''previous'', string ''classname'')</code>
| <code>handle FindByClassname(handle ''previous'', string ''classname'')</code>
| Find entities by the value of their <code>classname</code> keyvalue. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Find entities by the string of their <code>classname</code> keyvalue. Pass 'null' value to start an iteration, or reference to a previously found entity to continue a search.
{{ModernNote|The classname keyvalue of an entity can be manipulated and does not necessarily reflect its code class. There might be entities that have a different classname than the one they are created with.}}
{{note|The classname keyvalue of an entity can be manipulated and does not necessarily reflect its code class. There might be entities that have a different classname than the one they are created with. For example you can spawn a "prop_dynamic" then change its classname to "my_prop", and it will retain the functionality of its code class while also not showing up when searching for "prop_dynamic".}}
|-
|-
| <code>FindByClassnameNearest</code>
| <code>FindByClassnameNearest</code>
| <code>handle FindByClassnameNearest(string ''classname'', Vector ''center'', float ''radius'')</code>
| <code>handle FindByClassnameNearest(string ''classname'', Vector ''center'', float ''radius'')</code>
| Find entities by classname nearest to a point.
| Find entities by classname nearest to a point within a radius.
|-
|-
| <code>FindByClassnameWithin</code>
| <code>FindByClassnameWithin</code>
| <code>handle FindByClassnameWithin(handle ''previous'', string ''classname'', Vector ''center'', float ''radius'')</code>
| <code>handle FindByClassnameWithin(handle ''previous'', string ''classname'', Vector ''center'', float ''radius'')</code>
| Find entities by classname within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Find entities by classname within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
|-
|-
| <code>FindByModel</code>
| <code>FindByModel</code>
| <code>handle FindByModel(handle ''previous'', string ''modelname'')</code>
| <code>handle FindByModel(handle ''previous'', string ''model_name'')</code>
| Find entities by the value of their <code>model</code> keyvalue. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Find entities by the string of their <code>model</code> keyvalue. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
|-
|-
| <code>FindByName</code>
| <code>FindByName</code>
| <code>handle FindByName(handle ''previous'', string ''targetname'')</code>
| <code>handle FindByName(handle ''previous'', string ''targetname'')</code>
| Find entities by the value of their {{ent|targetname}} keyvalue. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Find entities by the string of their {{ent|targetname}} keyvalue. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
|-
|-
| <code>FindByNameNearest</code>
| <code>FindByNameNearest</code>
| <code>handle FindByNameNearest(string ''targetname'', Vector ''center'', float ''radius'')</code>
| <code>handle FindByNameNearest(string ''targetname'', Vector ''center'', float ''radius'')</code>
| Find entities by targetname nearest to a point.
| Find entities by targetname nearest to a point within a radius.
|-
|-
| <code>FindByNameWithin</code>
| <code>FindByNameWithin</code>
| <code>handle FindByNameWithin(handle ''previous'', string ''targetname'', Vector ''center'', float ''radius'')</code>
| <code>handle FindByNameWithin(handle ''previous'', string ''targetname'', Vector ''center'', float ''radius'')</code>
| Find entities by targetname within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Find entities by targetname within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
|-
|-
| <code>FindByTarget</code>
| <code>FindByTarget</code>
| <code>handle FindByTarget(handle ''previous'', string ''target'')</code>
| <code>handle FindByTarget(handle ''previous'', string ''target'')</code>
| Find entities by the value of their <code>target</code> keyvalue.{{confirm}} Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Find entities by the string of their <code>target</code> keyvalue.{{confirm}} Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
|-
|-
| <code>FindInSphere</code>
| <code>FindInSphere</code>
| <code>handle FindInSphere(handle ''previous'', Vector ''center'', float ''radius'')</code>
| <code>handle FindInSphere(handle ''previous'', Vector ''center'', float ''radius'')</code>
| Find entities within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Find entities within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
|-
|-
| <code>First</code>
| <code>First</code>
| <code>handle First()</code>
| <code>handle First()</code>
| Begin an iteration over the list of entities
| Begin an iteration over the list of entities. The first entity is always [[worldspawn]].
|-
|-
| <code>Next</code>
| <code>Next</code>
Line 2,182: Line 2,926:
|-
|-
| <code>AddIncomingConnection</code>
| <code>AddIncomingConnection</code>
| <code>void AddIncomingConnection(handle ''area'', int ''dir'')</code>
| <code>void AddIncomingConnection(CTFNavArea ''area'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'')</code>
| Add areas that connect TO this area by a ONE-WAY link
| Add areas that connect TO this area by a ONE-WAY link.
|-
|-
| <code>ClearAttributeTF</code>
| <code>ClearAttributeTF</code>
| <code>void ClearAttributeTF(int ''bits'')</code>
| <code>void ClearAttributeTF([[Team_Fortress_2/Scripting/Script_Functions/Constants#FTFNavAttributeType|FTFNavAttributeType]] ''bits'')</code>
| Clear TF-specific area attribute bits.
| Clear TF-specific area attribute bits.
|-
|-
| <code>ComputeClosestPointInPortal</code>
| <code>ComputeClosestPointInPortal</code>
| <code>Vector ComputeClosestPointInPortal(handle ''to'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'', Vector ''closePos'')</code>
| <code>Vector ComputeClosestPointInPortal(CTFNavArea ''to'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'', Vector ''close_pos'')</code>
| Compute closest point within the "portal" between to an area's direction from the given position.
| Compute closest point within the "portal" between to an area's direction from the given position.
|-
|-
Line 2,198: Line 2,942:
|-
|-
| <code>ConnectTo</code>
| <code>ConnectTo</code>
| <code>void ConnectTo(handle ''area'', int ''dir'')</code>
| <code>void ConnectTo(CTFNavArea ''area'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'')</code>
| Connect this area to given area in given direction.
| Connect this area to given area in given direction.
|-
|-
| <code>Contains</code>
| <code>Contains</code>
| <code>bool Contains(handle ''area'')</code>
| <code>bool Contains(CTFNavArea ''area'')</code>
| Return true if other area is on or above this area, but no others.
| Return true if other area is on or above this area, but no others.
|-
|-
Line 2,210: Line 2,954:
|-
|-
| <code>DebugDrawFilled</code>
| <code>DebugDrawFilled</code>
| <code>void DebugDrawFilled(int ''r'', int ''g'', int ''b'', int ''a'', float ''duration'', bool ''noDepthTest'', float ''margin'')</code>
| <code>void DebugDrawFilled(int ''r'', int ''g'', int ''b'', int ''a'', float ''duration'', bool ''no_depth_test'', float ''margin'')</code>
| Draw area as a filled rectangle of the given color.
| Draw area as a filled rectangle of the given color.
|-
|-
| <code>Disconnect</code>
| <code>Disconnect</code>
| <code>void Disconnect(handle ''area'')</code>
| <code>void Disconnect(CTFNavArea ''area'')</code>
| Disconnect this area from given area.
| Disconnect this area from given area.
|-
|-
Line 2,222: Line 2,966:
|-
|-
| <code>GetAdjacentArea</code>
| <code>GetAdjacentArea</code>
| <code>handle GetAdjacentArea(int ''dir'', int ''n'')</code>
| <code>handle GetAdjacentArea([[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'', int ''n'')</code>
| Return the n'th adjacent area in the given direction
| Return the n'th adjacent area in the given direction.
{{note|'Adjacent area' really means ''outgoing'' connection. Adjacent areas don't necessarily have to physically be touching, there can be a height discrepancy (e.g. at a drop ledge).}}
|-
|-
| <code>GetAdjacentAreas</code>
| <code>GetAdjacentAreas</code>
| <code>void GetAdjacentAreas(int ''dir'', handle ''table'')</code>
| <code>void GetAdjacentAreas([[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'', table ''result'')</code>
| Fills a passed in table with all adjacent areas in the given direction.
| Fills a passed in table with all adjacent areas in the given direction.
|-
|-
| <code>GetAdjacentCount</code>
| <code>GetAdjacentCount</code>
| <code>int GetAdjacentCount(ENavDirType ''dir'')</code>
| <code>int GetAdjacentCount([[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'')</code>
| Get the number of adjacent areas in the given direction.
| Get the number of adjacent areas in the given direction.
|-
|-
Line 2,236: Line 2,981:
| <code>int GetAttributes()</code>
| <code>int GetAttributes()</code>
| Get area attribute bits.
| Get area attribute bits.
See [[Team_Fortress_2/Scripting/Script_Functions/Constants#FNavAttributeType|FNavAttributeType]].
|-
|-
| <code>GetAvoidanceObstacleHeight</code>
| <code>GetAvoidanceObstacleHeight</code>
Line 2,246: Line 2,992:
|-
|-
| <code>GetCorner</code>
| <code>GetCorner</code>
| <code>Vector GetCorner(ENavDirType ''dir'')</code>
| <code>Vector GetCorner([[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'')</code>
| Get corner origin of area.
| Get corner origin of area.
|-
|-
Line 2,254: Line 3,000:
|-
|-
| <code>GetDoor</code>
| <code>GetDoor</code>
| <code>handle GetDoor()</code>
| <code>CBaseAnimating GetDoor()</code>
| Returns the door entity above the area.
| Returns the door entity above the area.
|-
|-
| <code>GetElevator</code>
| <code>GetElevator</code>
| <code>handle GetElevator()</code>
| <code>CBaseAnimating GetElevator()</code>
| Returns the elevator if in an elevator's path.
| Returns the elevator if in an elevator's path.
|-
|-
| <code>GetElevatorAreas</code>
| <code>GetElevatorAreas</code>
| <code>void GetElevatorAreas(handle ''table'')</code>
| <code>void GetElevatorAreas(table ''result'')</code>
| Fills table with a collection of areas reachable via elevator from this area.
| Fills table with a collection of areas reachable via elevator from this area.
|-
|-
Line 2,270: Line 3,016:
|-
|-
| <code>GetIncomingConnections</code>
| <code>GetIncomingConnections</code>
| <code>void GetIncomingConnections(ENavDirType ''dir'', handle ''table'')</code>
| <code>void GetIncomingConnections([[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'', table ''result'')</code>
| Fills a passed in table with areas connected TO this area by a ONE-WAY link (ie: we have no connection back to them).
| Fills a passed in table with areas connected TO this area by a ONE-WAY link (ie: we have no connection back to them).
|-
|-
| <code>GetParent</code>
| <code>GetParent</code>
| <code>handle GetParent()</code>
| <code>CTFNavArea GetParent()</code>
| Returns the area just prior to this one in the search path.
| Returns the area just prior to this one in the search path.
|-
|-
Line 2,286: Line 3,032:
|-
|-
| <code>GetPlayerCount</code>
| <code>GetPlayerCount</code>
| <code>int GetPlayerCount(int ''team'')</code>
| <code>int GetPlayerCount([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'')</code>
| Return number of players of given team currently within this area (team of zero means any/all).
| Return number of players of given team currently within this area (team of zero means any/all).
|-
|-
| <code>GetRandomAdjacentArea</code>
| <code>GetRandomAdjacentArea</code>
| <code>handle GetRandomAdjacentArea(int ''dir'')</code>
| <code>CTFNavArea GetRandomAdjacentArea([[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'')</code>
| Return a random adjacent area in the given direction.
| Return a random adjacent area in the given direction.
|-
|-
Line 2,307: Line 3,053:
| <code>GetZ</code>
| <code>GetZ</code>
| <code>float GetZ(Vector ''pos'')</code>
| <code>float GetZ(Vector ''pos'')</code>
| Return Z of area at (x,y) of 'pos'
| Return Z of area at (x,y) of 'pos'.
|-
|-
| <code>HasAttributeTF</code>
| <code>HasAttributeTF</code>
| <code>bool HasAttributeTF(int ''bits'')</code>
| <code>bool HasAttributeTF([[Team_Fortress_2/Scripting/Script_Functions/Constants#FTFNavAttributeType|FTFNavAttributeType]] ''bits'')</code>
| Has TF-specific area attribute bits of the given ones.
| Has TF-specific area attribute bits of the given ones. The name is slightly misleading, think of this one as "HasAttribute'''s'''TF".
|-
|-
| <code>HasAttributes</code>
| <code>HasAttributes</code>
| <code>bool HasAttributes(int ''bits'')</code>
| <code>bool HasAttributes([[Team_Fortress_2/Scripting/Script_Functions/Constants#FNavAttributeType|FNavAttributeType]] ''bits'')</code>
| Has area attribute bits of the given ones?.
| Has area attribute bits of the given ones?.
|-
|-
| <code>HasAvoidanceObstacle</code>
| <code>HasAvoidanceObstacle</code>
| <code>bool HasAvoidanceObstacle(float ''maxheight'')</code>
| <code>bool HasAvoidanceObstacle(float ''max_height'')</code>
| Returns true if there's a large, immobile object obstructing this area
| Returns true if there's a large, immobile object obstructing this area.
|-
|-
| <code>IsBlocked</code>
| <code>IsBlocked</code>
| <code>bool IsBlocked(int ''team'', bool ''affectsFlow'')</code>
| <code>bool IsBlocked([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'', bool ''affects_flow'')</code>
| Return true if team is blocked in this area.
| Return true if team is blocked in this area.
|-
|-
| <code>IsBottleneck</code>
| <code>IsBottleneck</code>
| <code>bool IsBottleneck()</code>
| <code>bool IsBottleneck()</code>
| Returns true if area is a bottleneck. (tiny narrow areas with only one path)
| Returns true if area is a bottleneck. (tiny narrow areas with only one path).
|-
|-
| <code>IsCompletelyVisibleToTeam</code>
| <code>IsCompletelyVisibleToTeam</code>
| <code>bool IsCompletelyVisibleToTeam(int ''team'')</code>
| <code>bool IsCompletelyVisibleToTeam([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'')</code>
| Return true if given area is completely visible from somewhere in this area by someone on the team.
| Return true if given area is completely visible from somewhere in this area by someone on the team.
|-
|-
| <code>IsConnected</code>
| <code>IsConnected</code>
| <code>bool IsConnected(handle ''area'', ENavDirType ''dir'')</code>
| <code>bool IsConnected(handle ''area'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'')</code>
| Return true if this area is connected to other area in given direction. (If you set direction to -1 or 4, it will automatically check all directions for a connection).
| Return true if this area is connected to other area in given direction. (If you set direction to -1 or 4, it will automatically check all directions for a connection).
|-
|-
| <code>IsCoplanar</code>
| <code>IsCoplanar</code>
| <code>bool IsCoplanar(handle ''area'')</code>
| <code>bool IsCoplanar(handle ''area'')</code>
| Return true if this area and given. area are approximately co-planar
| Return true if this area and given. area are approximately co-planar.
|-
|-
| <code>IsDamaging</code>
| <code>IsDamaging</code>
Line 2,350: Line 3,096:
|-
|-
| <code>IsEdge</code>
| <code>IsEdge</code>
| <code>bool IsEdge(ENavDirType ''dir'')</code>
| <code>bool IsEdge([[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'')</code>
| Return true if there are no bi-directional links on the given side.
| Return true if there are no bi-directional links on the given side.
|-
|-
Line 2,366: Line 3,112:
|-
|-
| <code>IsPotentiallyVisibleToTeam</code>
| <code>IsPotentiallyVisibleToTeam</code>
| <code>bool IsPotentiallyVisibleToTeam(int ''team'')</code>
| <code>bool IsPotentiallyVisibleToTeam([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'')</code>
| Return true if any portion of this area is visible to anyone on the given team.
| Return true if any portion of this area is visible to anyone on the given team.
|-
|-
| <code>IsReachableByTeam</code>
| <code>IsReachableByTeam</code>
| <code>bool IsReachableByTeam(int ''team'')</code>
| <code>bool IsReachableByTeam([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'')</code>
| Is this area reachable by the given team?
| Is this area reachable by the given team?
|-
|-
Line 2,394: Line 3,140:
|-
|-
| <code>MarkAsBlocked</code>
| <code>MarkAsBlocked</code>
| <code>void MarkAsBlocked(int ''team'')</code>
| <code>void MarkAsBlocked([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'')</code>
| Mark this area as blocked for team.
| Mark this area as blocked for team.
|-
|-
Line 2,406: Line 3,152:
|-
|-
| <code>RemoveAttributes</code>
| <code>RemoveAttributes</code>
| <code>void RemoveAttributes(int ''bits'')</code>
| <code>void RemoveAttributes([[Team_Fortress_2/Scripting/Script_Functions/Constants#FNavAttributeType|FNavAttributeType]] ''bits'')</code>
| Removes area attribute bits.
| Removes area attribute bits.
|-
|-
| <code>RemoveOrthogonalConnections</code>
| <code>RemoveOrthogonalConnections</code>
| <code>void RemoveOrthogonalConnections(ENavDirType ''dir'')</code>
| <code>void RemoveOrthogonalConnections([[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'')</code>
| Removes all connections in directions to left and right of specified direction.
| Removes all connections in directions to left and right of specified direction.
|-
|-
| <code>SetAttributeTF</code>
| <code>SetAttributeTF</code>
| <code>void SetAttributeTF(int ''bits'')</code>
| <code>void SetAttributeTF([[Team_Fortress_2/Scripting/Script_Functions/Constants#FTFNavAttributeType|FTFNavAttributeType]] ''bits'')</code>
| Set TF-specific area attributes.
| Set TF-specific area attributes.
|-
|-
| <code>SetAttributes</code>
| <code>SetAttributes</code>
| <code>void SetAttributes(int ''bits'')</code>
| <code>void SetAttributes([[Team_Fortress_2/Scripting/Script_Functions/Constants#FNavAttributeType|FNavAttributeType]] ''bits'')</code>
| Set area attribute bits.
| Set area attribute bits.
|-
|-
Line 2,447: Line 3,193:
|-
|-
| <code>FindNavAreaAlongRay</code>
| <code>FindNavAreaAlongRay</code>
| <code>handle FindNavAreaAlongRay(Vector ''startpos'', Vector ''endpos'', handle ''ignoreAreaID'')</code>
| <code>CTFNavArea FindNavAreaAlongRay(Vector ''start_pos'', Vector ''end_pos'', handle ''ignore_area'')</code>
| get nav area from ray
| Get nav area from ray.
|-
|-
| <code>GetAllAreas</code>
| <code>GetAllAreas</code>
| <code>void GetAllAreas(handle ''table'')</code>
| <code>void GetAllAreas(table ''result'')</code>
| fills a passed in table of all nav areas
| Fills a passed in table of all nav areas.
|-
|-
| <code>GetAreasWithAttributes</code>
| <code>GetAreasWithAttributes</code>
| <code>void GetAreasWithAttributes(int ''bits'', handle ''table'')</code>
| <code>void GetAreasWithAttributes([[Team_Fortress_2/Scripting/Script_Functions/Constants#FNavAttributeType|FNavAttributeType]] ''bits'', table ''result'')</code>
| fills a passed in table of all nav areas that have the specified attributes
| Fills a passed in table of all nav areas that have the specified attributes.
|-
|-
| <code>GetNavArea</code>
| <code>GetNavArea</code>
| <code>handle GetNavArea(Vector ''origin'', float ''flBeneath'')</code>
| <code>CTFNavArea GetNavArea(Vector ''origin'', float ''beneath'')</code>
| given a position in the world, return the nav area that is closest to or below that height.
| Given a position in the world, return the nav area that is closest to or below that height.
|-
|-
| <code>GetNavAreaByID</code>
| <code>GetNavAreaByID</code>
| <code>handle GetNavAreaByID(int ''areaID'')</code>
| <code>CTFNavArea GetNavAreaByID(int ''area_id'')</code>
| get nav area by ID
| Get nav area by ID.
|-
|-
| <code>GetNavAreaCount</code>
| <code>GetNavAreaCount</code>
| <code>int GetNavAreaCount()</code>
| <code>int GetNavAreaCount()</code>
| return total number of nav areas
| Return total number of nav areas.
|-
|-
| <code>GetNavAreasFromBuildPath</code>
| <code>GetNavAreasFromBuildPath</code>
| <code>bool GetNavAreasFromBuildPath(handle ''startArea'', handle ''endArea'', Vector ''goalPos'', float ''flMaxPathLength'', int ''teamID'', bool ''ignoreNavBlockers'', handle ''table'')</code>
| <code>bool GetNavAreasFromBuildPath(CTFNavArea ''start_area'', CTFNavArea ''end_area'', Vector ''goal_pos'', float ''max_path_length'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'', bool ''ignore_nav_blockers'', table ''result'')</code>
| Fills the table with areas from a path. Returns whether a path was found. If 'endArea' is NULL, will compute a path as close as possible to 'goalPos'.
| Fills the table with areas from a path. Returns whether a path was found. If 'end_area' is NULL, will compute a path as close as possible to 'goal_pos'.
{{note|The areas are passed from end area to the start area.}}
|-
|-
| <code>GetNavAreasInRadius</code>
| <code>GetNavAreasInRadius</code>
| <code>void GetNavAreasInRadius(Vector ''origin'', float ''radius'', handle ''table'')</code>
| <code>void GetNavAreasInRadius(Vector ''origin'', float ''radius'', table ''result'')</code>
| fills a passed in table of nav areas within radius
| Fills a passed in table of nav areas within radius.
|-
|-
| <code>GetNavAreasOverlappingEntityExtent</code>
| <code>GetNavAreasOverlappingEntityExtent</code>
| <code>void GetNavAreasOverlappingEntityExtent(handle ''entity'', handle ''table'')</code>
| <code>void GetNavAreasOverlappingEntityExtent(handle ''entity'', table ''result'')</code>
| fills passed in table with areas overlapping entity's extent
| Fills passed in table with areas overlapping entity's extent.
|-
|-
| <code>GetNearestNavArea</code>
| <code>GetNearestNavArea</code>
| <code>handle GetNearestNavArea(Vector ''origin'', float ''maxDist'', bool ''checkLOS'', bool ''checkGround'')</code>
| <code>CTFNavArea GetNearestNavArea(Vector ''origin'', float ''max_distance'', bool ''check_los'', bool ''check_ground'')</code>
| given a position in the world, return the nav area that is closest to or below that height.
| Given a position in the world, return the nav area that is closest to or below that height.
|-
|-
| <code>GetObstructingEntities</code>
| <code>GetObstructingEntities</code>
| <code>void GetObstructingEntities(handle ''table'')</code>
| <code>void GetObstructingEntities(table ''result'')</code>
| fills a passed in table of all obstructing entities
| Fills a passed in table of all obstructing entities.
|-
|-
| <code>NavAreaBuildPath</code>
| <code>NavAreaBuildPath</code>
| <code>bool NavAreaBuildPath(handle ''startArea'', handle ''endArea'', Vector ''goalPos'', float ''flMaxPathLength'', int ''teamID'', bool ''ignoreNavBlockers'')</code>
| <code>bool NavAreaBuildPath(CTFNavArea ''start_area'', CTFNavArea ''end_erea'', Vector ''goal_pos'', float ''max_path_length'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'', bool ''ignore_nav_blockers'')</code>
| returns true if a path exists
| Returns true if a path exists.
|-
|-
| <code>NavAreaTravelDistance</code>
| <code>NavAreaTravelDistance</code>
| <code>float NavAreaTravelDistance(handle ''startArea'', handle ''endArea'', float ''flMaxPathLength'')</code>
| <code>float NavAreaTravelDistance(CTFNavArea ''start_area'', CTFNavArea ''end_area'', float ''max_path_length'')</code>
| compute distance between two areas. Return -1 if can't reach 'endArea' from 'startArea'
| Compute distance between two areas. Return -1.0 if can't reach 'end_area' from 'start_area'.
|-
|-
| <code>RegisterAvoidanceObstacle</code>
| <code>RegisterAvoidanceObstacle</code>
| <code>void RegisterAvoidanceObstacle(handle ''entity'')</code>
| <code>void RegisterAvoidanceObstacle(handle ''entity'')</code>
| registers avoidance obstacle
| Registers avoidance obstacle.
|-
|-
| <code>UnregisterAvoidanceObstacle</code>
| <code>UnregisterAvoidanceObstacle</code>
| <code>void UnregisterAvoidanceObstacle(handle ''entity'')</code>
| <code>void UnregisterAvoidanceObstacle(handle ''entity'')</code>
| unregisters avoidance obstacle
| Unregisters avoidance obstacle.
|}
|}


Line 2,510: Line 3,257:
Game Instance: <code>NetProps</code>
Game Instance: <code>NetProps</code>


Allows reading and updating the [[Networking_Entities#Network_Variables|network properties]] and datamaps of an entity.  
Allows reading and updating the [[Networking_Entities#Network_Variables|network properties]] and data-maps of an entity. A brief explanation: all entities in the game have 2 types of internal properties: networked and saved (called "data" by the game). Networked properties are transmitted to the client, while data properties are a leftover from singleplayer games, which are properties that get saved to a save file (that can be re-loaded later). Some properties may exist in both lists, or one list but not the other and vice versa, so it's best to check both lists. Entities follow an inheritance tree, and they inherit the properties of their parent(s). For organization/optimization purposes, properties also tend to be nested inside "tables".
 
Netprops nested in a table can be accessed using dot notation similar to a [[Squirrel]] table. Example: to access the netprop <code>m_bJumping</code> on a player, you would specify <code>m_Shared.m_bJumping</code>.
 
{{note|Sometimes the table structure is figured out automatically and doesn't need to be specified explicitly. The easiest way to check is to use <code>HasProp</code> to see if its correct. For example, <code>LocalWeaponData</code> and <code>LocalActiveWeaponData</code> don't need to be specified. But on the contrary, <code>m_Collision</code>, <code>m_Shared</code> and <code>m_AttributeManager</code> (+ <code>m_Item</code>) must be explicitly specified.}}


If the entity has multiple netprops with the same name, the data table name can be prepended with a dot to specify which one to use (e.g. "m_itTimer.m_timestamp").
{{tip|Resources for finding netprops and datamaps of entities:
{{tip|Resources for finding netprops and datamaps of entities:
* Interactive viewer of netprops: https://jackz.me/netprops/tf2
* Interactive viewer of netprops: https://jackz.me/netprops/tf2
* Formatted list of netprops and datamaps: https://sigwiki.potato.tf/index.php/Entity_Properties
* Formatted list of netprops and datamaps: https://sigwiki.potato.tf/index.php/Entity_Properties
* Raw list of netprops and datamaps: https://www.invalidvertex.com/tf2dump.php
* Raw list of netprops and datamaps: https://www.invalidvertex.com/tf2dump.php
* Better raw list of datamaps that includes type information: https://cdn.discordapp.com/attachments/1039243316920844428/1095872595049599056/dump_datamaps.txt
}}
}}


{{ModernWarning|Each netprop has a set size in bits, exceeding the size may desync the clients from the server causing unpredictable behavior.}}
{{warning|Each netprop has a set size in bits, exceeding the size may desync the clients from the server causing unpredictable behavior.}}
{{note|Netprops containing the substring <code>EntityQuality</code> or <code>AccountID</code> are banned and cannot be set nor fetched, to prevent spoofing economy items as legitimate.}}
{{note|Netprops containing the substring <code>EntityQuality</code> or <code>AccountID</code> are banned and cannot be set nor fetched, to prevent spoofing economy items as legitimate.}}
{{tip|Run the code below to fold netprop functions for easier and more efficient usage. E.g. <code>NetProps.GetPropInt</code> would simply become <code>GetPropInt</code>.
<source lang=js>
foreach (name, method in ::NetProps.getclass())
if (name != "IsValid")
getroottable()[name] <- method.bindenv(::NetProps)
</source>
}}


==== Methods ====
==== Methods ====
Line 2,532: Line 3,287:
|-
|-
| <code>GetPropArraySize</code>
| <code>GetPropArraySize</code>
| <code>int GetPropArraySize(handle ''entity'', string ''propertyName'')</code>
| <code>int GetPropArraySize(handle ''entity'', string ''property_name'')</code>
| Returns the size of an netprop array, or -1.
| Returns the size of an netprop array, or -1.
|-
|-
| <code>GetPropEntity</code>
| <code>GetPropEntity</code>
| <code>handle GetPropEntity(handle ''entity'', string ''propertyName'')</code>
| <code>handle GetPropEntity(handle ''entity'', string ''property_name'')</code>
| Reads an EHANDLE-valued netprop (21 bit integer). Returns the script handle of the entity.
| Reads an EHANDLE-valued netprop (21 bit integer). Returns the script handle of the entity.
|-
|-
| <code>GetPropEntityArray</code>
| <code>GetPropEntityArray</code>
| <code>handle GetPropEntityArray(handle ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| <code>handle GetPropEntityArray(handle ''entity'', string ''property_name'', int ''array_element'')</code>
| Reads an EHANDLE-valued netprop (21 bit integer) from an array. Returns the script handle of the entity.
| Reads an EHANDLE-valued netprop (21 bit integer) from an array. Returns the script handle of the entity.
|-
|-
| <code>GetPropBool</code>
| <code>GetPropBool</code>
| <code>bool GetPropBool(handle ''entity'', string ''propertyName'')</code>
| <code>bool GetPropBool(handle ''entity'', string ''property_name'')</code>
| Reads a boolean-valued netprop.
| Reads a boolean-valued netprop.
|-
|-
| <code>GetPropBoolArray</code>
| <code>GetPropBoolArray</code>
| <code>bool GetPropBoolArray(handle ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| <code>bool GetPropBoolArray(handle ''entity'', string ''property_name'', int ''array_element'')</code>
| Reads a boolean-valued netprop from an array.
| Reads a boolean-valued netprop from an array.
|-
|-
| <code>GetPropFloat</code>
| <code>GetPropFloat</code>
| <code>float GetPropFloat(handle ''entity'', string ''propertyName'')</code>
| <code>float GetPropFloat(handle ''entity'', string ''property_name'')</code>
| Reads a float-valued netprop.
| Reads a float-valued netprop.
|-
|-
| <code>GetPropFloatArray</code>
| <code>GetPropFloatArray</code>
| <code>float GetPropFloatArray(handle ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| <code>float GetPropFloatArray(handle ''entity'', string ''property_name'', int ''array_element'')</code>
| Reads a float-valued netprop from an array.
| Reads a float-valued netprop from an array.
|-
|-
| <code>GetPropInfo</code>
| <code>GetPropInfo</code>
| <code>bool GetPropInfo(handle ''entity'', string ''propertyName'', int ''arrayElement'', handle ''table'')</code>
| <code>bool GetPropInfo(handle ''entity'', string ''property_name'', int ''array_element'', table ''result'')</code>
| Fills in a passed table with property info for the provided entity.
| Fills in a passed table with property info for the provided entity.
|-
|-
| <code>GetPropInt</code>
| <code>GetPropInt</code>
| <code>int GetPropInt(handle ''entity'', string ''propertyName'')</code>
| <code>int GetPropInt(handle ''entity'', string ''property_name'')</code>
| Reads an integer-valued netprop.
| Reads an integer-valued netprop.
|-
|-
| <code>GetPropIntArray</code>
| <code>GetPropIntArray</code>
| <code>int GetPropIntArray(handle ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| <code>int GetPropIntArray(handle ''entity'', string ''property_name'', int ''array_element'')</code>
| Reads an integer-valued netprop from an array.
| Reads an integer-valued netprop from an array.
|-
|-
| <code>GetPropString</code>
| <code>GetPropString</code>
| <code>string GetPropString(handle ''entity'', string ''propertyName'')</code>
| <code>string GetPropString(handle ''entity'', string ''property_name'')</code>
| Reads an string-valued netprop.
| Reads an string-valued netprop.
|-
|-
| <code>GetPropStringArray</code>
| <code>GetPropStringArray</code>
| <code>string GetPropStringArray(handle ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| <code>string GetPropStringArray(handle ''entity'', string ''property_name'', int ''array_element'')</code>
| Reads an string-valued netprop from an array.
| Reads an string-valued netprop from an array.
|-
|-
| <code>GetPropType</code>
| <code>GetPropType</code>
| <code>string GetPropType(handle ''entity'', string ''propertyName'')</code>
| <code>string GetPropType(handle ''entity'', string ''property_name'')</code>
| Returns the name of the netprop type as a string.
| Returns the name of the netprop type as a string.
|-
|-
| <code>GetPropVector</code>
| <code>GetPropVector</code>
| <code>Vector GetPropVector(handle ''entity'', string ''propertyName'')</code>
| <code>Vector GetPropVector(handle ''entity'', string ''property_name'')</code>
| Reads a 3D vector-valued netprop.
| Reads a 3D vector-valued netprop.
|-
|-
| <code>GetPropVectorArray</code>
| <code>GetPropVectorArray</code>
| <code>Vector GetPropVectorArray(handle ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| <code>Vector GetPropVectorArray(handle ''entity'', string ''property_name'', int ''array_element'')</code>
| Reads a 3D vector-valued netprop from an array.  
| Reads a 3D vector-valued netprop from an array.
|-
|-
| <code>GetTable</code>
| <code>GetTable</code>
| <code>void GetTable(handle ''entity'', int ''iPropType'', handle ''table'')</code>
| <code>void GetTable(handle ''entity'', int ''prop_type'', table ''result'')</code>
| Fills in a passed table with all props of a specified type for the provided entity (set iPropType to 0 for SendTable or 1 for DataMap)
| Fills in a passed table with all props of a specified type for the provided entity (set prop_type to 0 for SendTable or 1 for DataMap).
|-
|-
| <code>HasProp</code>
| <code>HasProp</code>
| <code>bool HasProp(handle ''entity'', string ''propertyName'')</code>
| <code>bool HasProp(handle ''entity'', string ''property_name'')</code>
| Checks if a netprop exists.
| Checks if a netprop exists.
|-
|-
| <code>SetPropBool</code>
| <code>SetPropBool</code>
| <code>void SetPropBool(handle ''entity'', string ''propertyName'', bool ''value'')</code>
| <code>void SetPropBool(handle ''entity'', string ''property_name'', bool ''value'')</code>
| Sets a netprop to the specified boolean.
| Sets a netprop to the specified boolean.
|-
|-
| <code>SetPropBoolArray</code>
| <code>SetPropBoolArray</code>
| <code>void SetPropBoolArray(handle ''entity'', string ''propertyName'', bool ''value'', int ''arrayElement'')</code>
| <code>void SetPropBoolArray(handle ''entity'', string ''property_name'', bool ''value'', int ''array_element'')</code>
| Sets a netprop from an array to the specified boolean.
| Sets a netprop from an array to the specified boolean.
|-
|-
| <code>SetPropEntity</code>
| <code>SetPropEntity</code>
| <code>void SetPropEntity(handle ''entity'', string ''propertyName'', handle ''value'')</code>
| <code>void SetPropEntity(handle ''entity'', string ''property_name'', handle ''value'')</code>
| Sets an EHANDLE-valued netprop (21 bit integer) to reference the specified entity.
| Sets an EHANDLE-valued netprop (21 bit integer) to reference the specified entity.
|-
|-
| <code>SetPropEntityArray</code>
| <code>SetPropEntityArray</code>
| <code>void SetPropEntityArray(handle ''entity'', string ''propertyName'', handle ''value'', int ''arrayElement'')</code>
| <code>void SetPropEntityArray(handle ''entity'', string ''property_name'', handle ''value'', int ''array_element'')</code>
| Sets an EHANDLE-valued netprop (21 bit integer) from an array to reference the specified entity.
| Sets an EHANDLE-valued netprop (21 bit integer) from an array to reference the specified entity.
|-
|-
| <code>SetPropFloat</code>
| <code>SetPropFloat</code>
| <code>void SetPropFloat(handle ''entity'', string ''propertyName'', float ''value'')</code>
| <code>void SetPropFloat(handle ''entity'', string ''property_name'', float ''value'')</code>
| Sets a netprop to the specified float.
| Sets a netprop to the specified float.
|-
|-
| <code>SetPropFloatArray</code>
| <code>SetPropFloatArray</code>
| <code>void SetPropFloatArray(handle ''entity'', string ''propertyName'', float ''value'', int ''arrayElement'')</code>
| <code>void SetPropFloatArray(handle ''entity'', string ''property_name'', float ''value'', int ''array_element'')</code>
| Sets a netprop from an array to the specified float.
| Sets a netprop from an array to the specified float.
|-
|-
| <code>SetPropInt</code>
| <code>SetPropInt</code>
| <code>void SetPropInt(handle ''entity'', string ''propertyName'', int ''value'')</code>
| <code>void SetPropInt(handle ''entity'', string ''property_name'', int ''value'')</code>
| Sets a netprop to the specified integer.
| Sets a netprop to the specified integer.
{{warning|Do not override <code>m_iTeamNum</code> netprops on players or Engineer buildings permanently. Use <code>ForceChangeTeam</code> or <code>SetTeam</code> or respectively. Not doing so will result in unpredictable server crashes later on. Overriding m_iTeamNum temporarily and then reverting it in the same frame is safe however.}}
|-
|-
| <code>SetPropIntArray</code>
| <code>SetPropIntArray</code>
| <code>void SetPropIntArray(handle ''entity'', string ''propertyName'', int ''value'', int ''arrayElement'')</code>
| <code>void SetPropIntArray(handle ''entity'', string ''property_name'', int ''value'', int ''array_element'')</code>
| Sets a netprop from an array to the specified integer.
| Sets a netprop from an array to the specified integer.
|-
|-
| <code>SetPropString</code>
| <code>SetPropString</code>
| <code>void SetPropString(handle ''entity'', string ''propertyName'', string ''value'')</code>
| <code>void SetPropString(handle ''entity'', string ''property_name'', string ''value'')</code>
| Sets a netprop to the specified string.
| Sets a netprop to the specified string.
|-
|-
| <code>SetPropStringArray</code>
| <code>SetPropStringArray</code>
| <code>void SetPropStringArray(handle ''entity'', string ''propertyName'', string ''value'', int ''arrayElement'')</code>
| <code>void SetPropStringArray(handle ''entity'', string ''property_name'', string ''value'', int ''array_element'')</code>
| Sets a netprop from an array to the specified string.
| Sets a netprop from an array to the specified string.
|-
|-
| <code>SetPropVector</code>
| <code>SetPropVector</code>
| <code>void SetPropVector(handle ''entity'', string ''propertyName'', Vector ''value'')</code>
| <code>void SetPropVector(handle ''entity'', string ''property_name'', Vector ''value'')</code>
| Sets a netprop to the specified vector.
| Sets a netprop to the specified vector.
|-
|-
| <code>SetPropVectorArray</code>
| <code>SetPropVectorArray</code>
| <code>void SetPropVectorArray(handle ''entity'', string ''propertyName'', Vector ''value'', int ''arrayElement'')</code>
| <code>void SetPropVectorArray(handle ''entity'', string ''property_name'', Vector ''value'', int ''array_element'')</code>
| Sets a netprop from an array to the specified vector.
| Sets a netprop from an array to the specified vector.
|}
|}
Line 2,661: Line 3,417:
|-
|-
| <code>AddOutput</code>
| <code>AddOutput</code>
| <code>void AddOutput(handle ''entity'', string ''outputName'', string ''targetName'', string ''inputName'', string ''parameter'', float ''delay'', int ''timesToFire'')</code>
| <code>void AddOutput(handle ''entity'', string ''output_name'', string ''targetname'', string ''input_name'', string ''parameter'', float ''delay'', int ''times_to_fire'')</code>
| Adds a new output to the entity.
| Adds a new output to the entity.
|-
|-
| <code>GetNumElements</code>
| <code>GetNumElements</code>
| <code>int GetNumElements(handle ntity ''entity'', string ''outputName'')</code>
| <code>int GetNumElements(handle ''entity'', string ''output_name'')</code>
| Returns the number of array elements.
| Returns the number of array elements.
|-
|-
| <code>GetOutputTable</code>
| <code>GetOutputTable</code>
| <code>void GetOutputTable(handle ''entity'', string ''outputName'', table, int ''arrayElement'')</code>
| <code>void GetOutputTable(handle ''entity'', string ''output_name'', table, int ''array_element'')</code>
| Fills the passed table with output information.
| Fills the passed table with output information.
|-
|-
| <code>HasAction</code>
| <code>HasAction</code>
| <code>bool HasAction(handle ''entity'', string ''outputName'')</code>
| <code>bool HasAction(handle ''entity'', string ''output_name'')</code>
| Returns true if an action exists for the output.
| Returns true if an action exists for the output.
|-
|-
| <code>HasOutput</code>
| <code>HasOutput</code>
| <code>bool HasOutput(handle ''entity'', string ''outputName'')</code>
| <code>bool HasOutput(handle ''entity'', string ''output_name'')</code>
| Returns true if the output exists.
| Returns true if the output exists.
|-
|-
| <code>RemoveOutput</code>
| <code>RemoveOutput</code>
| <code>void RemoveOutput(handle ''entity'', string ''outputName'', string ''targetName'', string ''inputName'', string ''parameter'')</code>
| <code>void RemoveOutput(handle ''entity'', string ''output_name'', string ''targetname'', string ''input_name'', string ''parameter'')</code>
| Removes an output from the entity.
| Removes an output from the entity.
{{note|The order of the internal output data may change after this is performed, which can be problematic if iterating outputs. As a workaround, all the outputs can be stored in an array of tables first and then removed while iterating the array.}}
|}
|}


=== CScriptKeyValues ===
=== CScriptKeyValues ===
Line 2,696: Line 3,452:
! Signature
! Signature
! Description
! Description
|-
| <code>constructor</code>
|-
|-
| <code>FindKey</code>
| <code>FindKey</code>
Line 2,753: Line 3,507:
|-
|-
| <code>GetPlayerSpeechDuration</code>
| <code>GetPlayerSpeechDuration</code>
| <code>float GetPlayerSpeechDuration(int ''playerIndex'')</code>
| <code>float GetPlayerSpeechDuration(int ''player_index'')</code>
| Returns the number of seconds the player has been continuously speaking.
| Returns the number of seconds the player has been continuously speaking.
|-
|-
| <code>IsPlayerSpeaking</code>
| <code>IsPlayerSpeaking</code>
| <code>bool IsPlayerSpeaking(int ''playerIndex'')</code>
| <code>bool IsPlayerSpeaking(int ''player_index'')</code>
| Returns whether the player specified is speaking.
| Returns whether the player specified is speaking.
|}
|}


=== CEnvEntityMaker ===
=== CEnvEntityMaker ===
Extends [[#CBaseEntity|CBaseEntity]]
Extends [[#CBaseEntity|CBaseEntity ]]


Script handle class for [[env_entity_maker]]]
Script handle class for [[env_entity_maker]].


==== Methods ====
==== Methods ====
Line 2,774: Line 3,528:
| <code>SpawnEntity</code>
| <code>SpawnEntity</code>
| <code>void SpawnEntity()</code>
| <code>void SpawnEntity()</code>
| Create an entity at the location of the maker
| Create an entity at the location of the maker.
|-
|-
| <code>SpawnEntityAtEntityOrigin</code>
| <code>SpawnEntityAtEntityOrigin</code>
Line 2,791: Line 3,545:


=== CPointTemplate ===
=== CPointTemplate ===
Extends [[#CBaseEntity|CBaseEntity]]
Extends [[#CBaseEntity|CBaseEntity ]]


Script handle class for {{ent|point_template}}.
Script handle class for {{ent|point_template}}.


==== Hooks ====
==== Hooks ====
;<code>table PreSpawnInstance(string ''entityClass'', string ''entityName'')</code>
;<code>table PreSpawnInstance(string ''entity_class'', string ''entity_name'')</code>
:If this is defined, it will be called right before the entity is created, and any keyvalues returned will be assigned to the entity.
:If this is defined, it will be called right before the entity is created, and any keyvalues returned will be assigned to the entity.
{{ExpandBox|<source lang=cpp>
{{ExpandBox|<source lang=js>
function PreSpawnInstance( entityClass, entityName )
function PreSpawnInstance(entity_class, entity_name)
{
{
local keyvalues =
local keyvalues =
{  
{
  rendercolor = "0 255 0",
rendercolor = "0 255 0",
  targetname = "mySpawnedEntity"
targetname = "my_spawned_entity"
}
}


Line 2,813: Line 3,567:
;<code>void PostSpawn(table ''entities'')</code>
;<code>void PostSpawn(table ''entities'')</code>
:Called after the entities are spawned. A table with the handles of the spawned entities indexed by name is passed to the function. Could use this to connect outputs or do whatever needs to be done after the entity was created.
:Called after the entities are spawned. A table with the handles of the spawned entities indexed by name is passed to the function. Could use this to connect outputs or do whatever needs to be done after the entity was created.
{{ModernNote|PostSpawn() will not be called unless the PreSpawnInstance() function is also defined in the script.}}
{{note|PostSpawn() will not be called unless the PreSpawnInstance() function is also defined in the script.}}
{{ExpandBox|<source lang=cpp>
{{ExpandBox|<source lang=js>
function PostSpawn( entities )
function PostSpawn( entities )
{
{
foreach( targetname, handle in entities )
foreach(targetname, handle in entities)
{
{
printl( targetname + ": " + handle )
printl(targetname + ": " + handle)
}
}
}
}
Line 2,826: Line 3,580:
===== Example =====
===== Example =====
Spawned entities can be accessed synchronously in script by using an entity maker. The following generalised example creates a global <code>SpawnMyEntity()</code> function which spawns and returns the templated entity. It can be modified to support multiple templated entities.
Spawned entities can be accessed synchronously in script by using an entity maker. The following generalised example creates a global <code>SpawnMyEntity()</code> function which spawns and returns the templated entity. It can be modified to support multiple templated entities.
{{ExpandBox|<source lang=cpp>
{{ExpandBox|<source lang=js>
m_hSpawnedEntity <- null;
m_hSpawnedEntity <- null
m_KeyValues <- null;
m_KeyValues <- null


m_hSpawner <- Entities.CreateByClassname( "env_entity_maker" );
m_hSpawner <- Entities.CreateByClassname("env_entity_maker")
m_hSpawner.__KeyValueFromString( "EntityTemplate", self.GetName() );
m_hSpawner.__KeyValueFromString("EntityTemplate", self.GetName())


function PreSpawnInstance( classname, targetname )
function PreSpawnInstance(classname, targetname)
{
{
return m_KeyValues;
return m_KeyValues
}
}


function PostSpawn( entities )
function PostSpawn(entities)
{
{
foreach ( targetname, entity in entities )
foreach (targetname, entity in entities)
{
{
m_hSpawnedEntity = entity;
m_hSpawnedEntity = entity
break;
break
}
}
}
}


::SpawnMyEntity <- function( keyvalues = null )
::SpawnMyEntity <- function(keyvalues = null)
{
{
m_KeyValues = keyvalues;
m_KeyValues = keyvalues
m_hSpawner.SpawnEntity();
m_hSpawner.SpawnEntity()
return m_hSpawnedEntity;
return m_hSpawnedEntity
}.bindenv(this)
}.bindenv(this)
</source>}}
</source>}}


Spawn templated entities from any script.
Spawn templated entities from any script.
{{ExpandBox|<source lang=cpp>
{{ExpandBox|<source lang=js>
local ent = SpawnMyEntity( {
local ent = SpawnMyEntity({
rendercolor = Vector( RandomInt(0, 255), RandomInt(0, 255), RandomInt(0, 255) )
rendercolor = Vector(RandomInt(0, 255), RandomInt(0, 255), RandomInt(0, 255))
} )
})


printl( ent )
printl( ent )
Line 2,865: Line 3,619:


=== CFuncTrackTrain ===
=== CFuncTrackTrain ===
Extends [[#CBaseEntity|CBaseEntity]]
Extends [[#CBaseEntity|CBaseEntity ]]


Script handle class for {{ent|func_tracktrain}}.
Script handle class for {{ent|func_tracktrain}}.
Line 2,883: Line 3,637:


=== CPointScriptTemplate ===
=== CPointScriptTemplate ===
Extends [[#CBaseEntity|CBaseEntity]]
Extends [[#CBaseEntity|CBaseEntity ]]


Script handle class for {{ent|point_script_template}}.
Script handle class for {{ent|point_script_template}}.
Line 2,894: Line 3,648:
|-
|-
| <code>AddTemplate</code>
| <code>AddTemplate</code>
| <code>void AddTemplate(string, table)</code>
| <code>void AddTemplate(string ''classname'', table ''keyvalues'')</code>
| Add an entity to the template spawner
| Add an entity with the given keyvalues to the template spawner, similar to <code>SpawnEntityFromTable</code>. The number of templates allowed is unlimited.
|-
|-
| <code>SetGroupSpawnTables</code>
| <code>SetGroupSpawnTables</code>
| <code>void SetGroupSpawnTables(table)</code>
| <code>void SetGroupSpawnTables(table ''group'', table ''spawn'')</code>
| Cache the group spawn tables
| Unused. This only stores a reference to the two tables which is removed when the {{ent|point_script_template}} is deleted.
|}
|}
{{note|To spawn every added template, fire the <code>ForceSpawn</code> input onto the {{ent|point_script_template}} with <code>AcceptInput</code>.}}
==== Hooks ====
<code>PreSpawnInstance</code> hook from {{ent|point_template}} is not available.
;<code>void PostSpawn(table ''entities'')</code>
:Called after the entities are spawned. A table with the handles of the spawned entities indexed by name is passed to the function.
{{bug|hidetested=1|As the <code>PreSpawnInstance</code> hook is not implemented, this callback is never fired. This can be fixed however by defining an entity table named <code>__EntityMakerResult</code> in the entity's scope.}}
{{tip|Due to tables requiring unique keys, templated entities that have no targetname or have conflicting ones will not be present in the table. A workaround is to intercept the <code>__EntityMakerResult</code> table and add every entity to an array instead, as shown in the following example: {{ExpandBox|<source lang=js>
local template = SpawnEntityFromTable("point_script_template", {})
template.SetGroupSpawnTables({})
local scope = template.GetScriptScope()
scope.Entities <- []
scope.__EntityMakerResult <- {entities = scope.Entities}.setdelegate({_newslot = function(_, value) {entities.append(value)}})
scope.PostSpawn <- function(named_entities)
{
__DumpScope(0, Entities)
}
template.AddTemplate("prop_dynamic",
{
model = "models/player/heavy.mdl",
origin = Vector(247, -281, -123)
})
template.AddTemplate("prop_dynamic",
{
model = "models/player/spy.mdl",
origin = Vector(247, -381, -123)
})
template.AcceptInput("ForceSpawn", "", null, null)
</source>}}}}




=== CSceneEntity ===
=== CSceneEntity ===
Extends [[#CBaseEntity|CBaseEntity]]
Extends [[#CBaseEntity|CBaseEntity ]]


Script handle class for {{ent|scripted_scene}}, which make use of [[VCD]] data.
Script handle class for {{ent|scripted_scene}}, which make use of [[VCD]] data.
Line 2,924: Line 3,714:
| <code>FindNamedEntity</code>
| <code>FindNamedEntity</code>
| <code>handle FindNamedEntity(string ''reference'')</code>
| <code>handle FindNamedEntity(string ''reference'')</code>
| Given an entity reference, such as !target, get actual entity from scene object
| Given an entity reference, such as !target, get actual entity from scene object.
|-
|-
| <code>IsPaused</code>
| <code>IsPaused</code>
Line 2,935: Line 3,725:
|-
|-
| <code>LoadSceneFromString</code>
| <code>LoadSceneFromString</code>
| <code>bool LoadSceneFromString(string ''sceneName'', string ''scene'')</code>
| <code>bool LoadSceneFromString(string ''scene_name'', string ''scene'')</code>
| Given a dummy scene name and a vcd string, load the scene.
| Given a dummy scene name and a vcd string, load the scene.
|-
|-
Line 2,956: Line 3,746:
|-
|-
| <code>constructor</code>
| <code>constructor</code>
| <code>CCallChainer(string ''functionPrefix'', table ''scope'' = null)</code>
| <code>CCallChainer(string ''function_prefix'', table ''scope'' = null)</code>
| Creates a CCallChainer object that'll collect functions that have a matching prefix in the given scope.
| Creates a CCallChainer object that'll collect functions that have a matching prefix in the given scope.
|-
|-
Line 2,988: Line 3,778:


=== CSimpleCallChainer ===
=== CSimpleCallChainer ===
Intended to be simpler to use than [[#CCallChainer|CCallChainer]], the class '''CSimpleCallChainer''' holds only a single chain of functions inside an array instead of multiple inside a table. As such, its <code>Call()</code> method does not need a function's name.
Intended to be simpler to use than [[#CCallChainer|CCallChainer ]], the class '''CSimpleCallChainer''' holds only a single chain of functions inside an array instead of multiple inside a table. As such, its <code>Call()</code> method does not need a function's name.


This class is also used internally by these [[#CBaseEntity|CBaseEntity]] hooks: <code>Precache()</code> and <code>OnPostSpawn()</code>.
This class is also used internally by these [[#CBaseEntity|CBaseEntity ]] hooks: <code>Precache()</code> and <code>OnPostSpawn()</code>.


==== Methods ====
==== Methods ====
Line 2,999: Line 3,789:
|-
|-
| <code>constructor</code>
| <code>constructor</code>
| <code>CSimpleCallChainer(string ''functionPrefix'', table ''scope'' = null, exactMatch = false)</code>
| <code>CSimpleCallChainer(string ''prefix'', table ''scope'' = null, ''exactMatch'' = false)</code>
| Creates a CSimpleCallChainer object that'll collect functions that have a matching prefix in the given scope, unless it seek for an exact name match.
| Creates a CSimpleCallChainer object that'll collect functions that have a matching prefix in the given scope, unless it seek for an exact name match.
|-
|-
Line 3,035: Line 3,825:


=== NextBotCombatCharacter ===
=== NextBotCombatCharacter ===
Extends [[#CBaseCombatCharacter|CBaseCombatCharacter]]
Extends [[#CBaseCombatCharacter|CBaseCombatCharacter ]]


Script handle class for non-playable combat characters operating under the [[NextBot]] system.
Script handle class for non-playable combat characters operating under the [[NextBot]] system.
Line 3,048: Line 3,838:
| <code>ClearImmobileStatus</code>
| <code>ClearImmobileStatus</code>
| <code>void ClearImmobileStatus()</code>
| <code>void ClearImmobileStatus()</code>
| Clear immobile status
| Clear immobile status.
|-
|-
| <code>FlagForUpdate</code>
| <code>FlagForUpdate</code>
| <code>void FlagForUpdate(bool)</code>
| <code>void FlagForUpdate(bool ''toggle'')</code>
| Flag this bot for update
| Flag this bot for update (or not to update if ''toggle'' is false).
{{tip|Use this in a think function to update nextbots faster than <code>nb_update_frequency</code>. 0.05 is enough to make existing nextbots such as [[Ghost]] look smooth.}}
|-
|-
| <code>GetBodyInterface</code>
| <code>GetBodyInterface</code>
| <code>INextBotComponent GetBodyInterface()</code>
| <code>INextBotComponent GetBodyInterface()</code>
| Get this bot's body interface
| Get this bot's body interface.
{{note|Not actually exposed, no functions exist.}}
|-
|-
| <code>GetBotId</code>
| <code>GetBotId</code>
| <code>int GetBotId()</code>
| <code>int GetBotId()</code>
| Get this bot's id
| Get this bot's id.
|-
|-
| <code>GetImmobileDuration</code>
| <code>GetImmobileDuration</code>
| <code>float GetImmobileDuration()</code>
| <code>float GetImmobileDuration()</code>
| How long have we been immobile
| How long have we been immobile.
|-
|-
| <code>GetImmobileSpeedThreshold</code>
| <code>GetImmobileSpeedThreshold</code>
| <code>float GetImmobileSpeedThreshold()</code>
| <code>float GetImmobileSpeedThreshold()</code>
| Return units/second below which this actor is considered immobile
| Return units/second below which this actor is considered immobile.
|-
|-
| <code>GetIntentionInterface</code>
| <code>GetIntentionInterface</code>
| <code>INextBotComponent GetIntentionInterface()</code>
| <code>INextBotComponent GetIntentionInterface()</code>
| Get this bot's intention interface
| Get this bot's intention interface.
{{note|Not actually exposed, no functions exist.}}
|-
|-
| <code>GetLocomotionInterface</code>
| <code>GetLocomotionInterface</code>
| <code>ILocomotion GetLocomotionInterface()</code>
| <code>ILocomotion GetLocomotionInterface()</code>
| Get this bot's locomotion interface
| Get this bot's locomotion interface.
|-
|-
| <code>GetTickLastUpdate</code>
| <code>GetTickLastUpdate</code>
| <code>int GetTickLastUpdate()</code>
| <code>int GetTickLastUpdate()</code>
| Get last update tick
| Get last update tick.
|-
|-
| <code>GetVisionInterface</code>
| <code>GetVisionInterface</code>
| <code>INextBotComponent GetVisionInterface()</code>
| <code>INextBotComponent GetVisionInterface()</code>
| Get this bot's vision interface
| Get this bot's vision interface.
{{note|Not actually exposed, no functions exist.}}
|-
|-
| <code>IsEnemy</code>
| <code>IsEnemy</code>
| <code>bool IsEnemy(handle)</code>
| <code>bool IsEnemy(handle ''entity'')</code>
| Return true if given entity is our enemy
| Return true if given entity is our enemy.
|-
|-
| <code>IsFlaggedForUpdate</code>
| <code>IsFlaggedForUpdate</code>
| <code>bool IsFlaggedForUpdate()</code>
| <code>bool IsFlaggedForUpdate()</code>
| Is this bot flagged for update
| Is this bot flagged for update.
|-
|-
| <code>IsFriend</code>
| <code>IsFriend</code>
| <code>bool IsFriend(handle)</code>
| <code>bool IsFriend(handle ''entity'')</code>
| Return true if given entity is our friend
| Return true if given entity is our friend.
|-
|-
| <code>IsImmobile</code>
| <code>IsImmobile</code>
| <code>bool IsImmobile()</code>
| <code>bool IsImmobile()</code>
| Return true if we haven't moved in awhile
| Return true if we haven't moved in awhile.
|}
|}


=== INextBotComponent ===
=== INextBotComponent ===
Base script handle class for any interfaces belonging to an individual [[#NextBotCombatCharacter|NextBotCombatCharacter]] entity.
Base script handle class for any interfaces belonging to an individual [[#NextBotCombatCharacter|NextBotCombatCharacter ]] entity.


==== Methods ====
==== Methods ====
Line 3,114: Line 3,908:
| <code>ComputeUpdateInterval</code>
| <code>ComputeUpdateInterval</code>
| <code>bool ComputeUpdateInterval()</code>
| <code>bool ComputeUpdateInterval()</code>
| Recomputes the component update interval
| Recomputes the component update interval.
|-
|-
| <code>GetUpdateInterval</code>
| <code>GetUpdateInterval</code>
| <code>float GetUpdateInterval()</code>
| <code>float GetUpdateInterval()</code>
| Returns the component update interval
| Returns the component update interval.
|-
|-
| <code>Reset</code>
| <code>Reset</code>
Line 3,126: Line 3,920:


=== ILocomotion ===
=== ILocomotion ===
Extends [[#INextBotComponent|INextBotComponent]]
Extends [[#INextBotComponent|INextBotComponent ]]


The interface for interacting with a specific NextBot's movement brain.
The interface for interacting with a specific NextBot's movement brain.
Line 3,138: Line 3,932:
|-
|-
| <code>Approach</code>
| <code>Approach</code>
| <code>void Approach(Vector, float)</code>
| <code>void Approach(Vector ''goal'', float ''goal_weight'')</code>
| The primary locomotive method. Sets the goal destination for the bot
| The primary locomotive method. Goal determines the destination position to move towards. goal_weight determines the priority of this path, you can set this to 1.0 generally speaking.
{{tip|To make the entity move smoothly towards its destination make sure to put this under a think function.}}
|-
|-
| <code>ClearStuckStatus</code>
| <code>ClearStuckStatus</code>
| <code>void ClearStuckStatus(string)</code>
| <code>void ClearStuckStatus(string ''reason'')</code>
| Reset stuck status to un-stuck
| Reset stuck status to un-stuck. Reason message is shown when debugging nextbots.
|-
|-
| <code>ClimbUpToLedge</code>
| <code>ClimbUpToLedge</code>
| <code>bool ClimbUpToLedge(Vector, Vector, handle)</code>
| <code>bool ClimbUpToLedge(Vector ''goal_pos'', Vector ''goal_forward'', handle ''obstacle'')</code>
| Initiate a jump to an adjacent high ledge, return false if climb can't start
| Initiate a jump to an adjacent high ledge, return false if climb can't start.
|-
|-
| <code>ComputeUpdateInterval</code>
| <code>ComputeUpdateInterval</code>
| <code>ComputeUpdateInterval()</code>
| <code>bool ComputeUpdateInterval()</code>
|  
| Returns false if no time has elapsed.
|-
|-
| <code>DriveTo</code>
| <code>DriveTo</code>
| <code>void DriveTo(Vector)</code>
| <code>void DriveTo(Vector ''pos'')</code>
| Move the bot to the precise given position immediately, updating internal state
| Move the bot to the precise given position immediately, updating internal state.
|-
|-
| <code>FaceTowards</code>
| <code>FaceTowards</code>
| <code>void FaceTowards(Vector)</code>
| <code>void FaceTowards(Vector ''target'')</code>
| Rotate body to face towards target
| Rotate body to face towards target.
{{tip|To make the entity look smoothly towards a spot make sure to put this under a think function, as using the function only once makes the entity only look towards it a bit but not fully, rotating ever so slightly.}}
|-
|-
| <code>FractionPotentialGap</code>
| <code>FractionPotentialGap</code>
| <code>float FractionPotentialGap(Vector, Vector)</code>
| <code>float FractionPotentialGap(Vector ''from'', Vector ''to'')</code>
| If the locomotor cannot jump over the gap, returns the fraction of the jumpable ray
| If the locomotor cannot jump over the gap, returns the fraction of the jumpable ray.
|-
|-
| <code>FractionPotentiallyTraversable</code>
| <code>FractionPotentiallyTraversable</code>
| <code>float FractionPotentiallyTraversable(Vector, Vector, bool)</code>
| <code>float FractionPotentiallyTraversable(Vector ''from'', Vector ''to'', bool ''immediately'')</code>
| If the locomotor could not move along the line given, returns the fraction of the walkable ray.
| If the locomotor could not move along the line given, returns the fraction of the walkable ray. If ''immediately'' is true, breakables are considered non-traverseable.
|-
|-
| <code>GetDeathDropHeight</code>
| <code>GetDeathDropHeight</code>
| <code>float GetDeathDropHeight()</code>
| <code>float GetDeathDropHeight()</code>
| Distance at which we will die if we fall
| Distance at which we will die if we fall.
|-
|-
| <code>GetDesiredSpeed</code>
| <code>GetDesiredSpeed</code>
| <code>float GetDesiredSpeed()</code>
| <code>float GetDesiredSpeed()</code>
| Get desired speed for locomotor movement
| Get desired speed for locomotor movement.
|-
|-
| <code>GetFeet</code>
| <code>GetFeet</code>
| <code>Vector GetFeet()</code>
| <code>Vector GetFeet()</code>
| Return position of feet - the driving point where the bot contacts the ground
| Return position of feet - the driving point where the bot contacts the ground.
|-
|-
| <code>GetGround</code>
| <code>GetGround</code>
| <code>handle GetGround()</code>
| <code>handle GetGround()</code>
| Return the current ground entity or NULL if not on the ground
| Return the current ground entity or NULL if not on the ground.
|-
|-
| <code>GetGroundMotionVector</code>
| <code>GetGroundMotionVector</code>
| <code>Vector GetGroundMotionVector()</code>
| <code>Vector GetGroundMotionVector()</code>
| Return unit vector in XY plane describing our direction of motion - even if we are currently not moving
| Return unit vector in XY plane describing our direction of motion - even if we are currently not moving.
|-
|-
| <code>GetGroundNormal</code>
| <code>GetGroundNormal</code>
| <code>Vector GetGroundNormal()</code>
| <code>Vector GetGroundNormal()</code>
| Surface normal of the ground we are in contact with
| Surface normal of the ground we are in contact with.
|-
|-
| <code>GetGroundSpeed</code>
| <code>GetGroundSpeed</code>
| <code>float GetGroundSpeed()</code>
| <code>float GetGroundSpeed()</code>
| Return current world space speed in XY plane
| Return current world space speed in XY plane.
|-
|-
| <code>GetMaxAcceleration</code>
| <code>GetMaxAcceleration</code>
| <code>float GetMaxAcceleration()</code>
| <code>float GetMaxAcceleration()</code>
| Return maximum acceleration of locomotor
| Return maximum acceleration of locomotor.
|-
|-
| <code>GetMaxDeceleration</code>
| <code>GetMaxDeceleration</code>
| <code>float GetMaxDeceleration()</code>
| <code>float GetMaxDeceleration()</code>
| Return maximum deceleration of locomotor
| Return maximum deceleration of locomotor.
|-
|-
| <code>GetMaxJumpHeight</code>
| <code>GetMaxJumpHeight</code>
| <code>float GetMaxJumpHeight()</code>
| <code>float GetMaxJumpHeight()</code>
| Return maximum height of a jump
| Return maximum height of a jump.
{{tip|If using a <code>base_boss</code> entity, as there is currently no available method to modify this value, you can fire the input <code>SetMaxJumpHeight</code> to change it.}}
|-
|-
| <code>GetMotionVector</code>
| <code>GetMotionVector</code>
| <code>Vector GetMotionVector()</code>
| <code>Vector GetMotionVector()</code>
| Return unit vector describing our direction of motion - even if we are currently not moving
| Return unit vector describing our direction of motion - even if we are currently not moving.
|-
|-
| <code>GetRunSpeed</code>
| <code>GetRunSpeed</code>
| <code>float GetRunSpeed()</code>
| <code>float GetRunSpeed()</code>
| Get maximum running speed
| Get maximum running speed.
|-
|-
| <code>GetSpeed</code>
| <code>GetSpeed</code>
| <code>float GetSpeed()</code>
| <code>float GetSpeed()</code>
| Return current world space speed (magnitude of velocity)
| Return current world space speed (magnitude of velocity).
|-
|-
| <code>GetSpeedLimit</code>
| <code>GetSpeedLimit</code>
| <code>float GetSpeedLimit()</code>
| <code>float GetSpeedLimit()</code>
| Get maximum speed bot can reach, regardless of desired speed
| Get maximum speed bot can reach, regardless of desired speed.
|-
|-
| <code>GetStepHeight</code>
| <code>GetStepHeight</code>
| <code>float GetStepHeight()</code>
| <code>float GetStepHeight()</code>
| If delta Z is greater than this, we have to jump to get up
| If delta Z is lower than this, we can step up the surface (like a stair step), but if delta Z is greater than this, we have to jump to get up.
{{tip|If using a <code>base_boss</code> entity, as there is currently no available method to modify this value, you can fire the input <code>SetStepHeight</code> to change it.}}
|-
|-
| <code>GetStuckDuration</code>
| <code>GetStuckDuration</code>
| <code>float GetStuckDuration()</code>
| <code>float GetStuckDuration()</code>
| Return how long we've been stuck
| Return how long we've been stuck.
|-
|-
| <code>GetTraversableSlopeLimit</code>
| <code>GetTraversableSlopeLimit</code>
| <code>float GetTraversableSlopeLimit()</code>
| <code>float GetTraversableSlopeLimit()</code>
| Return Z component of unit normal of steepest traversable slope
| Return Z component of unit normal of steepest traversable slope.
|-
|-
| <code>GetUpdateInterval</code>
| <code>GetUpdateInterval</code>
| <code>GetUpdateInterval()</code>
| <code>float GetUpdateInterval()</code>
|  
| Returns time between updates.
|-
|-
| <code>GetVelocity</code>
| <code>GetVelocity</code>
| <code>Vector GetVelocity()</code>
| <code>Vector GetVelocity()</code>
| Return current world space velocity
| Return current world space velocity.
|-
|-
| <code>GetWalkSpeed</code>
| <code>GetWalkSpeed</code>
| <code>float GetWalkSpeed()</code>
| <code>float GetWalkSpeed()</code>
| Get maximum walking speed
| Get maximum walking speed.
|-
|-
| <code>HasPotentialGap</code>
| <code>HasPotentialGap</code>
| <code>float HasPotentialGap(Vector, Vector)</code>
| <code>float HasPotentialGap(Vector ''from'', Vector ''to'')</code>
| Return true if there is a possible gap that will need to be jumped over
| Checks if there is a possible gap that will need to be jumped over. Returns fraction of ray from 0 to 1.
|-
|-
| <code>IsAbleToClimb</code>
| <code>IsAbleToClimb</code>
| <code>bool IsAbleToClimb()</code>
| <code>bool IsAbleToClimb()</code>
| Return true if this bot can climb arbitrary geometry it encounters
| Return true if this bot can climb arbitrary geometry it encounters.
|-
|-
| <code>IsAbleToJumpAcrossGaps</code>
| <code>IsAbleToJumpAcrossGaps</code>
| <code>bool IsAbleToJumpAcrossGaps()</code>
| <code>bool IsAbleToJumpAcrossGaps()</code>
| Return true if this bot can jump across gaps in its path
| Return true if this bot can jump across gaps in its path.
|-
|-
| <code>IsAreaTraversable</code>
| <code>IsAreaTraversable</code>
| <code>bool IsAreaTraversable(handle)</code>
| <code>bool IsAreaTraversable(handle ''area'')</code>
| Return true if given area can be used for navigation
| Return true if given area can be used for navigation.
|-
|-
| <code>IsAttemptingToMove</code>
| <code>IsAttemptingToMove</code>
| <code>bool IsAttemptingToMove()</code>
| <code>bool IsAttemptingToMove()</code>
| Return true if we have tried to Approach() or DriveTo() very recently
| Return true if we have tried to Approach() or DriveTo() very recently.
|-
|-
| <code>IsClimbingOrJumping</code>
| <code>IsClimbingOrJumping</code>
| <code>bool IsClimbingOrJumping()</code>
| <code>bool IsClimbingOrJumping()</code>
| Is jumping in any form
| Is jumping in any form.
|-
|-
| <code>IsClimbingUpToLedge</code>
| <code>IsClimbingUpToLedge</code>
| <code>bool IsClimbingUpToLedge()</code>
| <code>bool IsClimbingUpToLedge()</code>
| Is climbing up to a high ledge
| Is climbing up to a high ledge.
|-
|-
| <code>IsEntityTraversable</code>
| <code>IsEntityTraversable</code>
| <code>bool IsEntityTraversable(handle, bool)</code>
| <code>bool IsEntityTraversable(handle ''entity'', bool ''immediately'')</code>
| Return true if the entity handle is traversable
| Return true if the entity handle is traversable. If ''immediately'' is true, breakables are considered non-traverseable.
|-
|-
| <code>IsGap</code>
| <code>IsGap</code>
| <code>bool IsGap(Vector, Vector)</code>
| <code>bool IsGap(Vector ''pos'', Vector ''forward'')</code>
| Return true if there is a gap here when moving in the given direction
| Return true if there is a gap at this position.
{{note|''forward'' is unused.}}.
|-
|-
| <code>IsJumpingAcrossGap</code>
| <code>IsJumpingAcrossGap</code>
| <code>bool IsJumpingAcrossGap()</code>
| <code>bool IsJumpingAcrossGap()</code>
| Is jumping across a gap to the far side
| Is jumping across a gap to the far side.
|-
|-
| <code>IsOnGround</code>
| <code>IsOnGround</code>
| <code>bool IsOnGround()</code>
| <code>bool IsOnGround()</code>
| Return true if standing on something
| Return true if standing on something.
|-
|-
| <code>IsPotentiallyTraversable</code>
| <code>IsPotentiallyTraversable</code>
| <code>float IsPotentiallyTraversable(Vector, Vector, bool)</code>
| <code>float IsPotentiallyTraversable(Vector ''from'', Vector ''to'', bool ''immediately'')</code>
| Return true if this locomotor could potentially move along the line given.
| Checks if this locomotor could potentially move along the line given. Returns fraction of trace result (1 = clear). If ''immediately'' is true, breakables are considered non-traverseable.
|-
|-
| <code>IsRunning</code>
| <code>IsRunning</code>
Line 3,303: Line 4,102:
| <code>IsScrambling</code>
| <code>IsScrambling</code>
| <code>bool IsScrambling()</code>
| <code>bool IsScrambling()</code>
| Is in the middle of a complex action (climbing a ladder, climbing a ledge, jumping, etc) that shouldn't be interrupted
| Is in the middle of a complex action (climbing a ladder, climbing a ledge, jumping, etc) that shouldn't be interrupted.
|-
|-
| <code>IsStuck</code>
| <code>IsStuck</code>
Line 3,311: Line 4,110:
| <code>Jump</code>
| <code>Jump</code>
| <code>void Jump()</code>
| <code>void Jump()</code>
| Initiate a simple undirected jump in the air
| Initiate a simple undirected jump in the air.
|-
|-
| <code>JumpAcrossGap</code>
| <code>JumpAcrossGap</code>
| <code>void JumpAcrossGap(Vector, Vector)</code>
| <code>void JumpAcrossGap(Vector ''goal_pos'', Vector ''goal_forward'')</code>
| Initiate a jump across an empty volume of space to far side
| Initiate a jump across an empty volume of space to far side.
{{note|''goal_forward'' is unused.}}
|-
|-
| <code>OnLandOnGround</code>
| <code>OnLandOnGround</code>
| <code>void OnLandOnGround(handle)</code>
| <code>void OnLandOnGround(handle ''ground'')</code>
| Manually run the OnLandOnGround callback. Typically invoked when bot lands on the ground after being in the air
| Manually run the OnLandOnGround callback. Typically invoked when bot lands on the ground after being in the air.
|-
|-
| <code>OnLeaveGround</code>
| <code>OnLeaveGround</code>
| <code>void OnLeaveGround(handle)</code>
| <code>void OnLeaveGround(handle ''ground'')</code>
| Manually run the OnLeaveGround callback. Typically invoked when bot leaves ground for any reason
| Manually run the OnLeaveGround callback. Typically invoked when bot leaves ground for any reason.
|-
|-
| <code>Reset</code>
| <code>Reset</code>
| <code>Reset()</code>
| <code>void Reset()</code>
|  
| Resets motion, stuck state etc.
|-
|-
| <code>Run</code>
| <code>Run</code>
| <code>void Run()</code>
| <code>void Run()</code>
| Set desired movement speed to running
| Set desired movement speed to running.
|-
|-
| <code>SetDesiredSpeed</code>
| <code>SetDesiredSpeed</code>
| <code>void SetDesiredSpeed(float)</code>
| <code>void SetDesiredSpeed(float ''speed'')</code>
| Set desired speed for locomotor movement
| Set desired speed for locomotor movement.
|-
|-
| <code>SetSpeedLimit</code>
| <code>SetSpeedLimit</code>
| <code>void SetSpeedLimit(float)</code>
| <code>void SetSpeedLimit(float ''limit'')</code>
| Set maximum speed bot can reach, regardless of desired speed
| Set maximum speed bot can reach, regardless of desired speed.
|-
|-
| <code>Stop</code>
| <code>Stop</code>
| <code>void Stop()</code>
| <code>void Stop()</code>
| Set desired movement speed to stopped
| Set desired movement speed to stopped.
|-
|-
| <code>Walk</code>
| <code>Walk</code>
Line 3,360: Line 4,160:
|-
|-
| <code>Begin</code>
| <code>Begin</code>
|  
|
|  
|
|-
|-
| <code>End</code>
| <code>End</code>
|  
|
|  
|
|-
|-
| <code>EstablishDelegation</code>
| <code>EstablishDelegation</code>
|  
|
|  
|
|-
|-
| <code>HookRootMetamethod</code>
| <code>HookRootMetamethod</code>
|  
|
|  
|
|-
|-
| <code>UnhookRootMetamethod</code>
| <code>UnhookRootMetamethod</code>
|  
|
|  
|
|-
|-
| <code>RemoveDelegation</code>
| <code>RemoveDelegation</code>
|  
|
|  
|
|-
|-
| <code>Resolve</code>
| <code>Resolve</code>
|  
|
|  
|
|}
|}


Line 3,397: Line 4,197:
| <code>m_bindNamesStack</code>
| <code>m_bindNamesStack</code>
| <code>array</code>
| <code>array</code>
|  
|
|-
|-
| <code>m_fixupSet</code>
| <code>m_fixupSet</code>
| <code>array</code>
| <code>array</code>
|  
|
|-
|-
| <code>m_log</code>
| <code>m_log</code>
| <code>bool</code>
| <code>bool</code>
|  
|
|-
|-
| <code>m_logIndent</code>
| <code>m_logIndent</code>
| <code>int</code>
| <code>int</code>
|  
|
|-
|-
| <code>m_targetTable</code>
| <code>m_targetTable</code>
| <code>table?(null)</code>
| <code>table?(null)</code>
|  
|
|-
|-
|}
|}


=== regexp ===
== Data Types ==
The built-in [http://squirrel-lang.org/doc/sqstdlib3.html#d0e2591 Squirrel class] for regular expressions.
 
=== Vector ===
Squirrel equivalent of the C++ [[Vector]] class. A three-dimensional vector with overloaded arithmetic operations for both Vectors and scalar values.


==== Methods ====
==== Methods ====
Line 3,428: Line 4,230:
|-
|-
| <code>constructor</code>
| <code>constructor</code>
| <code>regexp()</code>
| <code>Vector(float ''x'' = 0.0, float ''y'' = 0.0, float ''z'' = 0.0)</code>
|  
| Creates a new vector with the specified Cartesian coordiantes.
|-
|-
| <code>capture</code>
| <code>Cross</code>
| <code>table capture(''str'', [''start''])</code>
| <code>Vector Cross(Vector ''factor'')</code>
| Returns an array of tables containing two indexes ("begin" and "end") of the first match of the regular expression in the string str. An array entry is created for each captured sub expressions. If no match occurs returns null. The search starts from the index start of the string, if start is omitted the search starts from the beginning of the string.  
| The vector product of two vectors. Returns a vector orthogonal to the input vectors.
|-
|-
| <code>match</code>
| <code>Dot</code>
| <code> bool match(''str'')</code>
| <code>float Dot(Vector ''factor'')</code>
| Returns a true if the regular expression matches the string str, otherwise returns false.  
| The scalar product of two vectors.
|-
|-
| <code>search</code>
| <code>Length</code>
| <code>table search(''str'', [''start''])</code>
| Returns a table containing two indexes ("begin" and "end") of the first match of the regular expression in the string ''str'', otherwise if no match occurs returns null. The search starts from the index start of the string, if start is omitted the search starts from the beginning of the string.
|-
| <code>subexpcount</code>
| <code>subexpcount()</code>
|
|}
 
== Data Types ==
 
=== Vector ===
Squirrel equivalent of the C++ [[Vector]] class. A three-dimensional vector with overloaded arithmetic operations for both Vectors and scalar values.
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>constructor</code>
| <code>Vector(float ''x'' = 0, float ''y'' = 0, float ''z'' = 0)</code>
| Creates a new vector with the specified Cartesian coordiantes.
|-
| <code>Cross</code>
| <code>Vector Cross(Vector ''factor'')</code>
| The vector product of two vectors. Returns a vector orthogonal to the input vectors.
|-
| <code>Dot</code>
| <code>float Dot(Vector ''factor'')</code>
| The scalar product of two vectors.
|-
| <code>Length</code>
| <code>float Length()</code>
| <code>float Length()</code>
| Magnitude of the vector.
| Magnitude of the vector.
Line 3,478: Line 4,247:
| <code>LengthSqr</code>
| <code>LengthSqr</code>
| <code>float LengthSqr()</code>
| <code>float LengthSqr()</code>
| The magnitude of the vector squared. Faster than the above method.
| The magnitude of the vector squared.
{{tip|This can be used to quickly check if the vector is equal to 0 0 0, by checking if the magnitude is 0.}}
|-
|-
| <code>Length2D</code>
| <code>Length2D</code>
| <code>float Length2D()</code>
| <code>float Length2D()</code>
| Returns the magnitude of the vector on the x-y plane. Meant to be used when working with the client's HUD.
| Returns the magnitude of the vector on the x-y plane.
|-
|-
| <code>Length2DSqr</code>
| <code>Length2DSqr</code>
| <code>float Length2DSqr()</code>
| <code>float Length2DSqr()</code>
| Returns the square of the magnitude of the vector on the x-y plane. Faster than the above method.
| Returns the square of the magnitude of the vector on the x-y plane.
|-
|-
| <code>Norm</code>
| <code>Norm</code>
Line 3,534: Line 4,304:
| <code>Vector + Vector</code>
| <code>Vector + Vector</code>
|rowspan="2"| <code>Vector</code>
|rowspan="2"| <code>Vector</code>
|rowspan="2"| Returns the sum of both classes's members (XYZ).
|rowspan="2"| Returns the sum of both classes's members.
|-
|-
| <code>QAngle + Vector</code>
| <code>QAngle + Vector</code>
Line 3,540: Line 4,310:
| <code>Vector - Vector</code>
| <code>Vector - Vector</code>
|rowspan="2"| <code>Vector</code>
|rowspan="2"| <code>Vector</code>
|rowspan="2"| Returns the subtraction of both classes's members (XYZ).
|rowspan="2"| Returns the subtraction of both classes's members.
|-
|-
| <code>QAngle + Vector</code>
| <code>QAngle - Vector</code>
|-
|-
| <code>Vector * integer</code>
| <code>Vector * integer</code>
Line 3,564: Line 4,334:
|-
|-
| <code>constructor</code>
| <code>constructor</code>
| <code>QAngle(float ''pitch'' = 0, float ''yaw'' = 0, float ''roll'' = 0)</code>
| <code>QAngle(float ''pitch'' = 0.0, float ''yaw'' = 0.0, float ''roll'' = 0.0)</code>
| Creates a new QAngle.
| Creates a new QAngle.
|-
|-
| <code>Forward </code>
| <code>Forward </code>
| <code>Vector Forward()</code>
| <code>Vector Forward()</code>
| Returns the Forward Vector of the angles.  
| Returns the Forward Vector of the angles.
|-
|-
| <code>Left</code>
| <code>Left</code>
| <code>Vector Left()</code>
| <code>Vector Left()</code>
| Returns the left Vector of the angles.
| {{note|Returns the ''right'' Vector of the angles.}}
|-
|-
| <code>Pitch</code>
| <code>Pitch</code>
Line 3,628: Line 4,398:
| <code>QAngle + QAngle</code>
| <code>QAngle + QAngle</code>
|rowspan="2"| <code>QAngle</code>
|rowspan="2"| <code>QAngle</code>
|rowspan="2"| Sum of both classes's members (XYZ).  
|rowspan="2"| Sum of both classes's members (XYZ).
|-
|-
| <code>Vector + QAngle</code>
| <code>Vector + QAngle</code>
Line 3,647: Line 4,417:


=== Vector2D, Vector4D ===
=== Vector2D, Vector4D ===
Two and four-dimensional equivalents to Vector.
Two and four-dimensional equivalents to Vector with less amount of methods.


==== Methods ====
==== Methods ====
Line 3,657: Line 4,427:
|-
|-
| <code>constructor</code>
| <code>constructor</code>
| <code>Vector''X''D(float ''x'', float ''y'', ...)</code>
| <code>Vector2D(float ''x'' = 0.0, float ''y'' = 0.0)</code>
| Creates a new vector with the specified Cartesian coordiantes.
| Creates a new 2-dimensional vector with the specified Cartesian coordiantes.
|-
| <code>constructor</code>
| <code>Vector4D(float ''x'' = 0.0, float ''y'' = 0.0, float ''z'' = 0.0, float ''w'' = 0.0)</code>
| Creates a new 4-dimensional vector with the specified Cartesian coordiantes.
|-
|-
| <code>Dot</code>
| <code>Dot</code>
Line 3,670: Line 4,444:
| <code>LengthSqr</code>
| <code>LengthSqr</code>
| <code>float LengthSqr()</code>
| <code>float LengthSqr()</code>
| The magnitude of the vector squared. Faster than the above method.
| The magnitude of the vector squared.
{{tip|This can be used to quickly check if the vector's members are all 0, by checking if the magnitude is 0.}}
|-
|-
| <code>Norm</code>
| <code>Norm</code>
| <code>float Norm()</code>
| <code>float Norm()</code>
| Seems to also return the vector length.
| Normalizes the vector in place and returns it's length.
|-
|-
| <code>ToKVString</code>
| <code>ToKVString</code>
Line 3,694: Line 4,469:
| <code>constructor</code>
| <code>constructor</code>
| <code>Quaternion()</code>
| <code>Quaternion()</code>
| Creates a new identity quaternion.
| Creates a new identity quaternion. (0, 0, 0, 1)
|-
|-
| <code>constructor</code>
| <code>constructor</code>
| <code>Quaternion(float ''x'',float ''y'',float ''z'',float ''w'')</code>
| <code>Quaternion(float ''x'', float ''y'' = 0.0, float ''z'' = 0.0, float ''w'' = 0.0)</code>
| Creates a new quaternion of the form <code>''w'' + ''x'''''i''' + ''y'''''j''' + ''z'''''k'''</code>.
| Creates a new quaternion of the form <code>''w'' + ''x'''''i''' + ''y'''''j''' + ''z'''''k'''</code>.
|-
|-
Line 3,709: Line 4,484:
|-
|-
| <code>Norm</code>
| <code>Norm</code>
| <code>Quaternion Norm()</code>
| <code>float Norm()</code>
| Normalizes the 4D vector length. {{todo|What effect does this have in quaternions?}}
| Normalizes the quaternion.
|-
|-
| <code>SetPitchYawRoll</code>
| <code>SetPitchYawRoll</code>
Line 3,780: Line 4,555:
|-
|-
| <code>AddThinkToEnt</code>
| <code>AddThinkToEnt</code>
| <code>void AddThinkToEnt(handle ''entity'', string ''FuncName'')</code>
| <code>void AddThinkToEnt(handle ''entity'', string ''function_name'')</code>
| Sets a function in the entity's script to rerun by itself constantly. Pass null as the function name to remove a think function. The default think interval is 0.1s, unless overridden by returning a different time interval in seconds in the think function
| Sets a function in the entity's script to rerun by itself constantly. Pass null as the function name to remove a think function.
{{tip|Return -1 to think every tick. Do not return 0, this will give inconsistent intervals. {{confirm|This issue has only been observed on players}}}}
The default think interval is 0.1s, unless overridden by returning a different time interval in seconds in the think function. TF2 runs at 66 ticks per second, so the lowest possible interval is 0.015 seconds.
{{note|If trying to clear a think function while inside a think function, this function alone will not work as the think function is restored on the entity after it's finished. <br><code>NetProps.SetPropString(self, "m_iszScriptThinkFunction", "");</code> must be used to fully clear the think function.
Return -1 to think every tick (do not return 0 or 0.015, this will give inconsistent intervals).
The highest interval where all clients will [[Interpolation|interpolate]] entities. regardless of network settings, is 0.05 (20 times per second).
{{note|If trying to clear a think function while inside a think function, <code>AddThinkToEnt</code> will not work as the think function is restored on the entity after it's finished. <br><code>NetProps.SetPropString(self, "m_iszScriptThinkFunction", "")</code> must be used to remove the think function.
{{warning|This can apply to events if they are chained from a think function, for example killing a player with <code>TakeDamage</code> and then trying to clear the think function in <code>player_death</code> event. The think function will not be cleared unless the line above is also added.}}}}
{{warning|This can apply to events if they are chained from a think function, for example killing a player with <code>TakeDamage</code> and then trying to clear the think function in <code>player_death</code> event. The think function will not be cleared unless the line above is also added.}}}}
{{bug|The think function name stored in the entity is not reset if null is passed as the function name. However this is harmless, and it will only show a warning in console.}}
{{note|Some entities are sensitive to when this think function executes within a frame. A notable example is modifying the [[tf_player_manager]] entity. The think function must be applied to the manager entity for netprop changes to work correctly, and not any other entity, otherwise modifying its properties will be inconsistent.}}
{{bug|hidetested=1|The think function name stored in the entity is not reset if null is passed as the function name. However this is harmless, and it will only show a warning in console.}}
{{warning|Entities with <code>EFL_KILLME</code> and/or <code>EFL_NO_THINK_FUNCTION</code> entity flags set do not process thinks.}}
|-
|-
| <code>AddToScriptHelp</code>
| <code>AddToScriptHelp</code>
| <code>AddToScriptHelp()</code>
| <code>void AddToScriptHelp(table ''help'')</code>
|  
|
|-
|-
| <code>AllowThirdPersonCamera</code>
| <code>Assert</code>
| <code>bool AllowThirdPersonCamera()</code>
| <code>void Assert(bool ''value'', string ''optional_message'' = null)</code>
|
| Test value and if not true, throws exception, optionally with message.
|-
| <code>ArePlayersInHell</code>
| <code>bool ArePlayersInHell()</code>
|
|-
| <code>Assert</code>
| <code>void Assert(bool ''value'', string ''optional message'')</code>
| Test value and if not true, throws exception, optionally with message.
|-
|-
| <code>ClearGameEventCallbacks</code>
| <code>ClearGameEventCallbacks</code>
| <code>void ClearGameEventCallbacks()</code>
| <code>void ClearGameEventCallbacks()</code>
| Empties the tables of game event callback functions.
| Empties the tables of game event callback functions.
|-
{{deprecated|'''Do NOT use this!''' It removes all events, including those from other scripts, and is a common source of script conflicts. Instead, update your event code to use a namespace (define and contain your callback functions inside of a table), which will clean up automatically when this table is removed without interfering with other scripts. Refer to the [[Source_SDK_Base_2013/Scripting/VScript_Examples#Listening_for_Events|examples page]] and expand the example for Team Fortress 2 for guidance on how to set an automatic system for this.}}
| <code>ConnectOutputs</code>
| <code>void ConnectOutputs(table)</code>
| sets output functions for entity by table {{todo}}
|-
|-
| <code>CreateProp</code>
| <code>CreateProp</code>
| <code>handle CreateProp(string, Vector, string, int)</code>
| <code>CBaseAnimating CreateProp(string ''classname'', Vector ''origin'', string ''model_name'', int ''activity'')</code>
| Create a physics prop
| Create a prop.
|-
|-
| <code>CreateSceneEntity</code>
| <code>CreateSceneEntity</code>
| <code>handle CreateSceneEntity(string)</code>
| <code>CBaseAnimating CreateSceneEntity(string ''scene'')</code>
| Create a scene entity to play the specified scene.
| Create a scene entity to play the specified scene.
|-
|-
Line 3,824: Line 4,592:
|-
|-
| <code>DispatchParticleEffect</code>
| <code>DispatchParticleEffect</code>
| <code>void DispatchParticleEffect(string ''name'', Vector ''origin'', Vector ''angles'')</code>
| <code>void DispatchParticleEffect(string ''name'', Vector ''origin'', Vector ''direction'')</code>
| Dispatches a one-off particle system {{ModernBug|The angles parameter is incorrectly defined as a ''Vector'' type rather than ''QAngle''.}}
| Dispatches a one-off particle system. To pass angles into this, use the <code>.Forward()</code> method on a QAngle.
{{note|For more control over particles such as parenting them to entities, see the [[Source_SDK_Base_2013/Scripting/VScript_Examples#Spawning_a_Particle|examples page]] for alternative methods.}}
{{warning|Does NOT work if called from a player think or OnTakeDamage caused by hitscan/melee due to [[prediction]] suppressing it. Can be workarounded by spawning the particle with a 0 delayed EntFire or spawning [[info_particle_system]] entity}}
{{warning|This does not precache custom particles. As a result, custom particles may show as a burst of red Xs instead on dedicated servers. To precache a particle, use the following function:
{{ExpandBox|<source lang=js>
function PrecacheParticle(name)
{
PrecacheEntityFromTable({ classname = "info_particle_system", effect_name = name })
}
</source>}}
}}
|-
|-
| <code>Document</code>
| <code>Document</code>
| <code>void Document(unknown ''symbolOrTable'', unknown ''itemIfSymbol'' = null, string ''descriptionIfSymbol'' = null)</code>
| <code>void Document(unknown ''symbol_or_table'', unknown ''item_if_symbol'' = null, string ''description_if_symbol'' = null)</code>
|
|-
|-
| <code>DoEntFire</code>
| <code>DoEntFire</code>
| <code>void DoEntFire(string ''target'', string ''action'', string ''value'', float ''delay'', handle ''activator'', handle ''caller'')</code>
| <code>void DoEntFire(string ''target'', string ''action'', string ''value'', float ''delay'', handle ''activator'', handle ''caller'')</code>
| Generate an entity I/O event. The ''caller'' and ''activator'' argument takes a ''CBaseEntity'' script handle, and entities assigned can receive inputs with ''target'' set to ''!self'', or ''!activator'' / ''!caller''.
| Generate an entity I/O event. The ''caller'' and ''activator'' argument takes a ''CBaseEntity'' script handle, and entities assigned can receive inputs with ''target'' set to ''!self'', or ''!activator'' / ''!caller''. Negative delays are clamped to 0.
{{tip|Use a -1 delay to consistently fire it at the end of the frame. 0 delay might bring inconsistent timing.}}
{{note|Does not work if the ''target'' string is <code>point_servercommand</code>.}}
|-
|-
| <code>DoIncludeScript</code>
| <code>DoIncludeScript</code>
| <code>bool DoIncludeScript(string ''file'', handle/table ''scope'')</code>
| <code>bool DoIncludeScript(string ''file'', handle/table ''scope'')</code>
| Execute a script. and put all its content for the argument passed to the<code>''scope''</code>parameter. (internal)
| Execute a script and put all its content for the argument passed to the<code>''scope''</code>parameter. The file must have the <code>.nut</code> extension.
{{warning|Do not put uppercase letters in the path, doing so will cause Linux to fail loading the script from loose directories.}}
|-
|-
| <code>IncludeScript</code>
| <code>IncludeScript</code>
| <code>bool IncludeScript(string ''file'', handle ''scope'' = null)</code>
| <code>bool IncludeScript(string ''file'', table ''scope'' = null)</code>
| Wrapper for DoIncludeScript
| Wrapper for DoIncludeScript.
|-
|-
| <code>EmitAmbientSoundOn</code>
| <code>EmitAmbientSoundOn</code>
| <code>void EmitAmbientSoundOn(string ''soundName'', float ''volume'', int ''soundlevel'', int ''pitch'', handle ''entity'')</code>
| <code>void EmitAmbientSoundOn(string ''sound_name'', float ''volume'', int ''soundlevel'', int ''pitch'', handle ''entity'')</code>
| Play named sound on an entity using configurations similar to [[ambient_generic]]. Soundlevel is in decibels, see [[Soundscripts#SoundLevel|this page]] for real world equivalents.
| Play named sound on an entity using configurations similar to [[ambient_generic]]. Soundlevel is in decibels, see [[Soundscripts#SoundLevel|this page]] for real world equivalents.
{{tip|Sounds may be hard to hear even at full volume. Naming custom sounds according to the [[soundmixer]] can be used to make them naturally louder.}}
{{tip|Sounds may be hard to hear even at full volume. Naming custom sounds according to the [[soundmixer]] can be used to make them naturally louder.}}
{{tip|To convert radius in Hammer units to decibels (similar to [[ambient_generic]]), use the following formula:
<source lang=js>
local soundlevel = (40 + (20 * log10(radius / 36.0))).tointeger()
</source>
}}
|-
|-
| <code>StopAmbientSoundOn</code>
| <code>StopAmbientSoundOn</code>
| <code>void StopAmbientSoundOn(string ''soundName'', handle ''entity'')</code>
| <code>void StopAmbientSoundOn(string ''sound_name'', handle ''entity'')</code>
| Stop named sound on an entity using configurations similar to [[ambient_generic]].
| Stop named sound on an entity using configurations similar to [[ambient_generic]].
|-
|-
| <code>EmitSoundEx</code>
| <code>[[Team Fortress 2/Scripting/Script Functions/EmitSoundEx|EmitSoundEx]]</code>
| <code>void EmitSoundEx(handle ''table'')</code>
| <code>void EmitSoundEx(table ''params'')</code>
| Play a sound. Takes in a script table of params. All parameters are optional except ''sound_name''.
| Play a sound. Takes in a script table of params: <code>sound_name</code>, <code>channel</code>, <code>volume</code>, <code>sound_level</code>, <code>flags</code>, <code>pitch</code>, <code>special_dsp</code>, <code>origin</code>, <code>delay</code>, <code>sound_time</code>, <code>entity</code>, <code>speaker_entity</code>, <code>filter_type</code>, <code>filter_param</code>. All parameters are optional except ''sound_name''. See the [[Team Fortress 2/Scripting/Script Functions/EmitSoundEx|main page]] for more details.
{| class="standard-table" style="width:100%"
! Name
! Type
! Default
! Description
|-
|-
| <code>sound_name</code>
| <code>EmitSoundOn</code>
| <code>string</code>
| <code>void EmitSoundOn(string ''sound_script'', handle ''entity'')</code>
|
| Play named sound on given entity. The sound must be precached first for it to play (using <code>PrecacheSound</code> or <code>PrecacheScriptSound</code>).
| Name of sound. Can be raw filename or soundscript.
{{warning|Looping sounds will not stop on the entity when it's destroyed and will persist forever! To workaround this, run <code>StopSound</code> in the <code>OnDestroy</code> callback.}}
|-
|-
| <code>channel</code>
| <code>StopSoundOn</code>
| <code>int</code>
| <code>void StopSoundOn(string ''sound_script'', handle ''entity'')</code>
| 0
| Stop named sound on an entity.
| Channel ID on which to play the sound. Channels from -1 to 8 have special behavior, all other channels behave normally. List of special channels:
* -1 : CHAN_REPLACE
* 0 : CHAN_AUTO
* 1 : CHAN_WEAPON
* 2 : CHAN_VOICE
* 3 : CHAN_ITEM
* 4 : CHAN_BODY
* 5 : CHAN_STREAM
* 6 : CHAN_STATIC
* 7 : CHAN_VOICE2
* 8 : CHAN_VOICE_BASE
|-
|-
| <code>volume</code>
| <code>EmitSoundOnClient</code>
| <code>float</code>
| <code>void EmitSoundOnClient(string ''sound_script'', handle ''player'')</code>
| 1.0
| Play named sound only on the client for the specified player. The sound must be precached first for it to play (<code>PrecacheScriptSound</code>).
| Volume of sound, in normalized 0 - 1 range. {{tip|Sounds may be hard to hear even at full volume. Naming custom sounds according to the [[soundmixer]] can be used to make them naturally louder.}}
{{note|This only supports soundscripts.}}
|-
|-
| <code>sound_level</code>
| <code>EntFire</code>
| <code>int</code>
| <code>void EntFire(string ''target'', string ''action'', string ''value'' = null, float ''delay'' = 0, handle ''activator'' = null)</code>
| 0  
| Wrapper for DoEntFire() that sets<code>''activator''</code> to null, but has no<code>''caller''</code>param. Negative delays are clamped to 0.
| Sound attenuation in decibels. See [[Soundscripts#SoundLevel|this page]] for real world equivalents.
{{note|Does not work if the ''target'' string is <code>point_servercommand</code>.}}
|-
|-
| <code>flags</code>
| <code>EntFireByHandle</code>
| <code>int</code>
| <code>void EntFireByHandle(handle ''entity'', string ''action'', string ''value'', float ''delay'', handle ''activator'', handle ''caller'')</code>
| 0
| Generate an entity I/O event. First parameter is an entity instance. Negative delays are clamped to 0.
| Special sound flags. List of flags available:
{{note|With a 0 delay, this will be processed at the end of the frame rather than instantly. If you need an instant, synchronous I/O event then use <code>AcceptInput</code> instead.}}
{| class="standard-table" style="width:100%"
{{warning|Calling <code>RunScriptCode</code> input will add the value provided to the string table. If your code uses a big range of distinct values provided to this input (for example passing a float like timestamp) the string table will eventually exceed it's limit of 65k strings causing the server to crash (CUtlRBTree overflow). To prevent this issue from occurring you can use custom delay function, such as the one implemented in [[Source_2013_MP/Scripting/VScript_Examples#EntFire(ByHandle)|Source SDK 2013 VScript Examples]].
! Name
{{note|This also affects <code>SetText</code> input on [[game_text]], but accounting for it is not as vital.}}
! Value
}}
! Description
|-
|-
| <code>No Flags</code>
| <code>EntIndexToHScript</code>
| <code>0</code>
| <code>handle EntIndexToHScript(int ''entindex'')</code>
| Nothing special.
| Turn an entity index integer to an HScript representing that entity's script instance.
|-
|-
| <code>Change Volume</code>
| <code>FileToString</code>
| <code>1</code>
| <code>string FileToString(string ''file'')</code>
| Changes volume of an already-playing sound on this entity.
| Reads a string from file located in the game's ''scriptdata'' folder. Returns the string from the file, null if no file or file is greater than 16384 bytes.
{{note|Files packed inside the [[BSP]] cannot be read.}}
{{note|This opens files in text mode, therefore binary files will not be parsed correctly.}}
|-
|-
| <code>Change Pitch</code>
| <code>FindCircularReference</code>
| <code>2</code>
| <code>FindCircularReference()</code>
| Changes pitch of an already-playing sound on this entity.
|
|-
|-
| <code>Stop Sound</code>
| <code>FindCircularReferences</code>
| <code>4</code>
| <code>FindCircularReferences()</code>
| Stops the specified sound if playing on this entity. {{ModernNote|This may be channel-specific.}}
|
|-
|-
| <code>Spawning</code>
| <code>FireGameEvent</code>
| <code>8</code>
| <code>bool FireGameEvent(string ''name'', table ''params'')</code>
| Writes sound info into net message for connecting clients. {{ModernNote|This probably doesn't do anything at runtime.}}
| Fire a game event to a listening callback function in script. Parameters are passed in a squirrel table.
{{note|The name might be misleading. This does not fire an event that the game will pick up, the function that sends a real game event is named <code>SendGlobalGameEvent</code>.}}
|-
|-
| <code>Delay</code>
| <code>FireScriptHook</code>
| <code>16</code>
| <code>bool FireScriptHook(string ''name'', table ''params'')</code>
| Specifies the sound should be scheduled with a delay.
| Fire a script hook to a listening callback function in script. Parameters are passed in a squirrel table.
|-
|-
| <code>Stop Looping</code>
| <code>FireScriptEvent</code>
| <code>32</code>
| <code>void FireScriptEvent(string ''event'', table ''params'')</code>
| Stop all looping sounds on the entity. {{ModernBug|Not implemented by the engine.}}
| Wrapper for <code>__RunEventCallbacks()</code>.
|-
|-
| <code>Speaker</code>
| <code>FrameTime</code>
| <code>64</code>
| <code>float FrameTime()</code>
| Used by audio played through [[env_microphone]]. Applies special mixing rules.
| Get the time spent on the server in the last frame. Usually this will be 0.015 (the default tickrate).
|-
|-
| <code>Should Pause</code>
| <code>GetDeveloperLevel</code>
| <code>128</code>
| <code>int GetDeveloperLevel()</code>
| Sound will be paused when the game is paused. Useless in multiplayer.
| Gets the level of 'developer'
|-
|-
| <code>Ignore Phonemes</code>
| <code>GetFrameCount</code>
| <code>256</code>
| <code>int GetFrameCount()</code>
| Prevents [[flex animation]] from being driven by this sound, if available.
| Returns the engines current frame count. The counter does not reset between map changes. This is NOT the tick count.
{{tip|To get the current tick count, read the <code>m_nSimulationTick</code> netprop from any player or moving entity.}}
|-
|-
| <code>Ignore Name</code>
| <code>GetFriction</code>
| <code>512</code>
| <code>float GetFriction(CTFPlayer ''player'')</code>
| Changes all sounds emitted on the entity, regardless of actual name.
| Returns the Friction on a player entity, meaningless if not a player.
|-
|-
| <code>Do Not Overwrite Existing On Channel</code>
| <code>GetFunctionSignature</code>
| <code>1024</code>
| <code>string GetFunctionSignature(function ''func'', string ''prefix'')</code>
| If an existing sound is found on the channel, the sound will not play instead of overwriting it.
|
|}
|-
|-
| <code>pitch</code>
| <code>GetListenServerHost</code>
| <code>int</code>
| <code>CTFPlayer GetListenServerHost()</code>
| 100
| Get the local player on a listen server. Returns null on dedicated servers.
| Pitch of the sound.
{{note|This depends on the player entity, and therefore this might return null on a listen server if the player doesn't exist yet during map load. Use <code>IsDedicatedServer</code> instead to check if the server is a listen or dedicated server, as it checks it in a different way.}}
{{tip|Alternatively, use <code>PlayerInstanceFromIndex(1)</code> to fetch the first player on the server. For convenience sake (e.g. for script compatibility), you can map this to that function using the following:
<source lang=js>
::GetListenServerHost <- @() PlayerInstanceFromIndex(1)
</source>}}
|-
|-
| <code>special_dsp</code>
| <code>GetMapName</code>
| <code>int</code>
| <code>string GetMapName()</code>
| 0
| Get the name of the map without extension, e.g. <code>ctf_2fort</code>. For workshop maps, this will be in the format <code>workshop/[name].ugc[id]</code>.
| [[DSP]] effect to use on this sound.
|-
|-
| <code>origin</code>
| <code>GetModelIndex</code>
| <code>Vector</code>
| <code>int GetModelIndex(string ''model_name'')</code>
|  
| Returns the index of the named model.
| Overwrites sound origin if specified.
{{ModernNote|If not specified, the origin will be fetched from the <code>entity</code> parameter for <code>RECIPIENT_FILTER_PAS</code> and <code>RECIPIENT_FILTER_PVS</code> filters.}}
|-
|-
| <code>delay</code>
| {{obs}} <code>GetPhysAngularVelocity</code>
| <code>float</code>
| <code>Vector GetPhysAngularVelocity(handle ''entity'')</code>
|  
| Returns the Angular velocity of the entity. Deprecated, use the <code>GetPhysAngularVelocity</code> method on the entity instead.
| Delay before playing sound. {{ModernNote|Might require ''Delay'' flag to be set.}}
|-
|-
| <code>sound_time</code>
| {{obs}} <code>GetPhysVelocity</code>
| <code>float</code>
| <code>Vector GetPhysVelocity(handle ''entity'')</code>
|  
| Returns the velocity of the entity. Deprecated, use the <code>GetPhysVelocity</code> method on the entity instead.
| Absolute time to delay sound until, NOT the duration. Overrides <code>delay</code> if specified. {{ModernNote|Might require ''Delay'' flag to be set.}}
|-
|-
| <code>entity</code>
| <code>GetPlayerFromUserID</code>
| <code>handle</code>
| <code>CTFPlayer GetPlayerFromUserID(int ''userid'')</code>
| null
| Given a user id, return the entity, or null.
| Optional (player) entity to filter sounds to. All filters can use this except <code>RECIPIENT_FILTER_GLOBAL</code> and <code>RECIPIENT_FILTER_TEAM</code>. E.g. <code>RECIPIENT_FILTER_SINGLE_PLAYER</code> will play sounds only to the specified player here.
{{note|The 'fake' [[SourceTV]] player will always be returned as null. If you need to actually retrieve the SourceTV player, use <code>EntIndexToHScript</code>.}}
{{tip|For the opposite, getting the user id from an entity, see the [[Source_SDK_Base_2013/Scripting/VScript_Examples#Getting_the_userid_from_a_player_handle|examples page]].}}
|-
|-
| <code>speaker_entity</code>
| <code>GetSoundDuration</code>
| <code>handle</code>
| <code>float GetSoundDuration(string ''sound_name'', string ''actor_model_name'')</code>
| null
| Returns float duration of the sound. Actor model name is optional and can be left null.
| Entity which will *speak* the sound. This is not the sound as the actual owner of the sound, see above.
{{todo|Actor model name is likely a leftover from {{hl2|2}}}}
{{warning|Does not work on dedicated servers as they do not have audio libraries built-in to load sounds.}}
|-
|-
| <code>filter_type</code>
| <code>IsDedicatedServer</code>
| <code>int</code>
| <code>bool IsDedicatedServer()</code>
| 0
| Returns true if this server is a dedicated server.
| Specifies what entities can hear this entity. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#EScriptRecipientFilter|Constants.EScriptRecipientFilter]].
|-
|-
| <code>filter_param</code>
| <code>IsModelPrecached</code>
| <code>int</code>
| <code>bool IsModelPrecached(string ''model_name'')</code>
| -1
| Checks if the ''model_name'' is precached.
| Specifies an extra option to the filter. Currently only used by <code>RECIPIENT_FILTER_TEAM</code>, which uses this to specify which team to play to.
|}
|-
|-
| <code>EmitSoundOn</code>
| <code>IsSoundPrecached</code>
| <code>void EmitSoundOn(string ''soundScript'', handle ''entity'')</code>
| <code>bool IsSoundPrecached(string ''sound_name'')</code>
| Play named sound on Entity. Legacy only, use EmitSoundEx.
| Checks if the ''sound_name'' is precached.
|-
|-
| <code>StopSoundOn</code>
| <code>IsPlayerABot</code>
| <code>void StopSoundOn(string ''soundScript'', handle ''entity'')</code>
| <code>bool IsPlayerABot(CTFPlayer ''player'')</code>
| Stop named sound on an entity.
| Is this player/entity a puppet or AI bot. To check if the player is a AI bot (<code>CTFBot</code>) specifically, use <code>IsBotOfType</code> instead.
|-
|-
| <code>EmitSoundOnClient</code>
| <code>IsWeakref</code>
| <code>void EmitSoundOnClient(string ''soundScript'', handle ''player'')</code>
| <code>bool IsWeakref()</code>
| Play named sound only on the client for the specified player. NOTE: This only supports soundscripts. Legacy only, use EmitSoundEx.
|
|-
|-
| <code>EntFire</code>
| <code>LocalTime</code>
| <code>void EntFire(string ''target'', string ''action'', string ''value = null'', float ''delay = 0'', handle ''activator = null'')</code>
| <code>void LocalTime(table ''result'')</code>
| Wrapper for DoEntFire() that sets<code>''activator''</code> to null, but has no<code>''caller''</code>param.
| Fills out a table with the local time (second, minute, hour, day, month, year, dayofweek, dayofyear, daylightsavings). This mirrors the <code>tm</code> structure in C++, see the [https://cplusplus.com/reference/ctime/tm/ reference page] for more information.
{{tip|Use a -1 delay to consistently fire it at the end of the frame. 0 delay might bring inconsistent timing.}}
{{warning|The month will be 1-12 rather than 0-11.}}
|-
|-
| <code>EntFireByHandle</code>
| <code>MakeNamespace</code>
| <code>void EntFireByHandle(handle ''entity'', string ''action'', string ''value'', float ''delay'', handle ''activator'', handle ''caller'')</code>
| <code>MakeNamespace()</code>
| Generate an entity i/o event. First parameter is an entity instance.
|
{{tip|Use a -1 delay to consistently fire it at the end of the frame. 0 delay might bring inconsistent timing.}}
|-
|-
| <code>EntIndexToHScript</code>
| <code>MaxClients</code>
| <code>handle EntIndexToHScript(int ''entIndex'')</code>
| <code>float MaxClients()</code>
| Turn an entity index integer to an HScript representing that entity's script instance.
| Get the current number of max clients set by the maxplayers command.
{{bug|hidetested=1|The return value is mistakenly defined as a float. It is best to use <code>.tointeger()</code> after calling this.}}
|-
|-
| <code>FileToString</code>
| <code>PickupObject</code>
| <code>string FileToString(string ''file'')</code>
| <code>void PickupObject(CTFPlayer ''player'', handle ''entity'')</code>
| Reads a string from file located in the game's ''scriptdata'' folder. Returns the string from the file, null if no file or file is greater than 16384 bytes.
| Object from world is put into the "Held" slot of the player. Warning: it will smoothly interpolate from where it is to the players hand - which is a bit goofy if it is on other side of level.
{{ModernNote|Files packed inside the [[BSP]] cannot be read.}}
{{note|Does nothing in {{tf2|2}} as the code is not implemented.}}
|-
|-
| <code>FindCircularReference</code>
| <code>PlayerInstanceFromIndex</code>
| <code>FindCircularReference()</code>
| <code>CTFPlayer PlayerInstanceFromIndex(int ''index'')</code>
|  
| Get a script handle of a player using the player index.
{{note|The 'fake' [[SourceTV]] player will always be returned as null. If you need to actually retrieve the SourceTV player, use <code>EntIndexToHScript</code>.}}
|-
|-
| <code>FindCircularReferences</code>
| <code>PrecacheEntityFromTable</code>
| <code>FindCircularReferences()</code>
| <code>bool PrecacheEntityFromTable(table ''keyvalues'')</code>
|  
| Precache an entity from [[KeyValues]] in a table. Internally this function creates the entity, fire <code>DispatchSpawn</code> and removes it instantly. Returns false if the table has no ''classname'' key, if the value of ''classname'' is null or empty, or if the entity failed to be created.
{{tip|Can be used  to precache gibs for a model on any entity by using [[tf_generic_bomb]]. Example: <source>PrecacheEntityFromTable({ classname = "tf_generic_bomb", model = MODEL_NAME })</source>}}
|-
|-
| <code>FireGameEvent</code>
| <code>PrecacheModel</code>
| <code>bool FireGameEvent(string, handle)</code>
| <code>int PrecacheModel(string ''model_name'')</code>
| Fire a game event to a listening callback function in script. Parameters are passed in a squirrel table.
| Precache a model (<code>.mdl</code>) or sprite (<code>.vmt</code>) and return model index. The extension must be specified. Returns -1 if null or empty ''model_name'' is passed in. Missing models/sprites will still return a new index.
{{note|Does not precache gibs. See <code>PrecacheEntityFromTable</code> instead.}}
|-
|-
| <code>FireScriptHook</code>
| <code>PrecacheScriptSound</code>
| <code>bool FireScriptHook(string, handle)</code>
| <code>bool PrecacheScriptSound(string ''sound_name'')</code>
| Fire a script hook to a listening callback function in script. Parameters are passed in a squirrel table.
| Precache a soundscript. Returns false if soundscript is missing, or if a null or empty sound name is passed in.
|-
|-
| <code>FireScriptEvent</code>
| <code>PrecacheSound</code>
| <code>void FireScriptEvent(string ''event'', table ''params'')</code>
| <code>bool PrecacheSound(string ''sound_name'')</code>
| Wrapper for <code>__RunEventCallbacks()</code>
| Precache a raw sound. Returns false if a null or empty sound name is passed in.
|-
|-
| <code>ForceEnableUpgrades</code>
| <code>PrintHelp</code>
| <code>void ForceEnableUpgrades(int)</code>
| <code>void PrintHelp()</code>
| Whether to force on MvM-styled upgrades on/off. 0 -> default, 1 -> force off, 2 -> force on
| Equivalent to running <code>script_help</code> command.
|-
|-
| <code>ForceEscortPushLogic</code>
| <code>RandomFloat</code>
| <code>void ForceEscortPushLogic(int)</code>
| <code>float RandomFloat(float ''min'', float ''max'')</code>
| Forces payload pushing logic. 0 -> default, 1 -> force off, 2 -> force on
| Generate a random floating-point number within a range, inclusive.
|-
|-
| <code>FlagsMayBeCapped</code>
| <code>RandomInt</code>
| <code>bool FlagsMayBeCapped()</code>
| <code>int RandomInt(int ''min'', int ''max'')</code>
| May a flag be captured?
| Generate a random integer within a range, inclusive.
|-
|-
| <code>FrameTime</code>
| <code>RegisterFunctionDocumentation</code>
| <code>float FrameTime()</code>
| <code>void RegisterFunctionDocumentation(function ''func'', string ''name'', string ''signature'', string ''description'')</code>
| Get the time spent on the server in the last frame
|
|-
|-
| <code>GameModeUsesCurrency</code>
| <code>RegisterScriptGameEventListener</code>
| <code>bool GameModeUsesCurrency()</code>
| <code>void RegisterScriptGameEventListener(string ''event_name'')</code>
| Does the current gamemode have currency?
| Register as a listener for a game event from script. It's what <code>__CollectGameEventCallbacks()</code> uses to register event callbacks to the C++ code.
{{note|This cannot be used to register non-existent game events.}}
|-
|-
| <code>GameModeUsesMiniBosses</code>
| <code>RegisterScriptHookListener</code>
| <code>bool GameModeUsesMiniBosses()</code>
| <code>void RegisterScriptHookListener(string ''name'')</code>
| Does the current gamemode have minibosses?
| Register as a listener for a script hook from script.
|-
|-
| <code>GameModeUsesUpgrades</code>
| <code>RetrieveNativeSignature</code>
| <code>bool GameModeUsesUpgrades()</code>
| <code>string RetrieveNativeSignature(function ''func'')</code>
| Does the current gamemode have upgrades?
|
|-
|-
| <code>GetClassLimit</code>
| <code>RotateOrientation</code>
| <code>int GetClassLimit(int)</code>
| <code>QAngle RotateOrientation(QAngle ''initial'', QAngle ''rotation'')</code>
| Get class limit for class. See Constants.ETFClass
| Rotate a QAngle by another QAngle.
|-
|-
| <code>GetDeveloperLevel</code>
| <code>RotatePosition</code>
| <code>int GetDeveloperLevel()</code>
| <code>Vector RotatePosition(Vector ''origin'', QAngle ''rotation'', Vector ''input'')</code>
| Gets the level of 'developer'
| Rotate the input Vector around an origin.
{{bug|hidetested=1|This is not calculated correctly and the rotation will always be relative to (0, 0, 0). As a workaround, subtract the origin from the input, call this function and then add the origin back which will perform the expected result.}}
|-
|-
| <code>GetFrameCount</code>
| <code>ScreenFade</code>
| <code>int GetFrameCount()</code>
| <code>void ScreenFade(CTFPlayer ''player'', int ''red'', int ''green'', int ''blue'', int ''alpha'', float ''fade_time'', float ''fade_hold'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#FFADE|FFADE]] ''flags'')</code>
| Returns the engines current frame count
| Start a customisable screenfade. If no player is specified, the fade will apply to all players.
|-
|-
| <code>GetFriction</code>
| <code>ScreenShake</code>
| <code>float GetFriction(handle ''player'')</code>
| <code>void ScreenShake(Vector ''center'', float ''amplitude'', float ''frequency'', float ''duration'', float ''radius'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#SHAKE_COMMAND|SHAKE_COMMAND]] ''command'', bool ''air_shake'')</code>
| Returns the Friction on a player entity, meaningless if not a player
| Start a customisable screenshake. Set ''command'' to 0 to start a shake, or 1 to stop an existing shake. ''air_shake'' determines whether the airborne players should be affected by the shake as well.
|-
|-
| <code>GetFunctionSignature</code>
| <code>ScriptHooksEnabled</code>
| <code>GetFunctionSignature()</code>
| <code>bool ScriptHooksEnabled()</code>
|  
| Returns whether script hooks are currently enabled.
|-
|-
| <code>GetGravityMultiplier</code>
| <code>SendGlobalGameEvent</code>
| <code>float GetGravityMultiplier()</code>
| <code>bool SendGlobalGameEvent(string ''event_name'', table ''params'')</code>
|  
| Sends a real game event to everything. Parameters are passed in a squirrel table.
|-
{{warning|Certain events that are usually clientside only will not work when fired by this function, with an error complaining that "no listeners are registered for this event". However, defining an empty event listener will make it work.}}
| <code>GetListenServerHost</code>
{{warning|Events that upload statistics to Steam servers such as <code>player_escort_score</code> can take as long as 1 millisecond to execute! This can be prevented by temporarily giving the player the <code>FL_FAKECLIENT</code> flag and reverting it afterwards (however be careful not to revert it on actual bots!).
| <code>handle GetListenServerHost()</code>
Example:
| Get the local player on a listen server.
{{ExpandBox|<source lang=js>
|-
local is_bot = player.IsFakeClient()
| <code>GetMannVsMachineAlarmStatus</code>
if (!is_bot) player.AddFlag(Constants.FPlayer.FL_FAKECLIENT)
| <code>bool GetMannVsMachineAlarmStatus()</code>
 
|
SendGlobalGameEvent("player_escort_score",
{
player = player.entindex(),
points = 1
})
 
if (!is_bot) player.RemoveFlag(Constants.FPlayer.FL_FAKECLIENT)
</source>
}}}}
|-
|-
| <code>GetMapName</code>
| <code>SendToConsole</code>
| <code>string GetMapName()</code>
| <code>void SendToConsole(string ''command'')</code>
| Get the name of the map.
| Issues a command to the local client, as if they typed in the command in their console. Does nothing on dedicated servers.
|-
|-
| <code>GetModelIndex</code>
| <code>SendToServerConsole</code>
| <code>int GetModelIndex(string ''filename'')</code>
| <code>void SendToServerConsole(string ''command'')</code>
| Returns the index of the named model.
| Issues a command to the server, as if typed in the console.
{{note|This obeys the behavior of the <code>sv_allow_point_servercommand</code> convar. By default, this command will do nothing unless the server has this command to set to "always"
{{todo|using this on listen servers without allowing point_servercommand is seemingly inconsistent, check <code>IsDedicatedServer()</code> and use <code>SendToConsole</code> instead.}}
}}
|-
|-
| <code>GetOvertimeAllowedForCTF</code>
| <code>SendToConsoleServer</code>
| <code>bool GetOvertimeAllowedForCTF()</code>
| <code>void SendToConsoleServer(string ''command'')</code>
|  
| Copy of SendToServerConsole with another name for compat.
|-
|-
| <code>{{obs}} GetPhysAngularVelocity</code>
| <code>SetFakeClientConVarValue</code>
| <code>Vector GetPhysAngularVelocity(handle ''entity'')</code>
| <code>void SetFakeClientConVarValue(CTFBot ''bot'', string ''cvar'', string ''value'')</code>
| Returns the Angular velocity of the entity.  Deprecated, use the <code>GetPhysAngularVelocity</code> method on the entity instead.
| Sets a USERINFO client ConVar for a fakeclient.
{{tip|This can be used to change the name of a bot by using the <code>name</code> cvar.}}
|-
|-
| <code>{{obs}} GetPhysVelocity</code>
| <code>SetSkyboxTexture</code>
| <code>Vector GetPhysVelocity(handle ''entity'')</code>
| <code>void SetSkyboxTexture(string ''texture'')</code>
| Returns the velocity of the entity. Deprecated, use the <code>GetPhysVelocity</code> method on the entity instead.
| Sets the current skybox texture. The path is relative to "materials/skybox/". Only the main name of a skybox texture is needed, for example "sky_gravel_01".
|-
|-
| <code>GetPlayerFromUserID</code>
| <code>SpawnEntityFromTable</code>
| <code>handle GetPlayerFromUserID(int ''ID'')</code>
| <code>handle SpawnEntityFromTable(string ''name'', table ''keyvalues'')</code>
| Given a user id, return the entity, or null.
| Spawn entity from KeyValues in table - 'name' is entity name, rest are KeyValues for spawn.
{{note|The 'fake' [[SourceTV]] player will always be returned as null.}}
{{note|Multiple keys of the same name can be specified by appending the key with an incremental #x suffix.}}
|-
{{note|<code>parentname</code> is not resolved and therefore will not work. Instead, fire <code>AcceptInput</code> after spawning (with <code>SetParent !activator</code> parameters), or use <code>SpawnEntityGroupFromTable</code>.}}
| <code>GetRoundState</code>
{{tip|If spawning multiple entities at once, use <code>SpawnEntityGroupFromTable</code> as it will be more efficient.}}
| <code>int GetRoundState()</code>
Example:
| Get current round state. See Constants.ERoundState
{{ExpandBox|<source lang=js>
SpawnEntityFromTable("logic_timer", {
targetname = "cool"
RefireTime = 60
"OnTimer#1" : "entity,Trigger,,0,-1"
"OnTimer#2" : "somethingelse,Disable,,0,-1"
})
</source>
}}
{{warning|If using commas inside the parameter field of a output key, it will not be parsed correctly as the comma will be treated as delimiter.
To fix this, an special delimiter also supported by the game can be used named 'ESC'. This cannot be typed on a keyboard normally, and must be copied from another source. The easiest way is to [https://pastebin.com/raw/TaJ7pnVC open this link], and copy + paste the character in a supporting editor such as Notepad++.<br>
Example (the character will not display correctly on this page):<br><code>"OnTrigger#5": "res,RunScriptCode,NetProps.SetPropString(self, `m_iszMvMPopfileName`, `test`),0,-1"</code><br>would instead be changed to<br>
<code>"OnTrigger#5": "res�RunScriptCode�NetProps.SetPropString(self, `m_iszMvMPopfileName`, `test`)�0�-1"</code>}}
{{note|If using a complex model, usually custom models, it might cause stutters to the server when spawning it. To work around this issue instead spawn it with <code>CreateByClassname</code> and set its netprops manually, and don't forget to make sure the model is precached properly too.}}
|-
|-
| <code>GetSoundDuration</code>
| <code>SpawnEntityGroupFromTable</code>
| <code>float GetSoundDuration(string ''soundname'', string ''actormodel'')</code>
| <code>bool SpawnEntityGroupFromTable(table ''groups'')</code>
| Returns float duration of the sound. Takes soundname and optional actormodelname.
| Hierarchically spawn an entity group from a set of spawn tables. This computes a spawn order for entities so that parenting is resolved correctly.
{{warning|Does not work on dedicated servers as they do not have audio libraries built-in to load sounds.}}
The table for this must take the following format. <code>group</code> can be any name, as long as it's unique. Each group can only contain one entity. (The table is formatted like this as otherwise it wouldn't be possible to spawn multiple entities of the same classname). The function always returns true, even if entity spawning fails.
<source lang=js>
{
<group> =
{
<classname> =
{
// key - values
}
},
// ...
}
</source>
Example usage:
{{ExpandBox|<source lang=js>
SpawnEntityGroupFromTable(
{
a =
{
info_particle_system =
{
origin = GetListenServerHost().GetOrigin(),
parentname = "mytarget",
effect_name = "soldierbuff_blue_soldier",
start_active = true
}
},
b =
{
info_particle_system =
{
origin = GetListenServerHost().GetOrigin(),
parentname = "mytarget",
effect_name = "soldierbuff_red_soldier",
start_active = true
}
},
})
</source>
}}
{{Note|You will need to hijack an unused string netprop and set the bounding box data for brush entities there, then run a script on the entity to parse it. Example: {{ExpandBox|
 
Make a script file named "make_brush.nut" that contains the following:
<source lang=js>
function OnPostSpawn()
{
local buf = split(NetProps.GetPropString(self, "m_iszResponseContext"), " ")
self.SetSize(Vector(buf[0], buf[1], buf[2]), Vector(buf[3], buf[4], buf[5]))
self.SetSolid(2)
}
</source>
 
Now you can set the min/max bounding box values for a brush ent directly in the ent key/values like so:
<source lang=js>
SpawnEntityGroupFromTable({
[0] = {
func_rotating =
{
message = "hl1/ambience/labdrone2.wav",
responsecontext = "-1 -1 -1 1 1 1",
vscripts = "make_brush",
volume = 8,
targetname = "crystal_spin",
spawnflags = 65,
solidbsp = 0,
rendermode = 10,
rendercolor = "255 255 255",
renderamt = 255,
maxspeed = 48,
fanfriction = 20,
angles = QAngle(),
origin = Vector(),
}
},
[1] = {
trigger_multiple =
{
targetname = "trigger1",
responsecontext = "-250 -250 -250 250 250 250",
vscripts = "make_brush",
parentname = "crystal_spin",
spawnflags = 1,
"OnStartTouchAll#1": "!activator�RunScriptCode�ClientPrint(self, 3, `I am in trigger1`)�0�-1",
}
},
[2] = {
prop_dynamic =
{
targetname = "crystal",
solid = 6,
renderfx = 15,
rendercolor = "255 255 255",
renderamt = 255,
physdamagescale = 1.0,
parentname = "crystal_spin",
modelscale = 1.3,
model = "models/props_moonbase/moon_gravel_crystal_blue.mdl",
MinAnimTime = 5,
MaxAnimTime = 10,
fadescale = 1.0,
fademindist = -1.0,
origin = Vector(),
angles = QAngle(45, 0, 0)
}
},
})
</source>
}}}}
{{tip|If a list of entity handles created from this function is needed, there is two workarounds:
*1 - Assign a <code>vscripts</code> file that appends <code>this</code> to a global array.
*2 - Use a <code>point_script_template</code>, see the [[#CPointScriptTemplate|spawn hook example ↑]].}}
|-
|-
| <code>GetStopWatchState</code>
| <code>StringToFile</code>
| <code>int GetStopWatchState()</code>
| <code>void StringToFile(string ''file'', string ''string'')</code>
| Get the current stopwatch state. See Constants.EStopwatchState
| Stores a string as a file, located in the game's ''scriptdata'' folder.
{{warning|Since this writes to the disk, the performance will vary depending on the hardware (i.e. HDD or SSD). This function should only be called at checkpoints such as round restart or before level change, and not during gameplay to prevent hitches.}}
{{warning|This writes files in text mode, therefore binary files will not be written correctly. As another consequence, if writing multi-line strings directly, this may cause issues due to Window's encoding new lines as \r\n, but Mac/Linux encodes as \n. This can be fixed by setting EOL (end-of-line) encoding to ''Unix'' or ''CR'' in your text editor.}}
{{bug|hidetested=1|A single NULL byte will always be appended to the end of the file.}}
|-
|-
| <code>GetWinningTeam</code>
| <code>Time</code>
| <code>int GetWinningTeam()</code>
| <code>float Time()</code>
| Who won!
| Get the current time since map load in seconds. The time resets on map change.
 
The time may be different compared to the global time if running in the context of a player, such as a player think function or damage callback caused by a player. This adjustment is for [[lag compensation]] and may be up to 1 second (<code>sv_maxunlag</code>). Therefore use <code>GetFrameCount</code> if you need to compare if events happened in the same tick.
|-
|-
| <code>HaveStopWatchWinner</code>
| <code>TraceLine</code>
| <code>bool HaveStopWatchWinner()</code>
| <code>float TraceLine(Vector ''start'', Vector ''end'', handle ''ignore'')</code>
|  
| Trace a ray. Return fraction along line that hits world or models. Optionally, ignore the specified entity.
{{tip|Specify the same start and end point to check whether a point is inside solid geometry/out of bounds.}}
|-
|-
| <code>InMatchStartCountdown</code>
| <code>TraceLinePlayersIncluded</code>
| <code>bool InMatchStartCountdown()</code>
| <code>float TraceLinePlayersIncluded(Vector ''start'', Vector ''end'', handle ''ignore'')</code>
| Are we in the pre-match/setup state?
| Different version of <code>TraceLine</code> that also hits players and NPCs.
|-
|-
| <code>InOvertime</code>
| <code>[[Team Fortress 2/Scripting/Script Functions/TraceLineEx|TraceLineEx]]</code>
| <code>bool InOvertime()</code>
| <code>bool TraceLineEx(table ''params'')</code>
| Currently in overtime?
| Extended version of <code>TraceLine</code>. See the [[Team Fortress 2/Scripting/Script Functions/TraceLineEx|main page]] for more details.
{{warning|Setting any input parameters which expect an instance (vector or entity) to a primitive type like integer will lead to a server crash. Setting it to <code>null</code> however will not cause such issue.}}
|-
|-
| <code>IsAttackDefenseMode</code>
| <code>[[Team Fortress 2/Scripting/Script Functions/TraceHull|TraceHull]]</code>
| <code>bool IsAttackDefenseMode()</code>
| <code>bool TraceHull(table ''params'')</code>
|  
| Trace a [[Bounding_box|box (AABB)]]. See the [[Team Fortress 2/Scripting/Script Functions/TraceHull|main page]] for more details.
{{warning|See above.}}
|-
|-
| <code>IsBirthday</code>
| <code>UniqueString</code>
| <code>bool IsBirthday()</code>
| <code>string UniqueString(string ''suffix'' = null)</code>
| Are we in birthday mode?
| Generate a string guaranteed to be unique across the life of the script VM, with an optional suffix. Useful for adding data to tables when not sure what keys are already in use in that table.
The format of the string is <code>_%x%llx_%s</code>, with arguments as follows: random number between 0 and 4095, an incrementing 64-bit counter, and ''suffix''.
|-
|-
| <code>IsCompetitiveMode</code>
| <code>DoUniqueString</code>
| <code>bool IsCompetitiveMode()</code>
| <code>string DoUniqueString(string ''suffix'')</code>
| Playing competitive?
| Internal function called by <code>UniqueString</code>.
|-
|-
| <code>IsDedicatedServer</code>
| <code>VSquirrel_OnCreateScope</code>
| <code>bool IsDedicatedServer()</code>
| <code>table VSquirrel_OnCreateScope(any ''value'', table ''scope'')</code>
| Returns true if this server is a dedicated server.
| Creates a new scope with the name of value in the submitted table (includes unique params).
|-
|-
| <code>IsDefaultGameMode</code>
| <code>VSquirrel_OnReleaseScope</code>
| <code>bool IsDefaultGameMode()</code>
| <code>void VSquirrel_OnReleaseScope(table ''created_scope'')</code>
| The absence of arena, mvm, tournament mode, etc
| Removes a scope created via VSquirrel_OnCreateScope.
|-
|-
| <code>IsHolidayActive</code>
| <code>__CollectEventCallbacks</code>
| <code>bool IsHolidayActive(int ''holiday'')</code>
| <code>void __CollectEventCallbacks(scope, prefix, global_table_name, reg_func)</code>
| Is the given holiday active? See Constants.EHoliday
| Overloaded function. Its only used for this: <code>__CollectEventCallbacks(scope, "OnGameEvent_", "GameEventCallbacks", ::RegisterScriptGameEventListener)</code>.
|-
|-
| <code>IsHolidayMap</code>
| <code>__CollectGameEventCallbacks</code>
| <code>bool IsHolidayMap(int ''holiday'')</code>
| <code>void __CollectGameEventCallbacks(table ''scope'')</code>
| Playing a holiday map? See Constants.EHoliday
| Wrapper that registers callbacks for both [[#Hooks|OnGameEvent_''x'' ↑]] and <code>OnScriptEvent_</code> functions. Done using the <code>__CollectEventCallbacks</code> function.
|-
|-
| <code>IsInArenaMode</code>
| <code>__ReplaceClosures</code>
| <code>bool IsInArenaMode()</code>
| <code>void __ReplaceClosures(script, scope)</code>
| Playing arena mode?
|
|-
|-
| <code>IsInKothMode</code>
| <code>__RunEventCallbacks</code>
| <code>bool IsInKothMode()</code>
| <code>void __RunEventCallbacks(event, params, prefix, global_table_name, bool warn_if_missing)</code>
| Playing king of the hill mode?
| Call all functions in the callback array for the given game event.
|-
|-
| <code>IsInMedievalMode</code>
| <code>__RunGameEventCallbacks</code>
| <code>bool IsInMedievalMode()</code>
| <code>void __RunGameEventCallbacks(event, params)</code>
| Playing medieval mode?
| Wrapper for <code>__RunEventCallbacks()</code>.
|-
|-
| <code>IsInWaitingForPlayers</code>
| <code>__RunScriptHookCallbacks</code>
| <code>bool IsInWaitingForPlayers()</code>
| <code>void __RunScriptHookCallbacks(event, param)</code>
| Are we waiting for some stragglers?
|
|}
 
=== Team Fortress 2 ===
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
|-
| <code>IsMannVsMachineMode</code>
| <code>AllowThirdPersonCamera</code>
| <code>bool IsMannVsMachineMode()</code>
| <code>bool AllowThirdPersonCamera()</code>
| Playing MvM? Beep boop
|
|-
|-
| <code>IsMannVsMachineRespecEnabled</code>
| <code>ArePlayersInHell</code>
| <code>bool IsMannVsMachineRespecEnabled()</code>
| <code>bool ArePlayersInHell()</code>
| Are players allowed to refund their upgrades?
|
|-
|-
| <code>IsMatchTypeCasual</code>
| <code>FlagsMayBeCapped</code>
| <code>bool IsMatchTypeCasual()</code>
| <code>bool FlagsMayBeCapped()</code>
| Playing casual?
| May a flag be captured?
|-
|-
| <code>IsMatchTypeCompetitive</code>
| <code>ForceEnableUpgrades</code>
| <code>bool IsMatchTypeCompetitive()</code>
| <code>void ForceEnableUpgrades(int ''state'')</code>
| Playing competitive?
| Whether to force on MvM-styled upgrades on/off. 0 -> default, 1 -> force off, 2 -> force on.
|-
|-
| <code>IsModelPrecached</code>
| <code>ForceEscortPushLogic</code>
| <code>bool IsModelPrecached(string ''modelname'')</code>
| <code>void ForceEscortPushLogic(int ''state'')</code>
| Checks if the modelname is precached.
| Forces payload pushing logic. 0 -> default, 1 -> force off, 2 -> force on.
|-
|-
| <code>IsSoundPrecached</code>
| <code>GameModeUsesCurrency</code>
| <code>bool IsSoundPrecached(string ''soundname'')</code>
| <code>bool GameModeUsesCurrency()</code>
| Checks if the soundname is precached.
| Does the current gamemode have currency?
|-
|-
| <code>IsPasstimeMode</code>
| <code>GameModeUsesMiniBosses</code>
| <code>bool IsPasstimeMode()</code>
| <code>bool GameModeUsesMiniBosses()</code>
| No ball games.
| Does the current gamemode have minibosses?
|-
|-
| <code>IsPlayerABot</code>
| <code>GameModeUsesUpgrades</code>
| <code>bool IsPlayerABot(handle ''player'')</code>
| <code>bool GameModeUsesUpgrades()</code>
| Is this player/entity a bot.
| Does the current gamemode have upgrades?
|-
|-
| <code>IsPowerupMode</code>
| <code>GetClassLimit</code>
| <code>bool IsPowerupMode()</code>
| <code>int GetClassLimit([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFClass|ETFClass]] ''class'')</code>
| Playing powerup mode? Not compatible with MvM
| Get class limit for class.
|-
|-
| <code>IsPVEModeActive</code>
| <code>GetGravityMultiplier</code>
| <code>bool IsPVEModeActive()</code>
| <code>float GetGravityMultiplier()</code>
|  
|
|-
|-
| <code>IsQuickBuildTime</code>
| <code>GetMannVsMachineAlarmStatus</code>
| <code>bool IsQuickBuildTime()</code>
| <code>bool GetMannVsMachineAlarmStatus()</code>
| If an engie places a building, will it immediately upgrade? Eg. MvM pre-round etc.
|
|-
|-
| <code>IsTruceActive</code>
| <code>GetOvertimeAllowedForCTF</code>
| <code>bool IsTruceActive()</code>
| <code>bool GetOvertimeAllowedForCTF()</code>
|  
|
|-
|-
| <code>IsUsingGrapplingHook</code>
| <code>GetRoundState</code>
| <code>bool IsUsingGrapplingHook()</code>
| <code>int GetRoundState()</code>
|  
| Get current round state. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ERoundState|Constants.ERoundState]].
|-
|-
| <code>IsUsingSpells</code>
| <code>GetStopWatchState</code>
| <code>bool IsUsingSpells()</code>
| <code>int GetStopWatchState()</code>
|  
| Get the current stopwatch state. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#EStopwatchState|Constants.EStopwatchState]].
|-
|-
| <code>IsWeakref</code>
| <code>GetWinningTeam</code>
| <code>bool IsWeakref()</code>
| <code>int GetWinningTeam()</code>
|  
| Who won!
|-
|-
| <code>LocalTime</code>
| <code>HaveStopWatchWinner</code>
| <code>void LocalTime(table)</code>
| <code>bool HaveStopWatchWinner()</code>
| Fills out a table with the local time (second, minute, hour, day, month, year, dayofweek, dayofyear, daylightsavings)
|
|-
|-
| <code>MakeNamespace</code>
| <code>InMatchStartCountdown</code>
| <code>MakeNamespace()</code>
| <code>bool InMatchStartCountdown()</code>
|  
| Are we in the pre-match/setup state?
|-
|-
| <code>MapHasMatchSummaryStage</code>
| <code>InOvertime</code>
| <code>bool MapHasMatchSummaryStage()</code>
| <code>bool InOvertime()</code>
|  
| Currently in overtime?
|-
|-
| <code>MatchmakingShouldUseStopwatchMode</code>
| <code>IsAttackDefenseMode</code>
| <code>bool MatchmakingShouldUseStopwatchMode()</code>
| <code>bool IsAttackDefenseMode()</code>
|  
|
|-
|-
| <code>MaxClients</code>
| <code>IsBirthday</code>
| <code>float MaxClients()</code>
| <code>bool IsBirthday()</code>
| Get the current number of max clients set by the maxplayers command.
| Are we in birthday mode?
{{bug|The return value is mistakenly defined as a float. It is best to use <code>.tointeger()</code> after calling this.}}
|-
|-
| <code>PickupObject</code>
| <code>IsCompetitiveMode</code>
| <code>void PickupObject(handle ''player'', handle ''entity'')</code>
| <code>bool IsCompetitiveMode()</code>
| Object from world is put into the "Held" slot of the player. Warning: it will smoothly interpolate from where it is to the players hand - which is a bit goofy if it is on other side of level.
| Playing competitive?
|-
|-
| <code>PlayerInstanceFromIndex</code>
| <code>IsDefaultGameMode</code>
| <code>CBasePlayer PlayerInstanceFromIndex(int ''index'')</code>
| <code>bool IsDefaultGameMode()</code>
| Get a script handle of a player using the player index.
| The absence of arena, mvm, tournament mode, etc.
{{note|The 'fake' [[SourceTV]] player will always be returned as null.}}
|-
|-
| <code>PlayerReadyStatus_ArePlayersOnTeamReady</code>
| <code>IsHolidayActive</code>
| <code>bool PlayerReadyStatus_ArePlayersOnTeamReady(int)</code>
| <code>bool IsHolidayActive([[Team_Fortress_2/Scripting/Script_Functions/Constants#EHoliday|EHoliday]] ''holiday'')</code>
|  
| Is the given holiday active?
|-
|-
| <code>PlayerReadyStatus_HaveMinPlayersToEnable</code>
| <code>IsHolidayMap</code>
| <code>bool PlayerReadyStatus_HaveMinPlayersToEnable()</code>
| <code>bool IsHolidayMap([[Team_Fortress_2/Scripting/Script_Functions/Constants#EHoliday|EHoliday]] ''holiday'')</code>
|  
| Playing a holiday map?
|-
|-
| <code>PlayerReadyStatus_ResetState</code>
| <code>IsInArenaMode</code>
| <code>void PlayerReadyStatus_ResetState()</code>
| <code>bool IsInArenaMode()</code>
|  
| Playing arena mode?
|-
|-
| <code>PlayersAreOnMatchSummaryStage</code>
| <code>IsInKothMode</code>
| <code>bool PlayersAreOnMatchSummaryStage()</code>
| <code>bool IsInKothMode()</code>
|  
| Playing king of the hill mode?
|-
|-
| <code>PointsMayBeCaptured</code>
| <code>IsInMedievalMode</code>
| <code>bool PointsMayBeCaptured()</code>
| <code>bool IsInMedievalMode()</code>
| Are points able to be captured?
| Playing medieval mode?
|-
|-
| <code>PrecacheEntityFromTable</code>
| <code>IsInWaitingForPlayers</code>
| <code>bool PrecacheEntityFromTable(table ''keyvalues'')</code>
| <code>bool IsInWaitingForPlayers()</code>
| Precache an entity from [[KeyValues]] in a table. Internally this function creates the entity, fire <code>DispatchSpawn</code> and removes it instantly.
| Are we waiting for some stragglers?
|-
|-
| <code>PrecacheModel</code>
| <code>IsMannVsMachineMode</code>
| <code>int PrecacheModel(string ''filename'')</code>
| <code>bool IsMannVsMachineMode()</code>
| Precache a model and return index of the model.
| Playing MvM? Beep boop.
|-
|-
| <code>PrecacheScriptSound</code>
| <code>IsMannVsMachineRespecEnabled</code>
| <code>bool PrecacheScriptSound(string ''soundName'')</code>
| <code>bool IsMannVsMachineRespecEnabled()</code>
| Precache a soundscript.
| Are players allowed to refund their upgrades?
|-
|-
| <code>PrecacheSound</code>
| <code>IsMatchTypeCasual</code>
| <code>bool PrecacheSound(string ''soundName'')</code>
| <code>bool IsMatchTypeCasual()</code>
| Precache a raw sound.
| Playing casual?
|-
|-
| <code>PrintHelp</code>
| <code>IsMatchTypeCompetitive</code>
| <code>PrintHelp()</code>
| <code>bool IsMatchTypeCompetitive()</code>
|  
| Playing competitive?
|-
|-
| <code>RandomFloat</code>
| <code>IsPasstimeMode</code>
| <code>float RandomFloat(float ''min'', float ''max'')</code>
| <code>bool IsPasstimeMode()</code>
| Generate a random floating-point number within a range, inclusive.
| No ball games.
|-
|-
| <code>RandomInt</code>
| <code>IsPowerupMode</code>
| <code>int RandomInt(int ''min'', int ''max'')</code>
| <code>bool IsPowerupMode()</code>
| Generate a random integer within a range, inclusive.
| Playing powerup mode? Not compatible with MvM.
|-
|-
| <code>RegisterFunctionDocumentation</code>
| <code>IsPVEModeActive</code>
| <code>void RegisterFunctionDocumentation(unknown ''func'', string ''name'', string ''signature'', string ''description'')</code>
| <code>bool IsPVEModeActive()</code>
|  
|
|-
|-
| <code>RegisterScriptGameEventListener</code>
| <code>IsQuickBuildTime</code>
| <code>void RegisterScriptGameEventListener(string ''eventName'')</code>
| <code>bool IsQuickBuildTime()</code>
| Register as a listener for a game event from script. It's what <code>__CollectGameEventCallbacks()</code> uses to register event callbacks to the C++ code.
| If an engie places a building, will it immediately upgrade? Eg. MvM pre-round etc.
|-
|-
| <code>RegisterScriptHookListener</code>
| <code>IsTruceActive</code>
| <code>void RegisterScriptHookListener(string)</code>
| <code>bool IsTruceActive()</code>
| Register as a listener for a script hook from script.
|
|-
|-
| <code>RetrieveNativeSignature</code>
| <code>IsUsingGrapplingHook</code>
| <code>RetrieveNativeSignature()</code>
| <code>bool IsUsingGrapplingHook()</code>
|  
|
|-
|-
| <code>RotateOrientation</code>
| <code>IsUsingSpells</code>
| <code>QAngle RotateOrientation(QAngle, QAngle)</code>
| <code>bool IsUsingSpells()</code>
| Rotate a QAngle by another QAngle.
|
|-
|-
| <code>RotatePosition</code>
| <code>MapHasMatchSummaryStage</code>
| <code>Vector RotatePosition(Vector ''origin'', QAngle ''rotation'', Vector ''input'')</code>
| <code>bool MapHasMatchSummaryStage()</code>
| Rotate the input Vector around an origin.
|
{{bug|This is not calculated correctly and the rotation will always be relative to (0, 0, 0). As a workaround, subtract the origin from the input, call this function and then add the origin back which will perform the expected result.}}
|-
|-
| <code>ScreenFade</code>
| <code>MatchmakingShouldUseStopwatchMode</code>
| <code>void ScreenFade(handle ''player'', int ''red'', int ''green'', int ''blue'', int ''alpha'', float ''fadeTime'', float ''fadeHold'', int ''flags'')</code>
| <code>bool MatchmakingShouldUseStopwatchMode()</code>
| Start a customisable screenfade. If no player is specified, the fade will apply to all players.
|
|-
|-
| <code>ScreenShake</code>
| <code>PlayerReadyStatus_ArePlayersOnTeamReady</code>
| <code>void ScreenShake(Vector ''vecCenter'', float ''flAmplitude'', float ''flFrequency'', float ''flDuration'', float ''flRadius'', int ''eCommand'', bool ''bAirShake'')</code>
| <code>bool PlayerReadyStatus_ArePlayersOnTeamReady([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'')</code>
| Start a customisable screenshake; eCommand( SHAKE_START = 0, SHAKE_STOP = 1 ).
|
|-
|-
| <code>ScriptHooksEnabled</code>
| <code>PlayerReadyStatus_HaveMinPlayersToEnable</code>
| <code>bool ScriptHooksEnabled()</code>
| <code>bool PlayerReadyStatus_HaveMinPlayersToEnable()</code>
| Returns whether script hooks are currently enabled.
|
|-
|-
| <code>SendGlobalGameEvent</code>
| <code>PlayerReadyStatus_ResetState</code>
| <code>bool SendGlobalGameEvent(string, handle)</code>
| <code>void PlayerReadyStatus_ResetState()</code>
| Sends a real game event to everything. Parameters are passed in a squirrel table.
|
|-
|-
| <code>SendToConsole</code>
| <code>PlayersAreOnMatchSummaryStage</code>
| <code>void SendToConsole(string ''command'')</code>
| <code>bool PlayersAreOnMatchSummaryStage()</code>
| Issues a command to the local client, as if they typed in the command in their console. Does nothing on dedicated servers.
|
|-
|-
| <code>SendToServerConsole</code>
| <code>PointsMayBeCaptured</code>
| <code>void SendToServerConsole(string ''command'')</code>
| <code>bool PointsMayBeCaptured()</code>
| Issues a command to the server, as if typed in the console.
| Are points able to be captured?
{{ModernNote|This obeys the behavior of the <code>sv_allow_point_servercommand</code> convar. By default, this command will do nothing unless the server has this command to set to "always"}}
|-
|-
| <code>SendToConsoleServer</code>
| <code>SetGravityMultiplier</code>
| <code>void SendToConsoleServer(string ''command'')</code>
| Copy of SendToServerConsole with another name for compat.
|-
| <code>SetFakeClientConVarValue</code>
| <code>void SetFakeClientConVarValue(handle ''bot'', string ''cvar'', string ''value'')</code>
| Sets a USERINFO client ConVar for a fakeclient.
{{tip|This can be used to change the name of a bot by using the <code>name</code> cvar.}}
|-
| <code>SetGravityMultiplier</code>
| <code>void SetGravityMultiplier(float ''multiplier'')</code>
| <code>void SetGravityMultiplier(float ''multiplier'')</code>
|  
|
|-
|-
| <code>SetMannVsMachineAlarmStatus</code>
| <code>SetMannVsMachineAlarmStatus</code>
| <code>void SetMannVsMachineAlarmStatus(bool ''status'')</code>
| <code>void SetMannVsMachineAlarmStatus(bool ''status'')</code>
|  
|
|-
|-
| <code>SetOvertimeAllowedForCTF</code>
| <code>SetOvertimeAllowedForCTF</code>
| <code>void SetOvertimeAllowedForCTF(bool ''state'')</code>
| <code>void SetOvertimeAllowedForCTF(bool ''state'')</code>
|  
|
|-
|-
| <code>SetPlayersInHell</code>
| <code>SetPlayersInHell</code>
| <code>void SetPlayersInHell(bool ''state'')</code>
| <code>void SetPlayersInHell(bool ''state'')</code>
|  
|
|-
| <code>SetSkyboxTexture</code>
| <code>void SetSkyboxTexture(string)</code>
| Sets the current skybox texture
|-
|-
| <code>SetUsingSpells</code>
| <code>SetUsingSpells</code>
| <code>void SetUsingSpells(bool ''state'')</code>
| <code>void SetUsingSpells(bool ''state'')</code>
|  
|
|-
|-
| <code>SpawnEntityFromTable</code>
| <code>UsePlayerReadyStatusMode</code>
| <code>handle SpawnEntityFromTable(string ''name'', handle ''keyvalues'')</code>
| <code>bool UsePlayerReadyStatusMode()</code>
| Spawn entity from KeyValues in table - 'name' is entity name, rest are KeyValues for spawn.
|
{{note|Multiple keys of the same name can be specified by appending the key with an incremental #x suffix.}}
|}
Example:
 
{{ExpandBox|<source lang=js>
=== Printing and Drawing ===
SpawnEntityFromTable("logic_timer", {
Functions for printing out messages or drawing elements in the world, mostly for debugging reasons.
    targetname = "cool"
{{warning|Any function with the <code>Debug</code> prefix requires the cvar <code>developer</code> be enabled and the game unpaused.<br>They also do not appear in multiplayer, only on a local server.}}
    RefireTime = 60
 
    "OnTimer#1" = "entity,Trigger,,0,-1"
{| class="standard-table" style="width:100%"
    "OnTimer#2" = "somethingelse,Disable,,0,-1"
|- style="position:sticky; z-index:10; top:0"
})
! Function
</source>
! Signature
}}
! Description
{{warning|If using commas inside the parameter field of a output key, it will not be parsed correctly as the comma will be treated as delimiter.
To fix this, an special delimiter also supported by the game can be used named 'ESC'. This cannot be typed on a keyboard normally, and must be copied from another source. The easiest way is to [https://cdn.discordapp.com/attachments/434089157875466242/1118946042591838328/esc.txt download the following text file], and copy + paste the character in a supporting editor such as Notepad++.<br>
Example (the character will not display correctly on this page):<br><code>"OnTrigger#5": "res,RunScriptCode,NetProps.SetPropString(self, `m_iszMvMPopfileName`, `test`),0,-1"</code><br>would instead be changed to<br>
<code>"OnTrigger#5": "res�RunScriptCode�NetProps.SetPropString(self, `m_iszMvMPopfileName`, `test`)�0�-1"</code>}}
|-
|-
| <code>SpawnEntityGroupFromTable</code>
| <code>ClientPrint</code>
| <code>bool SpawnEntityGroupFromTable(handle ''entityGroup'')</code>
| <code>void ClientPrint(CTFPlayer ''player'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#EHudNotify|EHudNotify]] ''destination'', string ''message'')</code>
| Hierarchically spawn an entity group from a set of spawn tables. See [[L4D2_EMS/Appendix:_Spawning]].
| Print a client message. If you pass null instead of a valid player, the message will be sent to all clients.
When printing to chat (''HUD_PRINTTALK''), the color of the text can be changed with certain hex codes:
* <code>\x01</code> - Default chat color
* <code>\x03</code> - Lime
* <code>\x04</code> - Green
* <code>\x05</code> - Olive
* <code>\x06</code> - Black
* <code>\x07</code> - custom color in hexadecimal RRGGBB format. Example: <code>\x07FF3F3F</code>
* <code>\x08</code> - custom color in hexadecimal RRGGBBAA format (i.e. with transparency). Example: <code>\x08FF3F3FCC</code>
Chat messages can contain multiple of these codes. If using color sequences, there MUST be a color sequence at the beginning of the string, or color codes won't work!.
{{warning|{{hammer}} Will not accept these escape sequences.  As a result, you cannot print colored text with a simple RunScriptCode input.
{{workaround|See the [[Source_SDK_Base_2013/Scripting/VScript_Examples#Printing_colored_text_from_Hammer_I/O|VScript Examples]] page for a workaround that replaces a normal character with <code>\x07</code> at run-time.}}
}}
{{tip|Standard chat colors:
* Default: <code>FBECCB</code>
* RED: <code>FF3F3F</code>
* BLUE: <code>99CCFF</code>
* Unassigned/spectator: <code>CCCCCC</code>}}
|-
|-
| <code>StringToFile</code>
| <code>DebugDrawBox</code>
| <code>void StringToFile(string ''file'', string ''string'')</code>
| <code>void DebugDrawBox(Vector ''origin'', Vector ''min'', Vector ''max'', int ''r'', int ''g'', int ''b'', int ''alpha'', float ''duration'')</code>
| Stores a string as a file, located in the game's ''scriptdata'' folder.
| Draw a debug overlay box.
|-
|-
| <code>Time</code>
| <code>DebugDrawBoxAngles</code>
| <code>float Time()</code>
| <code>void DebugDrawBoxAngles(Vector ''origin'', Vector ''min'', Vector ''max'', QAngle ''direction'', Vector ''rgb'', int ''alpha'', float ''duration'')</code>
| Get the current server time
| Draw a debug oriented box.
|-
|-
| <code>TraceLine</code>
| <code>DebugDrawBoxDirection</code>
| <code>float TraceLine(Vector, Vector, handle)</code>
| <code>void DebugDrawBoxDirection(Vector ''center'', Vector ''min'', Vector ''max'', Vector ''forward'', Vector ''rgb'', float ''alpha'', float ''duration'')</code>
| given 2 points & ent to ignore, return fraction along line that hits world or models
| Draw a debug forward box.
|-
|-
| <code>[[Left 4 Dead 2/Script Functions/TraceLine| TraceLineEx]]</code>
| <code>DebugDrawCircle</code>
| <code>bool TraceLineEx(table ''traceTable'')</code>
| <code>void DebugDrawCircle(Vector ''center'', Vector ''rgb'', float ''alpha'', float ''radius'', bool ''ztest'', float ''duration'')</code>
| Input Table: start, end, mask (optional, default is <code>MASK_VISIBLE_AND_NPCS</code>), ignore (optional, default is null)<br>Output Table: pos, fraction, hit, enthit, allsolid, startpos, endpos, startsolid, plane_normal, plane_dist, surface_name, surface_flags, surface_props<br>
| Draw a debug circle.
Returns false if <code>start</code> or <code>end</code> is not specified.
{{ModernWarning|<code>allsolid</code>, <code>enthit</code> and <code>startsolid</code> output parameters may not exist depending on the inputs and results of the trace. Check if they exist first before using.}}
|-
|-
| <code>TraceLinePlayersIncluded</code>
| <code>DebugDrawClear</code>
| <code>float TraceLinePlayersIncluded(Vector, Vector, handle)</code>
| <code>void DebugDrawClear()</code>
| given 2 points & ent to ignore, return fraction along line that hits world, models, players or npcs
| Try to clear all the debug overlay info.
|-
|-
| <code>TraceHull</code>
| <code>DebugDrawLine</code>
| <code>bool TraceHull(table ''traceTable'')</code>
| <code>void DebugDrawLine(Vector ''start'', Vector ''end'', int ''red'', int ''green'', int ''blue', bool ''z_test'', float ''time'')</code>
| Input Table: start, end, hullmin, hullmax, mask (optional, default is <code>MASK_VISIBLE_AND_NPCS</code>), ignore (optional, default is null)<br> Output Table: pos, fraction, hit, enthit, allsolid, startpos, endpos, startsolid, plane_normal, plane_dist, surface_name, surface_flags, surface_props
| Draw a debug overlay line.
Returns false if <code>start</code>, <code>end</code>, <code>hullmin</code> or <code>hullmax</code> is not specified.
{{ModernWarning|<code>allsolid</code>, <code>enthit</code> and <code>startsolid</code> output parameters may not exist depending on the inputs and results of the trace. Check if they exist first before using.}}
|-
|-
| <code>UniqueString</code>
| <code>DebugDrawLine_vCol</code>
| <code>string UniqueString(string ''input'')</code>
| <code>void DebugDrawLine_vCol(Vector ''start'', Vector ''end'', Vector ''rgb'', bool ''ztest'', float ''duration'')</code>
| Generate a string guaranteed to be unique across the life of the script VM, with an optional root string. Useful for adding data to tables when not sure what keys are already in use in that table.
| Draw a debug line using color vec.
|-
|-
| <code>DoUniqueString</code>
| <code>DebugDrawScreenTextLine</code>
| <code>string DoUniqueString(string ''input'')</code>
| <code>void DebugDrawScreenTextLine(float ''x'', float ''y'', int ''line_offset'', string ''text'', int ''r'', int ''g'', int ''b'', int ''a'', float ''duration'')</code>
| Unknown; presumably an internal function called by UniqueString, so call that instead.
| Draw text with a line offset.
|-
|-
| <code>UsePlayerReadyStatusMode</code>
| <code>DebugDrawText</code>
| <code>bool UsePlayerReadyStatusMode()</code>
| <code>void DebugDrawText(Vector ''origin'', string ''text'', bool ''use_view_check'', float ''duration'')</code>
|  
| Draw text on the screen, starting on the position of ''origin''.
|-
|-
| <code>VSquirrel_OnCreateScope</code>
| <code>__DumpScope</code>
| <code>table VSquirrel_OnCreateScope(any ''value'', table ''scope'')</code>
| <code>void __DumpScope(int ''indentation'', table ''scope'')</code>
| Creates a new scope with the name of value in the submitted table (includes unique params).
| Dumps a scope's contents and expands all tables and arrays; this is what the <code>ent_script_dump</code> command uses.
{{tip|You can use this to print tables/arrays.}}
{{Expand|title=Example|
Using this code:
<source lang=js>
local test_table =
{
integer = 20,
string = "hello",
array = [1, 2, 3]
}
 
printl("{")
__DumpScope(1, test_table)
printl("}")
</source>
 
Will print the following in console:
<source lang=js>
{
  string = "hello"
  array(ARRAY)
  [
      0 = 1
      1 = 2
      2 = 3
  ]
  integer = 20
}
</source>
}}
{{Note|The output will be unordered and/or incorrectly indented with multithreading enabled. Set <code>mat_queue_mode</code> to 0 before using this for the expected output.  This applies to all printing and drawing functions, but is most noticeable here}}
|-
|-
| <code>VSquirrel_OnReleaseScope</code>
| <code>DumpObject</code>
| <code>void VSquirrel_OnReleaseScope(table ''createdScope'')</code>
| <code>void DumpObject(handle ''object'')</code>
| Removes a scope created via VSquirrel_OnCreateScope.
| Dumps information about a class or instance.
|-
|-
| <code>__CollectEventCallbacks</code>
| <code>Msg</code>
| <code>void __CollectEventCallbacks(scope, prefix, globalTableName, regFunc)</code>
| <code>void Msg(string ''message'')</code>
| Overloaded function. Its only used for this: <code>__CollectEventCallbacks(scope, "OnGameEvent_", "GameEventCallbacks", ::RegisterScriptGameEventListener)</code>
| Prints message to console without any line feed after.
|-
|-
| <code>__CollectGameEventCallbacks</code>
| <code>printf</code>
| <code>void __CollectGameEventCallbacks(scope)</code>
| <code>void printf(string ''format'', args...)</code>
| Wrapper that registers callbacks for both [[#OnGameEvent_x|OnGameEvent_''x'']] and <code>OnScriptEvent_</code> functions. Done using the <code>__CollectEventCallbacks</code> function.
| Prints message to console with C style formatting. The line feed is not included.
|-
|-
| <code>__ReplaceClosures</code>
| <code>printl</code>
| <code>void __ReplaceClosures(script, scope)</code>
| <code>void printl(string ''message'')</code>
|  
| Prints message to console with a line feed after.
|-
|-
| <code>__RunEventCallbacks</code>
| <code>realPrint</code>
| <code>void __RunEventCallbacks(event, params, prefix, globalTableName, bWarnIfMissing)</code>
| <code>void realPrint(string ''message'')</code>
| Call all functions in the callback array for the given game event
| Identical to print. print seems to be a wrapper for this.
|-
|-
| <code>__RunGameEventCallbacks</code>
| <code>Say</code>
| <code>void __RunGameEventCallbacks(event, params)</code>
| <code>void Say(CTFPlayer ''player'', string ''message'', bool ''team_only'') </code>
| Wrapper for <code>__RunEventCallbacks()</code>
| Calling this will have the specified player send the message to chat, either to team_only (true) or to everyone.
|-
|-
| <code>__RunScriptHookCallbacks</code>
| <code>ShowMessage</code>
| <code>void __RunScriptHookCallbacks()</code>
| <code>void ShowMessage(string ''message'')</code>
|
| Displays a HUD message defined in <code>scripts/titles.txt</code> to all clients, similar to an [[env_message]] entity.
|}
|}


=== Printing and Drawing ===
=== Squirrel Standard Library ===


Functions for printing out messages or drawing elements in the world, mostly for debugging reasons.
{{sq}} Functions of both Squirrel's [https://web.archive.org/web/20131225032439/http://www.squirrel-lang.org/doc/squirrel3.html#d0e2358 built-in functions] and [https://web.archive.org/web/20131225032319/http://www.squirrel-lang.org/doc/sqstdlib3.html standard library].
{{ModernWarning|Any function with the <code>Debug</code> prefix requires the cvar <code>developer</code> be enabled and the game unpaused.}}


==== Global ====
{| class="standard-table" style="width:100%"
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
|- style="position:sticky; z-index:10; top:0"
Line 4,533: Line 5,482:
! Description
! Description
|-
|-
| <code>ClientPrint</code>
| <code>assert</code>
| <code>void ClientPrint(CBasePlayer ''player'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#EHudNotify|EHudNotify]] ''destination'', string ''message'')</code>
| <code>assert(bool ''exp'')</code>
| Print a client message. If you pass null instead of a valid player, the message will be sent to all clients. When printing to chat (''HUD_PRINTTALK''), the color of the text can be changed by inserting this sequence: <code>\x07RRGGBB</code> where RR GG BB is the hexadecimal format of the color. Transparency can be specified by a different sequence: <code>\x08RRGGBBAA</code>, where RR GG BB AA is the hexadecimal format of the color + alpha. All text following this sequence will be colored. Multiple sequences can be used in combination. If using color sequences, there MUST be a color sequence at the beginning of the string, or color codes won't work!.
| Throws an assertion error if the given expression evaluates to <code>false</code> (i.e. the values <tt>0, 0.0, null</tt> and <tt>false</tt>).
{{ModernWarning|{{hammer}} Will not accept these escape sequences.  As a result, you cannot print colored text with a simple RunScriptCode input. {{todo|soon to be supported in {{hammerpp}}, which does accept escape sequences, but currently crashes when attempting to load a .vmf with a colored text sequence.}}}}
{{tip|Standard chat colors:
* Default: <code>FBECCB</code>
* RED: <code>FF3F3F</code>
* BLUE: <code>99CCFF</code>
* Unassigned/spectator: <code>CCCCCC</code>}}
|-
|-
| <code>DebugDrawBox</code>
| <code>callee</code>
| <code>void DebugDrawBox(Vector ''origin'', vector ''min'', vector ''max'', int ''r'', int ''g'', int ''b'', int ''alpha'', float ''duration'')</code>
| <code>function callee()</code>
| Draw a debug overlay box.
| Returns the currently running closure.
|-
|-
| <code>DebugDrawBoxAngles</code>
| <code>castf2i</code>
| <code>void DebugDrawBoxAngles(Vector ''origin'', Vector ''min'', Vector ''max'', QAngle ''direction'', Vector ''rgb'', int ''alpha'', float ''duration'')</code>
| <code>int castf2i(float ''value'')</code>
| Draw a debug oriented box (cent, min, max, angles(p,y,r), vRgb, a, duration).
| Interprets the float's bytes as if it were a 32-bit integer representation.
{{warning|This is a '''bit''' reinterpretation, i.e. 1.0 will not result in 1, it will be 1065353216! Use the <code>tointeger()</code> method for an actual conversion.}}
{{bug|hidetested=1|Does not return correct results since it takes a 32-bit float and returns a 64-bit integer.
{{workaround|Truncate the resulting number to 32-bit. Example:
<source lang="js">
castf2i(2.01787e-43) & 0xFFFFFFFF
</source>
}}
}}
|-
|-
| <code>DebugDrawBoxDirection</code>
| <code>casti2f</code>
| <code>void DebugDrawBoxDirection(Vector ''center'', Vector ''min'', Vector ''max'', Vector ''forward'', Vector ''rgb'', float ''alpha'', float ''duration'')</code>
| <code>float casti2f(int ''value'')</code>
| Draw a debug forward box.
| Interprets the integer's bytes as if it were a floating-point encoding.
{{warning|This is a '''bit''' reinterpretation, i.e. 420 will not result in 420.0, it will be 5.88545e^-43! Use the <code>tofloat()</code> method for an actual conversion.}}
|-
|-
| <code>DebugDrawCircle</code>
| <code>collectgarbage</code>
| <code>void DebugDrawCircle(Vector ''center'', Vector ''rgb'', float ''alpha'', float ''radius'', bool ''ztest'', float ''duration'')</code>
| <code>int collectgarbage()</code>
| Draw a debug circle.
| Runs the garbage collector and returns the number of reference cycles found(and deleted) This function only works on garbage collector builds.
|-
|-
| <code>DebugDrawClear</code>
| <code>compilestring</code>
| <code>void DebugDrawClear()</code>
| <code>any compilestring(string ''string'', string ''buffer_name'' = null)</code>
| Try to clear all the debug overlay info.
| Compiles a string containing a squirrel script into a function and returns it.
|-
|-
| <code>DebugDrawLine</code>
| <code>dummy</code>
| <code>void DebugDrawLine(Vector ''start'', Vector ''end'', int ''red'', int ''green'', int ''blue', bool ''zTest'', float ''time'')</code>
| <code>dummy()</code>
| Draw a debug overlay line.
|
|-
|-
| <code>DebugDrawLine_vCol</code>
| <code>enabledebuginfo</code>
| <code>void DebugDrawLine_vCol(Vector ''start'', vector ''end'', vector ''rgb'', bool ''ztest'', float ''duration'')</code>
| <code>void enabledebuginfo(any ''enable'')</code>
| Draw a debug line using color vec.
| Enable/disable the debug line information generation at compile time. enable != null enables . enable == null disables.
|-
|-
| <code>DebugDrawScreenTextLine</code>
| <code>error</code>
| <code>void DebugDrawScreenTextLine(float ''x'', float ''y'', int ''lineOffset'', string ''text'', int ''r'', int ''g'', int ''b'', int ''a'', float ''duration'')</code>
| <code>void error(string ''x'')</code>
| Draw text with a line offset.
| Prints x in the standard error output .
|-
|-
| <code>DebugDrawText</code>
| <code>getconsttable</code>
| <code>void DebugDrawText(Vector ''origin'', string ''text'', bool ''useViewCheck'', float ''duration'')</code>
| <code>table getconsttable()</code>
| Draw text on the screen, starting on the position of ''origin''.
| Returns the const table of the VM.
|-
|-
| <code>__DumpScope</code>
| <code>getroottable</code>
| <code>void __DumpScope(int ''indentation'', handle ''scope'')</code>
| <code>table getroottable()</code>
| Dumps contents of everything in the scope.
| Returns the root table of the VM.
|-
|-
| <code>DumpObject</code>
| <code>getstackinfos</code>
| <code>void DumpObject(handle ''object'')</code>
| <code>table getstackinfos(int ''level'')</code>
| Dumps information about a class or instance.
| Returns the stack frame informations at the given stack level (0 is the current function 1 is the caller and so on). If the stack level doesn't exist the function returns null.
{{Expand|title=Example|
{{pre|
{
  func {{=}} "DoStuff", // function name
 
  src {{=}} "test.nut", // source file
 
  line {{=}} 10, // line number
 
  locals {{=}} // a table containing the local variables
  {
    a {{=}} 10,
 
    testy {{=}} "I'm a string"
  }
}
}}}}
|-
|-
| <code>Msg</code>
| <code>print</code>
| <code>void Msg(string ''message'')</code>
| <code>void print(string ''message'')</code>
| Prints message to console without any line feed after.
| Prints the given parameter but with no newline unlike <code>printl()</code>.
|-
|-
| <code>printl</code>
| <code>resurrectunreachable</code>
| <code>void printl(string ''message'')</code>
| <code>array resurrectunreachable()</code>
| Prints message to console with a line feed after.
| Runs the garbage collector and returns an array containing all unreachable object found. If no unreachable object is found, null is returned instead. This function is meant to help debugging reference cycles. This function only works on garbage collector builds.
|-
| <code>setconsttable</code>
| <code>table setconsttable(table ''new_const'')</code>
| Sets the const table of the VM which also returns the previous const table.
|-
| <code>setdebughook</code>
| <code>void setdebughook(function<type, file, line, func_name> ''hook_func'')</code>
| Sets the debug hook.
|-
| <code>seterrorhandler</code>
| <code>void seterrorhandler(function<error> ''error_handler'')</code>
| Sets the runtime error handler .
|-
| <code>setroottable</code>
| <code>table setroottable(table ''new_root'')</code>
| Sets the root table of the VM which also returns the previous root table.
|-
| <code>swap2</code>
| <code>int swap2(int ''value'')</code>
| Swaps bytes 1 and 2 of the integer.
|-
|-
| <code>realPrint</code>
| <code>swap4</code>
| <code>void realPrint(string ''message'')</code>
| <code>int swap4(int ''value'')</code>
| Identical to print. print seems to be a wrapper for this.
| Reverse byte order of the four bytes.
|-
|-
| <code>Say</code>
| <code>swapfloat</code>
| <code>void Say(CBasePlayer ''player'', string ''message'', bool ''teamOnly'') </code>
| <code>float swapfloat(float ''value'')</code>
| Calling this will have the specified player send the message to chat, either to teamOnly (true) or to everyone.  
| Reverse byte order of the four bytes.
|-
|-
| <code>ShowMessage</code>
| <code>type</code>
| <code>void ShowMessage(string ''message'')</code>
| <code>type(var)</code>
| Print a hud message on all clients {{ModernBug|Non-functional.}}
| Returns var._typeof(), i.e. the type of the given parameter as a string
|}
|}


=== Squirrel Standard Library ===
==== Math ====


{{sq}} Functions of both Squirrel's [https://web.archive.org/web/20131225032439/http://www.squirrel-lang.org/doc/squirrel3.html#d0e2358 built-in functions] and [https://web.archive.org/web/20131225032319/http://www.squirrel-lang.org/doc/sqstdlib3.html standard library].
{{note|Trigonometric functions (<code>sin</code>, <code>cos</code>, <code>acos</code>, etc.) operate on angles in radians. Use <code>degrees * PI / 180</code> to convert degrees to radians when trying to pass the degrees into these functions, and <code>radians * 180 / PI</code> to convert radians to degrees if you want to receive degrees from inverse functions such as <code>acos</code>.}}


{| class="standard-table" style="width:100%"
{| class="standard-table" style="width:100%"
Line 4,618: Line 5,607:
! Description
! Description
|-
|-
| <code>array</code>
| <code>abs</code>
| <code>array(int ''length'', any ''fill'' = null)</code>
| <code>int abs(float ''x'')</code>
| Returns a new array of the given length where each element is set to <tt>''fill''</tt> (<tt>null</tt> by default).
| Returns <nowiki>|x|</nowiki> as integer unlike <code>fabs()</code>.
|-
|-
| <code>assert</code>
| <code>acos</code>
| <code>assert(bool ''exp'')</code>
| <code>float acos(float ''x'')</code>
| Throws an assertion error if the given expression evaluates to <code>false</code> (i.e. the values <tt>0, 0.0, null</tt> and <tt>false</tt>)
| Returns cos<sup>-1</sup>(x), -1 ≤ x ≤ 1.
|-
|-
| <code>callee</code>
| <code>asin</code>
| <code>function callee()</code>
| <code>float asin(float ''x'')</code>
| Returns the currently running closure.
| Returns sin<sup>-1</sup>(x), -1 ≤ x ≤ 1.
|-
| <code>atan</code>
| <code>float atan(float ''x'')</code>
| Returns tan<sup>-1</sup>(x).
|-
| <code>atan2</code>
| <code>float atan2(float ''y'', float ''x'')</code> (!)
| Returns the angle between the ray from the point (0, 0) through (x, y) and the positive x-axis, confined to (−PI, PI], See also [[w:atan2|atan2]]. Note the order of the parameters x and y!
|-
|-
| <code>castf2i</code>
| <code>ceil</code>
| <code>int castf2i(float ''value'')</code>
| <code>int ceil(float ''x'')</code>
| Interprets the float's bytes as if it were a 32-bit integer representation
| Returns the smallest integer that is ≥ x.
{{warning|This is a '''bit''' reinterpretation, i.e. 1.0 will not result in 1, it will be 1065353216! Use the <code>tointeger()</code> method for an actual conversion.}}
|-
|-
| <code>casti2f</code>
| <code>cos</code>
| <code>float casti2f(int ''value'')</code>
| <code>float cos(float ''x'')</code>
| Interprets the integer's bytes as if it were a floating-point encoding
| Returns cos(x).
{{warning|This is a '''bit''' reinterpretation, i.e. 420 will not result in 420.0, it will be 5.88545e^-43! Use the <code>tofloat()</code> method for an actual conversion.}}
|-
|-
| <code>collectgarbage</code>
| <code>exp</code>
| <code>int collectgarbage()</code>
| <code>float exp(float ''x'')</code>
| Runs the garbage collector and returns the number of reference cycles found(and deleted) This function only works on garbage collector builds.  
| Returns exp(x) = e<sup>x</sup>.
|-
|-
| <code>compilestring</code>
| <code>fabs</code>
| <code>any compilestring(string ''string'', string ''buffername'' = null)</code>
| <code>float fabs(float ''x'')</code>
| Compiles a string containing a squirrel script into a function and returns it.
| Returns <nowiki>|x|</nowiki> as float unlike <code>abs()</code>.
|-
|-
| <code>dummy</code>
| <code>floor</code>
| <code>dummy()</code>
| <code>int floor(float ''x'')</code>
|  
| Returns the largest integer that is ≤ x.
|-
|-
| <code>enabledebuginfo</code>
| <code>log</code>
| <code>void enabledebuginfo(any ''enable'')</code>
| <code>float log(float ''x'')</code>
| Enable/disable the debug line information generation at compile time. enable != null enables . enable == null disables.  
| Returns log<sub>e</sub>(x) = ln(x).
|-
|-
| <code>error</code>
| <code>log10</code>
| <code>void error(string ''x'')</code>
| <code>float log10(float ''x'')</code>
| Prints x in the standard error output .
| Returns log<sub>10</sub>(x).
|-
|-
| <code>getconsttable</code>
| <code>pow</code>
| <code>table getconsttable()</code>
| <code>float pow(float ''x'', float ''y'')</code>
| Returns the const table of the VM.  
| Returns x<sup>y</sup>.
|-
|-
| <code>getroottable</code>
| <code>rand</code>
| <code>table getroottable()</code>
| <code>int rand()</code>
| Returns the root table of the VM.  
| Returns a random integer with <code>0 &le; rand() &le; RAND_MAX</code>.
{{warning|The value of <code>RAND_MAX</code> is 32768 on Windows, but 2147483647 on Linux. This can cause undeterministic behavior between a server running on Windows vs Linux even if the same seed is used with <code>srand</code>. If determinism is needed, [https://learn.microsoft.com/en-us/archive/msdn-magazine/2016/august/test-run-lightweight-random-number-generation roll your own random number generator].}}
|-
|-
| <code>getstackinfos</code>
| <code>sin</code>
| <code>table getstackinfos(int ''stacklevel'')</code>
| <code>float sin(float ''x'')</code>
| Returns the stack frame informations at the given stack level (0 is the current function 1 is the caller and so on). If the stack level doesn't exist the function returns null.
| Returns sin(x).
{{Expand|title=Example|
{{pre|
{
func {{=}} "DoStuff", // function name
src {{=}} "test.nut", // source file
line {{=}} 10, // line number
locals {{=}} // a table containing the local variables
{
a {{=}} 10,
testy {{=}} "I'm a string"
}
}
}}}}
|-
|-
| <code>newthread</code>
| <code>sqrt</code>
| <code>coroutine newthread(function ''threadfunc'')</code>
| <code>float sqrt(float ''x'')</code>
| Creates a new cooperative thread object(coroutine) and returns it .
| Returns the square root of x.
|-
|-
| <code>print</code>
| <code>srand</code>
| <code>print(string ''message'')</code>
| <code>void srand(int ''seed'')</code>
| Prints the given parameter but with no newline unlike <code>printl()</code>
| Sets the starting point for generating a series of pseudorandom integers.
|-
|-
| <code>resurrectunreachable</code>
| <code>tan</code>
| <code>array resurrectunreachable()</code>
| <code>float tan(float ''x'')</code>
| Runs the garbage collector and returns an array containing all unreachable object found. If no unreachable object is found, null is returned instead. This function is meant to help debugging reference cycles. This function only works on garbage collector builds.
| Returns tan(x)
|-
| <code>setconsttable</code>
| <code>table setconsttable(table ''consttable'')</code>
| Sets the const table of the VM which also returns the previous const table. 
|-
| <code>setdebughook</code>
| <code>void setdebughook(function ''hook_func'')</code>
| Sets the debug hook.
|-
| <code>seterrorhandler</code>
| <code>void seterrorhandler(function ''func'')</code>
| Sets the runtime error handler .
|-
| <code>setroottable</code>
| <code>table setroottable(table ''roottable'')</code>
| Sets the root table of the VM which also returns the previous root table.
|-
| <code>suspend</code>
| <code>void suspend(any ''ret'')</code>
| Suspends the coroutine that called this function.
|-
| <code>swap2</code>
| <code>int swap2(int ''value'')</code>
| Swaps bytes 1 and 2 of the integer
|-
| <code>swap4</code>
| <code>int swap4(int ''value'')</code>
| Reverse byte order of the four bytes
|-
| <code>swapfloat</code>
| <code>float swapfloat(float ''value'')</code>
| Reverse byte order of the four bytes
|-
| <code>type</code>
| <code>type(var)</code>
| Returns var._typeof(), i.e. the type of the given parameter as a string
|}
|}


==== Blob ====
==== Integer ====
A blob stores a block of binary data. See [https://developer.electricimp.com/squirrel/blob official documentation] for more information.
{{ModernNote|Each blob is restricted to a maximum size of 16 megabytes. Blobs are also limited to 32 megabytes total at any given time.}}
 
{| class="standard-table" style="width:100%"
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
|- style="position:sticky; z-index:10; top:0"
Line 4,748: Line 5,688:
! Description
! Description
|-
|-
| <code>blob</code>
| <code>tofloat</code>
| <code>blob(int ''initSize'' = 0)</code>
| <code>float tofloat()</code>
|  
| Converts the integer to float and returns it.
|-
|-
| <code>eos</code>
| <code>tostring</code>
| <code>int eos()</code>
| <code>string tostring()</code>
|  
| Converts the integer to string and returns it.
|-
|-
| <code>flush</code>
| <code>tochar</code>
| <code>flush()</code>
| <code>string tochar()</code>
|  
| Returns a string containing a single character represented by the integer.
|}
 
==== Float ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
|-
| <code>len</code>
| <code>tointeger</code>
| <code>int len()</code>
| <code>int tointeger()</code>
|  
| Converts the float to integer and returns it.
|-
|-
| <code>readblob</code>
| <code>tostring</code>
| <code>blob readblob(int ''numberOfBytes'')</code>
| <code>string tostring()</code>
|  
| Converts the integer to string and returns it.
|-
|-
| <code>readn</code>
| <code>tochar</code>
| <code>any readn(char ''dataType'')</code>
| <code>string tochar()</code>
|  
| Returns a string containing a single character represented by the integer part of the float.
|}
 
==== Bool ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
|-
| <code>resize</code>
| <code>tofloat</code>
| <code>void resize(int ''newSize'')</code>
| <code>float tofloat()</code>
|  
| Returns <code>1.0</code> for true <code>0.0</code> for false.
|-
|-
| <code>seek</code>
| <code>tointeger</code>
| <code>int seek(int ''offset'', int ''offsetBasis'')</code>
| <code>int tointeger()</code>
|  
| Returns <code>1</code> for true <code>0</code> for false.
|-
|-
| <code>swap2</code>
| <code>tostring</code>
| <code>void swap2()</code>
| <code>string tostring()</code>
|  
| Returns "true" for true and "false" for false.
|-
| <code>swap4</code>
| <code>void swap4()</code>
|
|-
| <code>tell</code>
| <code>int tell()</code>
|
|-
| <code>writeblob</code>
| <code>void writeblob(blob ''blob'')</code>
|
|-
| <code>writen</code>
| <code>void writen(num ''value'', char ''dataType'')</code>
|
|}
|}


==== Math ====
==== String ====


The following belong as member methods of the string object, in other words they must be called with the dot operator on a string, e.g. <code>str.slice(0, 5)</code>.
{| class="standard-table" style="width:100%"
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
|- style="position:sticky; z-index:10; top:0"
Line 4,809: Line 5,750:
! Description
! Description
|-
|-
| <code>abs</code>
| <code>find</code>
| <code>abs(num ''x'')</code>
| <code>int find(string ''search_string'', int ''start_index'' = 0)</code>
| Returns <nowiki>|x|</nowiki> as integer unlike <code>fabs()</code>
| Looks for the sub-string passed as its first parameter, starting at either the beginning of the string or at a specific character index if one is provided as a second parameter. If the sub-string is found, returns the index at which it first occurs, otherwise returns null.
|-
|-
| <code>acos</code>
| <code>len</code>
| <code>acos(num ''x'')</code>
| <code>int len()</code>
| Returns cos<sup>-1</sup>(x), -1 &le; x &le; 1
| Returns the length of the string, ie. the number of characters it comprises.
|-
|-
| <code>asin</code>
| <code>slice</code>
| <code>asin(num ''x'')</code>
| <code>string slice(int ''start_index'', int ''end_index'' = null)</code>
| Returns sin<sup>-1</sup>(x), -1 &le; x &le; 1
| Creates a sub-string from a string. Copies characters from ''start_index'' to ''end_index''. The sub-string includes the character at ''start_index'', but excludes the one at ''end_index''. If ''end_index'' is not specified, copies until the last character. If the provided end index is beyond the string, an exception is thrown. If the numbers are negative the count will start from the end of the string (e.g. -2 represents a second last character).
|-
|-
| <code>atan</code>
| <code>tofloat</code>
| <code>atan(num ''x'')</code>
| <code>float tofloat()</code>
| Returns tan<sup>-1</sup>(x)
| Returns float value represented by the string. Must only contain numeric characters and/or plus and minus symbols. An exception is thrown otherwise.
|-
|-
| <code>atan2</code>
| <code>tointeger</code>
| <code>atan2(num ''y'', num ''x'')</code> (!)
| <code>int tointeger(int ''base'' = 10)</code>
| Returns the angle between the ray from the point (0, 0) through (x, y) and the positive x-axis, confined to (−PI, PI], see also [[w:atan2|atan2]]. Note the order of the parameters x and y!]
| Returns integer value represented by the string. Must only contain numeric characters. An exception is thrown otherwise. Hexadecimal notation is supported (i.e. <code>0xFF</code>). If a hexadecimal string contains more than 10 characters, including the <code>0x</code>, returns -1.
|-
|-
| <code>ceil</code>
| <code>tolower</code>
| <code>ceil(num ''x'')</code>
| <code>string tolower()</code>
| Returns the smallest integer that is &ge; x
| Returns a new string with all upper-case characters converted to lower-case.
|-
|-
| <code>cos</code>
| <code>toupper</code>
| <code>cos(num ''x'')</code>
| <code>string toupper()</code>
| Returns cos(x)
| Returns a new string with all lower-case characters converted to upper-case.
|}
The following belong as global string functions, e.g. <code>str = format("%d", num)</code>.
{| class="standard-table" style="width:100%"
! Function
! Signature
! Description
|-
|-
| <code>exp</code>
| <code>endswith</code>
| <code>exp(num ''x'')</code>
| <code>bool endswith(string ''str'', string ''cmp'')</code>
| Returns exp(x) = e<sup>x</sup>
| Returns true if the end of the string matches the comparison string.
|-
|-
| <code>fabs</code>
| <code>escape</code>
| <code>fabs(num ''x'')</code>
| <code>string escape(string ''str'')</code>
| Returns <nowiki>|x|</nowiki> as float unlike <code>abs()</code>
| Returns a string with backslashes before characters that need to be escaped: <code>“ a b t n v f r \ ” ’ 0 xNN</code>.
|-
|-
| <code>floor</code>
| <code>format</code>
| <code>floor(num ''x'')</code>
| <code>string format(string ''format'', args...)</code>
| Returns the largest integer that is &le; x
| Returns a [[w:printf format string|formatted string]]. Same rules as the standard C functions (except * is not supported).
|-
|-
| <code>log</code>
| <code>lstrip</code>
| <code>log(num ''x'')</code>
| <code>string lstrip(string ''str'')</code>
| Returns log<sub>e</sub>(x) = ln(x)
| Removes whitespace at the beginning of the given string.
|-
|-
| <code>log10</code>
| <code>rstrip</code>
| <code>log10(num ''x'')</code>
| <code>string rstrip(string ''str'')</code>
| Returns log<sub>10</sub>(x)
| Removes whitespace at the end of the given string.
|-
|-
| <code>pow</code>
| <code>split</code>
| <code>pow(num ''x'', num ''y'')</code>
| <code>array split(string ''str'', string ''separator'', bool ''skip_empty'' = false)</code>
| Returns x<sup>y</sup>
| Returns an array of strings split at each point where a separator character occurs in str. The separator is not returned as part of any array element. the parameter separators is a string that specifies the characters as to be used for the splitting. If skipempty is true, empty strings are not added to array.
{{Warning|Passing <code>null</code> as the first parameter will crash the server}}
|-
|-
| <code>rand</code>
| <code>startswith</code>
| <code>rand()</code>
| <code>bool startswith(string ''str'', string ''cmp'')</code>
| Returns a random integer with <code>0 &le; rand() &le; RAND_MAX</code>
| Returns true if the beginning of the string matches the comparison string.
|-
|-
| <code>sin</code>
| <code>strip</code>
| <code>sin(num ''x'')</code>
| <code>string strip(string ''str'')</code>
| Returns sin(x)
| Removes whitespace at the beginning and end of the given string
|-
| <code>sqrt</code>
| <code>sqrt(num ''x'')</code>
| Returns the square root of x
|-
| <code>srand</code>
| <code>srand(num ''seed'')</code>
| Sets the starting point for generating a series of pseudorandom integers
|-
| <code>tan</code>
| <code>tan(num ''x'')</code>
| Returns tan(x)
|}
|}


==== Strings ====
==== Array ====
 
The following belong as member methods of the string object, in other words they must be called with the dot operator on a string, e.g. <code>str.slice(0, 5)</code>.
{| class="standard-table" style="width:100%"
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
|- style="position:sticky; z-index:10; top:0"
Line 4,891: Line 5,825:
! Description
! Description
|-
|-
| <code>find</code>
| <code>array</code>
| <code>int find(string ''searchString'', int ''startIndex'' = null)</code>
| <code>array(int ''length'', any ''fill'' = null)</code>
| Looks for the sub-string passed as its first parameter, starting at either the beginning of the string or at a specific character index if one is provided as a second parameter. If the sub-string is found, returns the index at which it first occurs, otherwise returns null.
| Returns a new array of the given length where each element is set to <tt>''fill''</tt>.
|-
| <code>append</code>
| <code>void append(any ''item'')</code>
| Adds an item to the end of an array.
|-
|-
| <code>len</code>
| <code>apply</code>
| <code>void apply(function<value, [index, array_ref]>  ''func'')</code>
| Applies a function to all of an array's items and replace the original value of the element with the return value of the function. Provided func can accept up to 3 arguments: array item value (required), array item index (optional), reference to array itself (optional).
|-
| <code>clear</code>
| <code>void clear()</code>
| Removes all of the items from an array.
|-
| <code>extend</code>
| <code>array extend(array ''other'')</code>
| Combines two arrays into one.
|-
| <code>filter</code>
| <code>array filter(function<index, value> ''condition'')</code>
| Applies a filter function to an array's items, storing the results in a new array.
|-
| <code>find</code>
| <code>int find(any ''element'')</code>
| Looks for the element passed as its parameter, starting at either the beginning of the array. If the element is found, returns the index at which it first occurs, otherwise returns null.
|-
| <code>insert</code>
| <code>void insert(int ''index'', any ''item'')</code>
| Inserts an item into an array at the specified index.
|-
| <code>len</code>
| <code>int len()</code>
| <code>int len()</code>
| Returns the length of the string, ie. the number of characters it comprises.
| Returns the length of the array, ie. the number of elements it has.
|-
| <code>map</code>
| <code>array map(function<value, [index, array_ref]> ''func'')</code>
| Creates a new array of the same size. For each element in the original array invokes the function ‘func’ and assigns the return value of the function to the corresponding element of the newly created array. Provided func can accept up to 3 arguments: array item value (required), array item index (optional), reference to array itself (optional).
|-
|-
| <code>slice</code>
| <code>pop</code>  
| <code>string slice(int ''startIndex'', int ''endIndex'' = null)</code>
| <code>any pop()</code>
| Creates a sub-string from a string. Copies characters from ''startIndex'' to ''endIndex''. If ''endIndex'' is not specified, copies until the last character. If the provided end index is beyond the string, an exception is thrown.
| Returns and removes the value at the end of the array.
|-
|-
| <code>tofloat</code>
| <code>push</code>
| <code>float tofloat()</code>
| <code>void push(any ''item'')</code>
| Returns float value represented by the string. Must only contain numeric characters and/or plus and minus symbols. An exception is thrown otherwise.
| Adds an item to the end of an array.
|-
|-
| <code>tointeger</code>
| <code>reduce</code>
| <code>int tointeger()</code>
| <code>any reduce(function<pre_value, current_value> ''func'', any ''init'' = null)</code>
| Returns integer value represented by the string. Must only contain numeric characters. An exception is thrown otherwise. Hexadecimal notation is supported (i.e. <code>0xFF</code>). If a hexadecimal string contains more than 10 characters, including the <code>0x</code>, returns -1.
| This method applies the supplied function to all of the items in the target array, starting with the first two. The function returns a single value which is then combined with the next (third) item in the array — and so on until all of the items have been combined into a single value which the method returns.
|-
|-
| <code>tolower</code>
| <code>remove</code>
| <code>string tolower()</code>
| <code>any remove(int ''index'')</code>
| Returns a new string with all upper-case characters converted to lower-case.
| Returns and removes an array item at a specified index.
|-
|-
| <code>toupper</code>
| <code>resize</code>
| <code>string toupper()</code>
| <code>void resize(int ''new_size'', any ''fill'' = null)</code>
| Returns a new string with all lower-case characters converted to upper-case.
| Increases or decreases the size of an array. In case of increasing fills the new spots with ''fill'' parameter.
|}
The following belong as global string functions, e.g. <code>str = format("%d", num)</code>.
{| class="standard-table" style="width:100%"
! Function
! Signature
! Description
|-
|-
| <code>format</code>
| <code>reverse</code>  
| <code>format(string, args...)</code>
| <code>void reverse()</code>
| Returns a [[w:printf format string|formatted string]]
| Reverses the order of the elements in an array.
|-
|-
| <code>lstrip</code>
| <code>slice</code>
| <code>lstrip(string)</code>
| <code>array slice(int ''start_index'', int ''end_index'' = null)</code>
| Removes whitespace at the beginning of the given string
| Creates a new array from an array. Copies elements from ''start_index'' to ''end_index''. The new array includes the element at ''start_index'', but excludes the one at ''end_index''. If ''end_index'' is not specified, copies until the last element. If the provided end index is beyond the array, an exception is thrown. If the numbers are negative the count will start from the end of the array (e.g. -2 represents a second last character).
|-
|-
| <code>rstrip</code>
| <code>sort</code>  
| <code>rstrip(string)</code>
| <code>void sort(function<a, b> ''compare'' = null)</code>
| Removes whitespace at the end of the given string
| This method sorts the items within the target array into either a lowest-to-highest order or according to the results of an optional comparison function which may be passed to the method as a parameter. If the items are arrays, blobs, functions, objects and/or tables, they will be sorted by reference not value. The optional comparison function should take two parameters: two values which will be compared in some way. It should return the value -1 if the first value should be placed before the second, or 1 if it should follow the second value. Return 0 if the two values are equivalent. Spaceship operator <code><=></code> may come in handy if trying to sort by some field value. E.g. <source lang=js>arr.sort(@(a, b) a.distance <=> b.distance)</source>
|-
|-
| <code>split</code>
| <code>top</code>  
| <code>string split(string ''str'', string ''separator'')</code>
| <code>any top()</code>
| Returns an array of strings split at each point where a separator character occurs in str. The separator is not returned as part of any array element. the parameter separators is a string that specifies the characters as to be used for the splitting.
| Returns the value at the end of an array.
|-
|-
| <code>strip</code>
| <code>tostring</code>
| <code>strip(string)</code>
| <code>string tostring()</code>
| Removes whitespace at the beginning and end of the given string
| Returns the string "(array : ''pointer'')"
|}
|}


=== Script Debug ===
==== Table ====
Functions for interacting with the debugger. Some of them are documented [[L4D2_EMS/Appendix:_Debugging|here]].
 
{| class="standard-table" style="width:100%"
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
|- style="position:sticky; z-index:10; top:0"
Line 4,955: Line 5,913:
! Description
! Description
|-
|-
| <code>BeginScriptDebug</code>
| <code>clear</code>
| <code>void BeginScriptDebug()</code>
| <code>void clear()</code>
|  
| Removes all of the items from a table.
|-
|-
| <code>EndScriptDebug</code>
| <code>filter</code>
| <code>void EndScriptDebug()</code>
| <code>table filter(function<key, value> ''func'')</code>
|  
| Creates a new table with all values that pass the test implemented by the provided function. In detail, it creates a new table, invokes the specified function for each key-value pair in the original table; if the function returns ‘true’, then the value is added to the newly created table at the same key.
|-
|-
| <code>ScriptDebugAddTextFilter</code>
| <code>getdelegate</code>
| <code>void ScriptDebugAddTextFilter()</code>
| <code>table getdelegate()</code>
|  
| Returns a table's delegate.
|-
|-
| <code>ScriptDebugAddTrace</code>
| <code>keys</code>
| <code>void ScriptDebugAddTrace()</code>
| <code>array keys()</code>
|  
| Returns an array containing all the keys of the table slots.
|-
|-
| <code>ScriptDebugAddWatch</code>
| <code>len</code>
| <code>void ScriptDebugAddWatch()</code>
| <code>int len()</code>
|  
| Returns the length of the table, ie. the number of entries it has.
|-
|-
| <code>ScriptDebugAddWatches</code>
| <code>rawdelete</code>
| <code>void ScriptDebugAddWatches()</code>
| <code>any rawdelete(any ''key'')</code>
|  
| This method deletes the target slot without employing delegation. If the table lacks the target slot, the methods returns null, otherwise it returns the value associated with that slot.
|-
|-
| <code>ScriptDebugAddWatchPattern</code>
| <code>rawget</code>
| <code>void ScriptDebugAddWatchPattern()</code>
| <code>any rawget(any ''key'')</code>
|  
| Retrieves the value of the specified key without employing delegation.
|-
|-
| <code>ScriptDebugClearTraces</code>
| <code>rawin</code>
| <code>void ScriptDebugClearTraces()</code>
| <code>bool rawin(any ''key'')</code>
|  
| Checks for the presence of the specified key in the table/class/handle without employing delegation.
|-
|-
| <code>ScriptDebugClearWatches</code>
| <code>rawset</code>
| <code>void ScriptDebugClearWatches()</code>
| <code>table rawset(any ''key'', any ''value'')</code>
|  
| Sets the value of the specified key without employing delegation. Returns table itself.
|-
|-
| <code>ScriptDebugDefaultWatchColor</code>
| <code>setdelegate</code>
| <code>void ScriptDebugDefaultWatchColor()</code>
| <code>table setdelegate(table ''delegate'')</code>
|  
| This method assigns the passed table as the target’s new custom delegate. The method always returns the target.To remove a delegate, either assign the target with a new delegate, or pass null.
|-
|-
| <code>ScriptDebugDraw</code>
| <code>values</code>
| <code>void ScriptDebugDraw()</code>
| <code>array values()</code>
|  
| Returns an array containing all the values of the table slots.
|-
|-
| <code>ScriptDebugDrawWatches</code>
| <code>tostring</code>
| <code>void ScriptDebugDrawWatches()</code>
| <code>string tostring()</code>
|  
| Tries to invoke the <code>_tostring</code> metamethod. If that fails returns the string "(table: ''pointer'')".
|}
 
==== Function ====
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
|-
| <code>ScriptDebugDumpKeys</code>
| <code>acall</code>
| <code>void ScriptDebugDumpKeys()</code>
| <code>any acall(array ''args'')</code>
|  
| Calls the target function and passes array values into its parameters. First element of the array should be the non-default context object.
|-
|-
| <code>ScriptDebugHook</code>
| <code>bindenv</code>
| <code>void ScriptDebugHook()</code>
| <code>function bindenv(table ''environment'')</code>
|  
| Clones the target function and binds it to a specified context object.
|-
|-
| <code>ScriptDebugIterateKeys</code>
| <code>call</code>
| <code>void ScriptDebugIterateKeys()</code>
| <code>any call(table ''environment'', any ''args''...)</code>
|  
| Calls the function with a non-default context object.
|-
|-
| <code>ScriptDebugIterateKeysRecursive</code>
| <code>getinfos</code>
| <code>void ScriptDebugIterateKeysRecursive()</code>
| <code>table getinfos()</code>
|  
| Returns a table containing informations about the function, like parameters, name and source name.
{{Expand|title=Example|
{{pre|
//pure squirrel function
{
  native {{=}} false
  name {{=}} "zefuncname"
  src {{=}} "/somthing/something.nut"
  parameters {{=}} ["a","b","c"]
  defparams {{=}} [1,"def"]
  varargs {{=}} 2
}
//native C function
{
  native {{=}} true
  name {{=}} "zefuncname"
  paramscheck {{=}} 2
  typecheck {{=}} [83886082,83886384] //this is the typemask (see C defines OT_INTEGER,OT_FLOAT etc...)
}
}}}}
|-
|-
| <code>ScriptDebugRemoveTextFilter</code>
| <code>getroot</code>
| <code>void ScriptDebugRemoveTextFilter()</code>
| <code>table getroot()</code>
|  
| Returns the root table of the closure.
|-
|-
| <code>ScriptDebugRemoveTrace</code>
| <code>pacall</code>
| <code>void ScriptDebugRemoveTrace()</code>
| <code>any pacall(array ''args'')</code>
|  
| Calls the function with an array of parameters, bypassing Squirrel error callbacks. First element of the array should be the non-default context object.
|-
|-
| <code>ScriptDebugRemoveWatch</code>
| <code>pcall</code>
| <code>void ScriptDebugRemoveWatch()</code>
| <code>any pcall(table ''environment'', any ''args''...)</code>
|  
| Calls the function with a non-default context object, bypassing Squirrel error callbacks.
|-
|-
| <code>ScriptDebugRemoveWatches</code>
| <code>setroot</code>
| <code>void ScriptDebugRemoveWatches()</code>
| <code>void setroot(table ''root'')</code>
|  
| Sets the root table of a closure.
|-
|-
| <code>ScriptDebugRemoveWatchPattern</code>
| <code>tostring</code>
| <code>void ScriptDebugRemoveWatchPattern()</code>
| <code>string tostring()</code>
|  
| Returns the string "(closure: ''pointer'')".
|}
 
==== Class ====
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>getattributes</code>
| <code>any getattributes(string ''member_name'')</code>
| Returns the attributes of the specified member. If the parameter member is null, the function returns the class-level attributes.
|-
| <code>instance</code>
| <code>instance instance()</code>
| Returns a new instance of the class. This function does not invoke the instance constructor. The constructor must be explicitly called (e.g., <code>class_inst.constructor(class_inst)</code>).
|-
| <code>newmember</code>
| <code>void newmember(any ''key'', any ''value'', table ''attributes'' = {}, bool ''static'' = false)</code>
| Sets/adds the slot <code>key</code> with the value <code>val</code> and attributes <code>attributes</code> and, if present, invokes the <code>_newmember</code> metamethod. If <code>static</code> is true, the slot will be added as static. If the slot does not exist, it will be created.
|-
| <code>rawdelete</code>
| <code>any rawdelete(any ''key'')</code>
| Deletes the target slot without employing delegation. Returns null if the slot is missing; otherwise, returns the associated value.
|-
| <code>rawget</code>
| <code>any rawget(any ''key'')</code>
| Retrieves the value of the specified key without employing delegation.
|-
|-
| <code>ScriptDebugText</code>
| <code>rawin</code>
| <code>void ScriptDebugText()</code>
| <code>bool rawin(any ''key'')</code>
|  
| Checks for the presence of the specified key in the class without employing delegation.
|-
|-
| <code>ScriptDebugTextDraw</code>
| <code>rawnewmember</code>
| <code>void ScriptDebugTextDraw()</code>
| <code>void rawnewmember(any ''key'', any ''value'', table ''attributes'' = {}, bool ''static'' = false)</code>
|  
| Sets/adds the slot <code>key</code> with the value <code>val</code> and attributes <code>attributes</code>. If <code>static</code> is true, the slot will be added as static. If the slot does not exist, it will be created.
|-
|-
| <code>ScriptDebugTextPrint</code>
| <code>rawset</code>
| <code>void ScriptDebugTextPrint()</code>
| <code>class rawset(any ''key'', any ''value'')</code>
|  
| Sets the value of the specified key without employing delegation. Returns the class itself.
|-
|-
| <code>ScriptDebugTextTrace</code>
| <code>setattributes</code>
| <code>void ScriptDebugTextTrace()</code>
| <code>any setattributes(string ''member_name'', any ''value'')</code>
|  
| Sets the attribute of the specified member and returns the previous attribute value. If the parameter member is null, sets the class-level attributes.
|-
|-
| <code>ScriptDebugTraceAll</code>
| <code>tostring</code>
| <code>void ScriptDebugTraceAll()</code>
| <code>string tostring()</code>
|  
| Returns the string "(class: ''pointer'')".
|}
 
==== Class instance ====
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
|-
| <code>ScriptDebugWatches</code>
| <code>getclass</code>
| <code>void ScriptDebugWatches()</code>
| <code>class getclass()</code>
|  
| Returns the class that created the instance.
|-
|-
| <code>__VScriptServerDebugHook</code>
| <code>rawget</code>
| <code>__VScriptServerDebugHook()</code>
| <code>any rawget(any ''key'')</code>
|  
| Retrieves the value of the specified key without employing delegation.
|-
| <code>rawin</code>
| <code>bool rawin(any ''key'')</code>
| Checks for the presence of the specified key in the instance without employing delegation.
|-
| <code>rawset</code>
| <code>instance rawset(any ''key'', any ''value'')</code>
| Sets the value of the specified key without employing delegation. Returns the instance itself.
|-
| <code>tostring</code>
| <code>string tostring()</code>
| Tries to invoke the <code>_tostring</code> metamethod. If that fails returns the string "(instance: ''pointer'')".
|}
 
==== Generator ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>getstatus</code>
| <code>string getstatus()</code>
| Returns the status of the generator as string: "running", "dead" or "suspended".
|-
| <code>tostring</code>
| <code>string tostring()</code>
| Returns the string "(generator : ''pointer'')".
|}
 
==== Thread ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>newthread</code>
| <code>thread newthread(function ''threadfunc'')</code>
| Creates a new cooperative thread object(coroutine) and returns it.
{{warning|Coroutines introduce their own additional overhead and require very specific configuration to avoid server crashes. {{workaround|Use a [https://developer.electricimp.com/squirrel/squirrel-guide/functions#generator-functions generator function] instead.  Generators can spread expensive functions across multiple frames to avoid stutters/timeouts.
[https://github.com/ficool2/TF2Ware_Ultimate/blob/d698583894b87f5b94f99a0535f40fafd34a98ce/scripts/vscripts/tf2ware_ultimate/main.nut#L416 Real world TF2 example]}}}}
|-
| <code>call</code>
| <code>any call(any ''args''...)</code>
| Starts the thread with the specified parameters. Returns either the first <code>suspend</code> value or the returned value of the function if none suspends were triggered.
|-
| <code>getstackinfos</code>
| <code>table getstackinfos(int ''level'')</code>
| Returns the stack frame informations at the given stack level (0 is the current function 1 is the caller and so on). If the stack level doesn't exist the function returns null.
|-
| <code>getstatus</code>
| <code>string getstatus()</code>
| Returns the status of the thread ("idle", "running", "suspended").
|-
| <code>tostring</code>
| <code>string tostring()</code>
| Returns the string "(thread : ''pointer'')".
|-
| <code>wakeup</code>
| <code>any wakeup(any ''return'' = null)</code>
| Wakes up a suspended thread, accepts a optional parameter that will be used as return value for the function that suspended the thread(<code>suspend</code> method). The returned value will be received on the next thread suspension depending on what was passed in the <code>suspend</code> method.
|-
| <code>wakeupthrow</code>
| <code>any wakeupthrow(any ''obj_to_throw'', ''propagate_error'' = true)</code>
| Wakes up a suspended thread, throwing an exception in the awaken thread, throwing the object ''obj_to_throw''.
|}
 
This is meant to be used with the thread.
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>suspend</code>
| <code>any suspend(any ''return'' = this)</code>
| Suspends the coroutine that called this function. Needs to be called inside the thread's function body. Accepts a optional parameter that will be used as return value for the function that woke up the thread(<code>wakeup</code> method). If nothing is passed defaults to <code>this</code>(the scope in which this function was called). The returned value will be received on the next thread wake up depending on what was passed in the <code>wakeup</code> method.
|}
 
==== Weak reference ====
 
Weak references let you reference an object without preventing it from being garbage collected. They're useful when you want to refer to an object, but don't want to increase its reference count and keep it alive unnecessarily. When the object pointed by weak reference is destroyed, the weak reference is automatically set to null. <code>weakref</code> method that returns weak reference to an object exist on every object in squirrel, but primitive types like numbers will return itself since they're stored differently, therefore making this method redundant. Everything else works as expected.
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>ref</code>
| <code>instance ref()</code>
| Returns the object that the weak reference is pointing at. null if the object that was point at was destroyed.
|-
| <code>tostring</code>
| <code>string tostring()</code>
| Returns the string "(weakref : ''pointer'')".
|}
 
==== regexp ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>regexp</code>
| <code>regexp(string ''pattern'')</code>
| Create and compile a regular expression represented by the ''pattern''.
{{Note|Make sure to use double back slashes (<code>\\</code> instead of <code>\</code>) if you want to insert one in the regex instead of escaping a character.}}
{{Warning|Do not create a regular expression with empty string as it will lead to out of memory server crash.}}
|-
| <code>capture</code>
| <code>table capture(string ''str'', int ''start'' = 0)</code>
| Returns an array of tables containing two indexes ("begin" and "end") of the first match of the regular expression in the string str. An array entry is created for each captured sub expressions. If no match occurs returns null. The search starts from the index start of the string, if start is omitted the search starts from the beginning of the string.
|-
| <code>match</code>
| <code>bool match(string ''str'')</code>
| Returns a true if the regular expression matches the string str, otherwise returns false.
|-
| <code>search</code>
| <code>table search(string ''str'', int ''start'' = 0)</code>
| Returns a table containing two indexes ("begin" and "end") of the first match of the regular expression in the string ''str'', otherwise if no match occurs returns null. The search starts from the index start of the string, if start is omitted the search starts from the beginning of the string.
|-
| <code>subexpcount</code>
| <code>int subexpcount()</code>
| Counts the amount of groups present in the regular expression, note that the whole regex is considered a group so the result will always be &ge; 1.
|}
 
==== Blob ====
A blob stores a block of binary data. See [https://developer.electricimp.com/squirrel/blob official documentation] for more information.
{{note|Each blob is restricted to a maximum size of 16 megabytes. Blobs are also limited to 32 megabytes total at any given time.}}
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>blob</code>
| <code>blob(int ''init_size'' = 0)</code>
|
|-
| <code>eos</code>
| <code>int eos()</code>
|
|-
| <code>flush</code>
| <code>flush()</code>
|
|-
| <code>len</code>
| <code>int len()</code>
|
|-
| <code>readblob</code>
| <code>blob readblob(int ''number_of_bytes'')</code>
|
|-
| <code>readn</code>
| <code>any readn(char ''data_type'')</code>
|
|-
| <code>resize</code>
| <code>void resize(int ''new_size'')</code>
|
|-
| <code>seek</code>
| <code>int seek(int ''offset'', int ''offset_basis'')</code>
|
|-
| <code>swap2</code>
| <code>void swap2()</code>
|
|-
| <code>swap4</code>
| <code>void swap4()</code>
|
|-
| <code>tell</code>
| <code>int tell()</code>
|
|-
| <code>writeblob</code>
| <code>void writeblob(blob ''blob'')</code>
|
|-
| <code>writen</code>
| <code>void writen(number ''value'', char ''data_type'')</code>
|
|}
 
=== Script Debug ===
Functions for interacting with the debugger. Some of them are documented [[L4D2_EMS/Appendix:_Debugging|here]].
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>BeginScriptDebug</code>
| <code>void BeginScriptDebug()</code>
|
|-
| <code>EndScriptDebug</code>
| <code>void EndScriptDebug()</code>
|
|-
| <code>ScriptDebugAddTextFilter</code>
| <code>void ScriptDebugAddTextFilter()</code>
|
|-
| <code>ScriptDebugAddTrace</code>
| <code>void ScriptDebugAddTrace()</code>
|
|-
| <code>ScriptDebugAddWatch</code>
| <code>void ScriptDebugAddWatch()</code>
|
|-
| <code>ScriptDebugAddWatches</code>
| <code>void ScriptDebugAddWatches()</code>
|
|-
| <code>ScriptDebugAddWatchPattern</code>
| <code>void ScriptDebugAddWatchPattern()</code>
|
|-
| <code>ScriptDebugClearTraces</code>
| <code>void ScriptDebugClearTraces()</code>
|
|-
| <code>ScriptDebugClearWatches</code>
| <code>void ScriptDebugClearWatches()</code>
|
|-
| <code>ScriptDebugDefaultWatchColor</code>
| <code>void ScriptDebugDefaultWatchColor()</code>
|
|-
| <code>ScriptDebugDraw</code>
| <code>void ScriptDebugDraw()</code>
|
|-
| <code>ScriptDebugDrawWatches</code>
| <code>void ScriptDebugDrawWatches()</code>
|
|-
| <code>ScriptDebugDumpKeys</code>
| <code>void ScriptDebugDumpKeys()</code>
|
|-
| <code>ScriptDebugHook</code>
| <code>void ScriptDebugHook()</code>
|
|-
| <code>ScriptDebugIterateKeys</code>
| <code>void ScriptDebugIterateKeys()</code>
|
|-
| <code>ScriptDebugIterateKeysRecursive</code>
| <code>void ScriptDebugIterateKeysRecursive()</code>
|
|-
| <code>ScriptDebugRemoveTextFilter</code>
| <code>void ScriptDebugRemoveTextFilter()</code>
|
|-
| <code>ScriptDebugRemoveTrace</code>
| <code>void ScriptDebugRemoveTrace()</code>
|
|-
| <code>ScriptDebugRemoveWatch</code>
| <code>void ScriptDebugRemoveWatch()</code>
|
|-
| <code>ScriptDebugRemoveWatches</code>
| <code>void ScriptDebugRemoveWatches()</code>
|
|-
| <code>ScriptDebugRemoveWatchPattern</code>
| <code>void ScriptDebugRemoveWatchPattern()</code>
|
|-
| <code>ScriptDebugText</code>
| <code>void ScriptDebugText()</code>
|
|-
| <code>ScriptDebugTextDraw</code>
| <code>void ScriptDebugTextDraw()</code>
|
|-
| <code>ScriptDebugTextPrint</code>
| <code>void ScriptDebugTextPrint()</code>
|
|-
| <code>ScriptDebugTextTrace</code>
| <code>void ScriptDebugTextTrace()</code>
|
|-
| <code>ScriptDebugTraceAll</code>
| <code>void ScriptDebugTraceAll()</code>
|
|-
| <code>ScriptDebugWatches</code>
| <code>void ScriptDebugWatches()</code>
|
|-
| <code>__VScriptServerDebugHook</code>
| <code>__VScriptServerDebugHook()</code>
|
|}
|}


Line 5,073: Line 6,409:
* {{sq}} [[Squirrel]]
* {{sq}} [[Squirrel]]
* {{tf2}} [[TF2 VScript Examples|VScript Examples]]
* {{tf2}} [[TF2 VScript Examples|VScript Examples]]
* {{src13}} [[Source SDK Base 2013/Scripting/VScript Examples|List of Source SDK Base 2013 VScript Examples]]
* {{csgo}} [[List of CS:GO Script Functions]]
* {{csgo}} [[List of CS:GO Script Functions]]
* {{l4d2}} [[Left 4 Dead 2/Script Functions|List of L4D2 Script Functions]]
* {{l4d2}} [[Left 4 Dead 2/Script Functions|List of L4D2 Script Functions]]
Line 5,078: Line 6,415:
* {{asrd}} [[List of Reactive Drop Script Functions|List of AS:RD Script Functions]]
* {{asrd}} [[List of Reactive Drop Script Functions|List of AS:RD Script Functions]]
* [[List of Script Libraries]]
* [[List of Script Libraries]]
[[Category:VScript functions]]
[[Category:Scripting]]

Latest revision as of 03:41, 25 August 2025

English (en)Español (es)Русский (ru)Translate (Translate)

Squirrel This list contains the engine-related Squirrel classes, functions and variables available for VScript in Team Fortress 2 Team Fortress 2

The official documentation can be printed in the console by setting developer to non-zero, loading a map, and executing script_help. However, this documentation does not list everything, requiring them to be found by other means instead.

Tip.pngTip:TF2Maps.net Discord has a dedicated VScript channel, which is a useful place to ask for help from other people.
Tip.pngTip:Tutorial on setting up Visual Studio Code (VSCode), including auto-completing of VScript functions, can be found here.

Instances

Name Class Description
Convars Convars ↓ Provides an interface to read and change the values of console variables.
Entities CEntities ↓ Provides access to currently spawned entities.
EntityOutputs CScriptEntityOutputs ↓ Allows manipulation of entity output data.
NavMesh CNavMesh ↓ Provides access to the maps NavMesh and NavAreas.
NetProps CNetPropManager ↓ Allows reading and updating the network properties of an entity.
PlayerVoiceListener CPlayerVoiceListener ↓ Tracks if any player is using voice and for how long.

Variables

Name Type Value / Description
__FILE__ string File name of the currently executing script.
__LINE__ integer Line number of the currently executing code.
Constants table Enumerations for various function arguments or netprops.
Documentation table Contains the printed strings from the script_help command.
GameEventCallbacks table Table of registered game event callbacks.
print_indent integer 0. Spaces to indent prints by, except ones from realPrint.
_PublishedHelp table NONE
ScriptEventCallbacks table Table of registered script event callbacks.
ScriptHookCallbacks table Table of registered script hook callbacks.

Script Debug

Name Type Value
ScriptDebugDefaultWatchColor array [0, 192, 0]
ScriptDebugDrawTextEnabled bool true
ScriptDebugDrawWatchesEnabled bool true
ScriptDebugInDebugDraw bool false
ScriptDebugText array NONE
ScriptDebugTextIndent integer 0
ScriptDebugTextFilters table NONE
ScriptDebugTraces table NONE
ScriptDebugTraceAllOn bool false
ScriptDebugWatches array NONE

Constants

A constant is a variable whose value cannot be altered during program runtime, usually made to rid any instances of magic numbers by giving them self-documenting names.

Name Type Value
_charsize_ integer 1
_floatsize_ integer 4
_intsize_ integer 32-bit: 4

64-bit: 8

_version_ string "Squirrel 3.2 stable"
_versionnumber_ integer 320
RAND_MAX integer Windows: 32768

Linux: 2147483647

PI float 3.14159

Enums

See this page for all enums under the Constants table.

There are also enums kept within the Constants table, all with their own constants. For an example of accessing an enum's constant, the HIDEHUD_CROSSHAIR constant of the enum HideHUD is accessed by doing Constants.HideHUD.HIDEHUD_CROSSHAIR.

Classes

Note.pngNote:All the parameters of type string imply that you can pass null in it's place as well and the result would be equal to passing in an empty string. int parameter can be substituted with float (the floating part will be cut off) and vice versa. handle or table parameters have a poor error detection since you can pass parameter of any type into them and VM wouldn't throw any errors, this however will obviously lead to wrong or most likely completely non-functional behaviour, the only other proper parameter is null depending on whether method description advocates for it.

CBaseEntity

This is a script handle class for entities. All entities have a script handle using this class, sometimes as one of its subclasses.

An entity's own handle are accessed with:

Methods

Function Signature Description
Obsolete __KeyValueFromFloat (→ KeyValueFromFloat) bool __KeyValueFromFloat(string key, float value) Behaves the same as KeyValueFromFloat, use that instead.
Obsolete __KeyValueFromInt (→ KeyValueFromInt) bool __KeyValueFromInt(string key, int value) Behaves the same as KeyValueFromInt, use that instead.
Obsolete __KeyValueFromString (→ KeyValueFromString) bool __KeyValueFromString(string key, string value) Behaves the same as KeyValueFromString, use that instead.
Obsolete __KeyValueFromVector (→ KeyValueFromVector) bool __KeyValueFromVector(string key, Vector value) Behaves the same as KeyValueFromVector, use that instead.
AcceptInput bool AcceptInput(string input, string param, handle activator, handle caller) Generate a synchronous I/O event. Unlike EntFireByHandle, this is processed immediately. Returns false if input is a null/empty string, or if the input wasn't handled.
AddEFlags void AddEFlags(FEntityEFlags flags) Adds the supplied flags to the Entity Flags in the entity. (m_iEFlags datamap)
Note.pngNote:Adding EFL_KILLME will make the entity unkillable, even on round resets, until the flag is removed.
AddFlag void AddFlag(FPlayer flags) Adds the supplied flags to another separate player-related entity flags system in the entity. (m_fFlags datamap)
AddSolidFlags void AddSolidFlags(FSolid flags) Adds the supplied flags to the Solid Flags in the entity. (m_Collision.m_usSolidFlags datamap)
ApplyAbsVelocityImpulse void ApplyAbsVelocityImpulse(Vector impulse) Apply a Velocity Impulse as a world space impulse vector. Works for most physics-based objects including dropped weapons and even dropped Sandviches.
ApplyLocalAngularVelocityImpulse void ApplyLocalAngularVelocityImpulse(Vector impulse) Apply an Angular Velocity Impulse in entity local space. The direction of the input vector is the rotation axis, and the length is the magnitude of the impulse.
BecomeRagdollOnClient bool BecomeRagdollOnClient(Vector impulse) Acts like the BecomeRagdoll input, with the required impulse value applied as a force on the ragdoll. Does NOT spawn a prop_ragdoll or any other entity.
Warning.pngWarning:These are a special group of ragdolls that never disappear by default. To limit them or force them to disappear, use the game_ragdoll_manager entity.
ClearFlags void ClearFlags() Sets the player-related entity flags to 0 on an entity, clearing them.
ClearSolidFlags void ClearSolidFlags() Sets Solid Flags to 0 on an entity, clearing them.
ConnectOutput void ConnectOutput(string output_name, string function_name) Adds an I/O connection that will call the named function when the specified output fires.
Note.pngNote:If you are trying to access activator and caller in the called function and it doesn't exist, this means the entity has no script scope. Use ValidateScriptScope to fix this.
Destroy void Destroy() Removes the entity. Simply calls UTIL_Remove.
DisableDraw void DisableDraw() Disable drawing and transmitting the entity to clients. (adds EF_NODRAW)
DisconnectOutput void DisconnectOutput(string output_name, string function_name) Removes a connected script function from an I/O event.
DispatchSpawn void DispatchSpawn() Alternative dispatch spawn, same as the one in CEntities, for convenience.
Note.pngNote:Calling this on players will cause them to respawn. In Counter-Strike: Source, set the m_iPlayerState netprop to 0 before calling this to fully respawn.
EmitSound void EmitSound(string sound_name) Plays a sound from this entity. The sound must be precached first for it to play (using PrecacheSound or PrecacheScriptSound).
Warning.pngWarning:Looping sounds will not stop on the entity when it's destroyed and will persist forever! To workaround this, run StopSound in the OnDestroy callback.
EnableDraw void EnableDraw() Enable drawing and transmitting the entity to clients. (removes EF_NODRAW)
entindex int entindex() Returns the entity index.
EyeAngles QAngle EyeAngles() Returns the entity's eye angles. Acts like GetAbsAngles if the entity does not support it.
EyePosition Vector EyePosition() Get vector to eye position - absolute coords. Acts like GetOrigin if the entity does not support it.
FirstMoveChild handle FirstMoveChild() Returns the most-recent entity parented to this one.
Tip.pngTip:Example usage:
for (local child = entity.FirstMoveChild(); child != null; child = child.NextMovePeer())
GetAbsAngles QAngle GetAbsAngles() Get the entity's pitch, yaw, and roll as QAngles.
GetAbsVelocity Vector GetAbsVelocity() Returns the current absolute velocity of the entity.
Obsolete GetAngles (→ GetAbsAngles) Vector GetAngles() Get the entity's pitch, yaw, and roll as a Vector.
GetAngularVelocity Vector GetAngularVelocity() Get the local angular velocity - returns a Vector of pitch, yaw, and roll.
GetBaseVelocity Vector GetBaseVelocity() Returns any constant velocity currently being imparted onto the entity. This includes being pushed by effects like trigger_push and players standing on moving geometry like elevators. Should always returns a zero vector if the entity is not affected by any movement effects.
GetBoundingMaxs Vector GetBoundingMaxs() Get a vector containing max bounds, centered on object.
GetBoundingMaxsOriented Vector GetBoundingMaxsOriented() Get a vector containing max bounds, centered on object, taking the object's orientation into account.
Icon-Bug.pngBug:This does not transform the bounds correctly and in some cases the bounding box will not cover the whole entity. As a workaround, use the non-oriented bounds and perform an AABB transformation using a matrix constructed from the entity's origin and angles.
GetBoundingMins Vector GetBoundingMins() Get a vector containing min bounds, centered on object.
GetBoundingMinsOriented Vector GetBoundingMinsOriented() Get a vector containing min bounds, centered on object, taking the object's orientation into account.
Icon-Bug.pngBug:This does not transform the bounds correctly and in some cases the bounding box will not cover the whole entity. As a workaround, use the non-oriented bounds and perform an AABB transformation using a matrix constructed from the entity's origin and angles.
GetCenter Vector GetCenter() Gets center point of the entity in world coordinates.
GetClassname string GetClassname()
GetCollisionGroup int GetCollisionGroup() Gets the current collision group of the entity.

See Constants.ECollisionGroup

GetEFlags int GetEFlags() Get the entity's engine flags.

See Constants.FEntityEFlags.

GetFlags int GetFlags() Get the entity's flags.

See Constants.FPlayer.

Tip.pngTip:Example usage:
if (entity.GetFlags() & Constants.FPlayer.FL_ONGROUND)
{
	printl("Entity is on the ground!")
}
GetEntityHandle ehandle GetEntityHandle() Get the entity as an EHANDLE.
Obsolete-notext.pngDeprecated:Leftover from earlier versions of VScript.
GetEntityIndex int GetEntityIndex()
GetForwardVector Vector GetForwardVector() Get the forward vector of the entity.
Note.pngNote:If you intend to get a player's eye forward vector, use EyeAngles().Forward() instead as it's more accurate.
GetFriction float GetFriction() Get PLAYER friction, ignored for objects.
GetGravity float GetGravity()
GetHealth int GetHealth()
Obsolete GetLeftVector (→ GetRightVector) Vector GetLeftVector() Get the right vector of the entity. This is purely for compatibility.
GetLocalAngles QAngle GetLocalAngles()
GetLocalOrigin Vector GetLocalOrigin()
GetLocalVelocity Vector GetLocalVelocity() Get Entity relative velocity.
GetMaxHealth int GetMaxHealth()
GetModelKeyValues CScriptKeyValues GetModelKeyValues() Get a KeyValue class instance on this entity's model.
GetModelName string GetModelName() Returns the name of the model.
Note.pngNote:When you try to call this method on weapons the returned model would be a player hand model. For naturally spawned weapons you can receive the model index from m_iWorldModelIndex netprop, however, artificially spawned weapons always have this netprop set to 0. Instead you can create a tf_wearable with the same definition index and get it's model:

function DefinitionIndexModel(index)
{
	local wearable = Entities.CreateByClassname("tf_wearable")
	NetProps.SetPropInt(wearable, "m_AttributeManager.m_Item.m_iItemDefinitionIndex", index)
	NetProps.SetPropBool(wearable, "m_AttributeManager.m_Item.m_bInitialized", true)
	NetProps.SetPropBool(wearable, "m_bForcePurgeFixedupStrings", true)
	wearable.DispatchSpawn()

	local model = wearable.GetModelName()

	wearable.Destroy()

	return model
}
GetMoveParent handle GetMoveParent() If in hierarchy, retrieves the entity's parent.
GetMoveType int GetMoveType()
GetName string GetName() Get entity's targetname.
GetOrigin Vector GetOrigin() This is GetAbsOrigin with a funny script name for some reason. Not changing it for legacy compat though.
GetOwner handle GetOwner() Gets this entity's owner.
Note.pngNote:This is a wrapper for m_hOwnerEntity netprop. To get m_hOwner you would need to use NetProps.GetPropEntity(entity, "m_hOwner").
GetPhysAngularVelocity Vector GetPhysAngularVelocity()
GetPhysVelocity Vector GetPhysVelocity()
GetPreTemplateName string GetPreTemplateName() Get the entity name stripped of template unique decoration.
GetRightVector Vector GetRightVector() Get the right vector of the entity.
GetRootMoveParent handle GetRootMoveParent() If in hierarchy, walks up the hierarchy to find the root parent.
GetScriptId string GetScriptId() Retrieve the unique identifier used to refer to the entity within the scripting system.
GetScriptScope table GetScriptScope() Retrieve the script-side data associated with an entity.
GetScriptThinkFunc string GetScriptThinkFunc() Retrieve the name of the current script think func.
GetSolid int GetSolid() See ESolidType.
GetSoundDuration float GetSoundDuration(string sound_name, string actor_model_name) Returns float duration of the sound. Actor model name is optional and can be left null.
Todo: Actor model name is likely a leftover from Half-Life 2 Half-Life 2
Warning.pngWarning:Does not work on dedicated servers as they do not have audio libraries built-in to load sounds.
GetTeam int GetTeam() See ETFTeam.
GetUpVector Vector GetUpVector() Get the up vector of the entity.
Obsolete GetVelocity (→ GetAbsVelocity) Vector GetVelocity()
GetWaterLevel int GetWaterLevel() This function tells you how much of the entity is underwater. It returns a value of 0 if not underwater, 1 if the feet are (touching water brush), 2 if the waist is (center of the hull of the entity), and 3 if the head is (eyes position).
Note.pngNote:Some entities might not return 1 despite touching water. In some cases you might get 0 and 3 only, or sometimes 0, 2 and 3.
GetWaterType int GetWaterType() It returns the type of water the entity is currently submerged in. 32 for water and 16 for slime.
IsAlive bool IsAlive() Am I alive?
IsEFlagSet bool IsEFlagSet(FEntityEFlags flag)
IsPlayer bool IsPlayer() Checks whether the entity is a player or not.
IsSolid bool IsSolid()
IsSolidFlagSet bool IsSolidFlagSet(FSolid flag)
IsValid bool IsValid() Checks whether the entity still exists. Useful when storing entity handles and needing to check if the entity was not deleted.
Note.pngNote:This function is never necessary to call on handles returned from built-in script functions, as they are guaranteed to be valid or null.
KeyValueFromFloat bool KeyValueFromFloat(string key, float value) Executes KeyValue with a float.
Warning.pngWarning:Does not update the internal network state of the entity, which can result in any desired visual changes being delayed for clients if used after spawning. Netprops ↓ can be used instead which correctly updates the networking state and results in an immediate update. An exception is the origin keyvalue, which does update network state immediately.
KeyValueFromInt bool KeyValueFromInt(string key, int value) Executes KeyValue with an int.
Warning.pngWarning:See above.
KeyValueFromString bool KeyValueFromString(string key, string value) Executes KeyValue with a string.
Warning.pngWarning:See above.
KeyValueFromVector bool KeyValueFromVector(string key, Vector value) Executes KeyValue with a vector.
Warning.pngWarning:See above.
Kill void Kill() Removes the entity. Equivalent of firing the Kill I/O input, but instantaneous.
Warning.pngWarning:This clears the owner entity (m_hOwnerEntity netprop) before removing, this may cause unexpected problems with entities that rely on cleaning up data related to their owner, such as Medigun healing targets. In those cases, use Destroy instead.
LocalEyeAngles QAngle LocalEyeAngles() Returns the entity's local eye angles.
NextMovePeer handle NextMovePeer() Returns the next entity parented with the entity. Intended for iteration use with FirstMoveChild().
PrecacheModel void PrecacheModel(string model_name) Precache a model (.mdl) or sprite (.vmt). The extension must be specified.
Note.pngNote:This has no return, unlike the global PrecacheModel function. Use the latter if you need the model index.
Note.pngNote:Does not precache gibs. See PrecacheEntityFromTable instead.
PrecacheScriptSound void PrecacheScriptSound(string sound_script) Precache a sound script. Same as PrecacheSoundScript.
PrecacheSoundScript void PrecacheSoundScript(string sound_script) Precache a sound script. Same as PrecacheScriptSound.
RemoveEFlags void RemoveEFlags(FEntityEFlags flags)
RemoveFlag void RemoveFlag(FPlayer flags)
RemoveSolidFlags void RemoveSolidFlags(FSolid flags)
SetAbsAngles void SetAbsAngles(QAngle angles) Set entity pitch, yaw, roll as QAngles. Does not work on players, use SnapEyeAngles instead.
SetAbsVelocity void SetAbsVelocity(Vector velocity) Sets the current absolute velocity of the entity. Does nothing on VPhysics objects (such as prop_physics). For those, use SetPhysVelocity instead.
SetAbsOrigin void SetAbsOrigin(Vector origin) Sets the absolute origin of the entity.
Note.pngNote:On some entities, this won't interpolate positions and therefore moving entities might look jittery. In those cases, use KeyValueFromVector("origin", pos) instead.
Obsolete SetAngles (→ SetAbsAngles) void SetAngles(float pitch, float yaw, float roll) Set entity angles.
SetAngularVelocity void SetAngularVelocity(float pitch, float yaw, float roll) Set the local angular velocity.
SetCollisionGroup void SetCollisionGroup(ECollisionGroup group) Set the current collision group of the entity.
SetDrawEnabled void SetDrawEnabled(bool toggle) Enables drawing if you pass true, disables drawing if you pass false.
SetEFlags void SetEFlags(FEntityEFlags flags)
SetForwardVector void SetForwardVector(Vector forward) Set the orientation of the entity to have this forward vector.
Note.pngNote:If used on the players the resulting orientation will not be normalized which can lead to console warnings in some cases. To avoid this convert the vector to an angle with the following function and pass the result into SnapEyeAngles:

function VectorAngles(forward)
{
	local yaw, pitch
	if (forward.y == 0.0 && forward.x == 0.0)
	{
		yaw = 0.0
		if (forward.z > 0.0)
			pitch = 270.0
		else
			pitch = 90.0
	}
	else
	{
		yaw = (atan2(forward.y, forward.x) * 180.0 / Constants.Math.Pi)
		if (yaw < 0.0)
			yaw += 360.0
		pitch = (atan2(-forward.z, forward.Length2D()) * 180.0 / Constants.Math.Pi)
		if (pitch < 0.0)
			pitch += 360.0
	}

	return QAngle(pitch, yaw, 0.0)
}
Note.pngNote:If used on the players consider the note on SnapEyeAngles in CBasePlayer ↓.
SetFriction void SetFriction(float friction)
SetGravity void SetGravity(float gravity) Sets a multiplier for gravity. 1 is default gravity.
Note.pngNote:0 gravity will not work. Instead, set it to something like 0.000001 as a workaround.
SetHealth void SetHealth(int health)
SetLocalAngles void SetLocalAngles(QAngle angles)
SetLocalOrigin void SetLocalOrigin(Vector origin)
SetMaxHealth void SetMaxHealth(int health) Sets the maximum health this entity can have. Does not update the current health, so SetHealth should be used afterwards.
Note.pngNote:Does nothing on players.
PlacementTip.pngWorkaround:Instead, use AddCustomAttribute to add an attribute like max health additive bonus or hidden maxhealth non buffed. The latter attribute works like the max health gained from the Heavy's Dalokohs Bar, which doesn't affect max overheal amount.
SetModel void SetModel(string model_name) Set a model for this entity.
Note.pngNote:Does nothing on players. Use SetCustomModel in that case.
Warning.pngWarning:Make sure the model was already precached before using this function or otherwise the game will crash! Alternatively, SetModelSimple will precache the entity for you.
SetMoveType void SetMoveType(EMoveType movetype, EMoveCollide movecollide)
Obsolete SetOrigin (→ SetAbsOrigin) void SetOrigin(Vector origin)
SetOwner void SetOwner(handle entity) Sets this entity's owner.
Note.pngNote:This is a wrapper for m_hOwnerEntity netprop. To set m_hOwner you would need to use NetProps.SetPropEntity(entity, "m_hOwner", owner).
SetPhysAngularVelocity void SetPhysAngularVelocity(Vector angular_velocity)
SetPhysVelocity void SetPhysVelocity(Vector velocity)
SetSize void SetSize(Vector mins, Vector maxs) Sets the bounding box's scale for this entity.
Warning.pngWarning:If any component of mins/maxs is backwards (i.e. mins.x > maxs.x), the engine will exit with a fatal error.
SetSolid void SetSolid(ESolidType solid)
SetSolidFlags void SetSolidFlags(FSolid flags)
SetTeam void SetTeam(ETFTeam team) Sets entity team.
Note.pngNote:Use ForceChangeTeam on players instead.
Obsolete SetVelocity (→ SetAbsVelocity) void SetVelocity(Vector velocity)
SetWaterLevel void SetWaterLevel(int water_level) This sets how much of the entity is underwater. Setting it to 0 means it is not underwater, 1 if the feet are (touching water brush), 2 if the waist is (center of the hull of the entity), and 3 if the head is (eyes position).
SetWaterType void SetWaterType(int water_type) Set the type of water the entity is currently submerged in. Generic values to use are 32 for water and 16 for slime.
StopSound void StopSound(string sound_name) Stops a sound on this entity.
TakeDamage void TakeDamage(float damage, FDmgType damage_type, handle attacker) Deals damage to the entity.
TakeDamageEx void TakeDamageEx(handle inflictor, handle attacker, handle weapon, Vector damage_force, Vector damage_position, float damage, FDmgType damage_type) Extended version of TakeDamage.
Note.pngNote:If damage_force is Vector(0, 0, 0), the game will automatically calculate it from damage_position and damage. However, specifying a custom damage force requires a really, really big value to have visible effect (in the hundreds of thousands).
TakeDamageCustom void TakeDamageCustom(handle inflictor, handle attacker, handle weapon, Vector damage_force, Vector damage_position, float damage, FDmgType damage_type, ETFDmgCustom custom_damage_type) Extended version of TakeDamageEx that can apply a custom damage type.
Teleport void Teleport(bool use_origin, Vector origin, bool use_angles, QAngle angles, bool use_velocity, Vector velocity) Teleports this entity. For this function, set the bools to false if you want that entity's property unchanged. (do not use null arguments!)
TerminateScriptScope void TerminateScriptScope() Clear the current script scope for this entity.
ToggleFlag void ToggleFlag(FPlayer flags)
ValidateScriptScope bool ValidateScriptScope() Create a script scope for an entity if it doesn't already exist. The return value is always true, unless the script VM is disabled in launch options.
Note.pngNote:This is unnecessary to run on entities that have an entity script assigned. Entity scripts will already create the script scope themselves.
Tip.pngTip:On players, this only needs to be called once. Script scopes remain permanent on players until their entity is removed, i.e. disconnected. The best place to call this is in the player_spawn event when params.team equals 0 (unassigned). The event is always fired once for team unassigned when the player entity spawns. Similarly, for engineer buildings, this function can also be called once. The player_builtobject is fired when an engineer building is created (or re-placed after moving, but this shouldn't matter).

Hooks

Hooks are functions that are called by the game code at appropriate moments. For example, when an entity takes damage, the OnTakeDamage hook would be executed.

Function Signature Description
Input<name> bool Input<name>() Called right before an entity receives a valid input from the I/O system that matches the function's name. The name of the function needs to beInputfollowed by the name of the input. E.g. for the FireUser1 input, it would beInputFireUser1. When the function is called, Script Handles of the activator and caller entities are accessible to the function under the variablesactivatorandcaller. The function needs to return a boolean value: returningtrueprocesses the input, whilefalsecancels it.
Icon-Bug.pngBug:There is an inconsistency with the naming scheme of the inputs. Certain inputs are required in PascalCase format, others in lowercase format. For example, ForceDrop input on item_teamflag must be specified in lowercase, i.e. Inputforcedrop, but another input such as Kill input must be in PascalCase, i.e. InputKill. However, this inconsistency also varies between different entity classes as well. The cause of this is string caching in the game (I/O is case-insensitive so it normally doesn't matter, but Squirrel is case-sensitive).
Tip.pngTip:It is best to define both variants of these function and have one be a wrapper for the other, i.e. Inputfireuser1 <- InputFireUser1.
Tip.pngTip:This hook is fired before the game processes the input internally. If a hook is required that runs after the game processes it, there is two options:
  • Asynchronous: Use a EntFire with a 0 delay to run code at the end of the frame. This is not instantly executed which may cause issues if multiple inputs get processed at once.
  • Synchronous: Using a quirk, it's possible to synchronously detect when the input has been processed. The game wipes the activator and caller variables from the root table after processing an input. A metamethod that overrides the slot deletion operator can be used to detect this. The following example demonstrates a system to conveniently define pre- and post- input hooks using a SetInputHook function:

// Implementation

local PostInputFunc = null

::SetInputHook <- function(entity, input, pre_func, post_func)
{
	entity.ValidateScriptScope()
	local scope = entity.GetScriptScope()

	if (post_func)
	{
		post_func = post_func.bindenv(scope)
		
		local wrapper_func
		if (pre_func)
		{
			pre_func = pre_func.bindenv(scope)
			wrapper_func = function()
			{
				PostInputFunc = post_func
				return pre_func()
			}
		}
		else 
		{
			wrapper_func = function()
			{
				PostInputFunc = post_func
				return true
			}
		}

		scope["Input" + input]           <- wrapper_func
		scope["Input" + input.tolower()] <- wrapper_func
	}
	else if (pre_func)
	{
		scope["Input" + input]           <- pre_func
		scope["Input" + input.tolower()] <- pre_func
	}
}

getroottable().setdelegate(
{
	_delslot = function(key) {
		if (!(key in this))
			throw format("the index '%s' does not exist", key)

		if (PostInputFunc && key == "activator")
		{
			PostInputFunc()
			PostInputFunc = null
		}

		return rawdelete(key)
	}
})

// Example that hooks the RunScriptCode input on worldspawn

function PreInputRunScriptCode()
{
	printl("INPUT PRE: RunScriptCode")
	printl("\tself: " + self)
	printl("\tactivator: " + activator)
	return true
}

function PostInputRunScriptCode()
{
	printl("INPUT POST: RunScriptCode")
	printl("\tself: " + self)
	printl("\tactivator: " + activator)
}

local world = Entities.FindByClassname(null, "worldspawn")
SetInputHook(world, "RunScriptCode", PreInputRunScriptCode, PostInputRunScriptCode)

EntFire("worldspawn", "RunScriptCode", "printl(`RunScriptCode executed`)", 0, GetListenServerHost())
OnGameEvent_<name> void OnGameEvent_<name>(table params) Called each time a game event with the specified name occurs. The name of the function needs to be OnGameEvent_ followed by the name of the game event. E.g. for the player_spawn input, it would be OnGameEvent_player_spawn.

When the function is called, a table is passed to the function with keys that vary depending on the event. For example, the player_spawn event passes a table with the keys userid, team, class, while the deadringer_cheat_death event passes a table with the keys spy, attacker.

A call to __CollectGameEventCallbacks is required to register this hook. See the examples page.

See this page for a list of game events as well as the table passed on each event.

Precache void Precache() Entity function that is called after the script executes, but before the entity is initialized. Can be used to call precache functions for models and sounds on map load.
Tip.pngTip:This can also be used to modify keyvalues on the entity, and it will use the new values when initializing.
ConnectOutputs void ConnectOutputs(table scope) Global function called after an entity with an script assigned spawns (i.e. vscripts keyvalue is not blank). Unlike OnPostSpawn, this is called immediately and therefore on map respawn, some entities may not exist during this point.
Note.pngNote:This is a global hook and therefore will only work in global scope, unlike Precache and OnPostSpawn.
OnPostSpawn void OnPostSpawn() Entity function called after the entity is spawned and initialized, at the end of the frame. When map entities are respawned, this effectively runs after all scripts, players etc have been loaded. This could be used to have an entity register itself with a master script, or adjusting the entity parameters in a programmatic way.
OnScriptHook_OnTakeDamage void OnScriptHook_OnTakeDamage(table params) Called each time an entity takes damage. The script can modify the table entries not prefixed with const, and these will be sent back to the game code.

A call to __CollectGameEventCallbacks is required to register this hook. Internally, this hook is processed the same as a game event, but with the OnScriptHook prefix instead of OnGameEvent. Therefore, see the example page for an explanation of how to register the hook. Example:


local EventsID = UniqueString()
getroottable()[EventsID] <-
{
	OnScriptHook_OnTakeDamage = function(params)
	{
		printl("OnScriptHook_OnTakeDamage")
		if (params.const_entity.IsPlayer())
		{
			__DumpScope(1, params) // show parameters
			params.damage = 0
		}
	}

	// Cleanup events on round restart
	OnGameEvent_scorestats_accumulated_update = function(_) { delete getroottable()[EventsID] }
}
local EventsTable = getroottable()[EventsID]
foreach (name, callback in EventsTable) EventsTable[name] = callback.bindenv(this)
__CollectGameEventCallbacks(EventsTable)
Note.pngNote:The world entity (brushes, static props etc) will not trigger this function by default as it normally can't 'receive' damage. However, the world can be made to 'allow' damage using the following code: NetProps.SetPropInt(Entities.FindByClassname(null, "worldspawn"), "m_takedamage", 1). This does not appear to have any adverse side effects, and allows detecting when the world has been hit.
Note.pngNote:If called where the damage source is a player's hitscan weapon, player positions or angles fetched within the lag compensation "cone" of the attacker will be using lag compensated positions rather than their real positions.
Note.pngNote:Drowning damage does not trigger this hook. As a workaround, it can be detected in player_hurt event or disabled by setting m_PainFinished netprop to a very high value.
Warning.pngWarning:This is called before any actual damage processing is done. Certain entries might not be calculated or have different values compared to what will be calculated.
Tip.pngTip:Listen for the player_hurt or npc_hurt (nextbots) event to effectively have an OnTakeDamage callback after final damage calculations are done.
Tip.pngTip:DMG_ACID is set in damage_type for critical damage, and DMG_SLOWBURN for falloff. These flags can be toggled to add/remove crits or falloff respectively.
Tip.pngTip:The hitbox that got hit can be retrieved using the m_LastHitGroup netprop on player entities or generic_actor. The number corresponds to Constants.EHitGroup.

The table contains the following keys:

Name Type Description
const_entity handle The entity which took damage.
inflictor handle The entity which dealt the damage, can be null.
weapon handle The weapon which dealt the damage, can be null.
attacker handle The owner of the damage, can be null.
damage float Damage amount.
max_damage float Damage cap.
damage_bonus float Additional damage (e.g. from crits).
Warning.pngWarning:Always 0 because this hook is run before this is calculated.
damage_bonus_provider handle Owner of the damage bonus.
Warning.pngWarning:Always 0 because this hook is run before this is calculated.
const_base_damage float Base damage.
damage_force Vector Damage force.
damage_for_force_calc float
Icon-Bug.pngBug:This value does not seem to do anything.
damage_position Vector World position of where the damage came from. E.g. end position of a bullet or a rocket.
reported_position Vector World position of where the damage supposedly came from.
damage_type int Combination of damage types. See Constants.FDmgType
damage_custom int
Icon-Bug.pngBug:Because of a code oversight, this value is read-only. Use damage_stats instead which can be read and written.
damage_stats int Special damage type. See Constants.ETFDmgCustom. Unlike damage_type, only one custom damage type can be set.
force_friendly_fire bool If true, force the damage to friendlyfire, regardless of this entity's and attacker's team.
Note.pngNote:Hitscan/melee will not run OnTakeDamage unless the mp_friendlyfire convar is set to 1.
ammo_type int Unused.
player_penetration_count int How many players the damage has penetrated so far.
damaged_other_players int How many players other than the attacker has the damage been applied to. Used for rocket jump damage reduction.
crit_type int Type of crit damage. 0 - None, 1 - Mini, 2 - Full. The numbers correspond to Constants.ECritType.
Warning.pngWarning:Always 0 because this hook is run before this is set. You can check for DMG_ACID in damage_type, which is set when the shot will be critical, however, it doesn't show ordinary hits which would be converted to critical ones like Neon Annihilator hitting a soaked target or a Bushwacka hitting with a mini-crit. Alternative would be to check whether the damage is crit in player_hurt event, which also works for mini-crits as well, the downside is that this event happens only after the damage has been dealt so no changes inside the hook are possible.

If you want to force the damage to be critical you need to set DMG_ACID to be included in damage_type:

params.damage_type = params.damage_type | Constants.FDmgType.DMG_ACID

For players, if you want to force the damage to be a mini-crit you can add a mini-crit cond to the attacker inside this hook and remove it in player_hurt or npc_hurt respective events afterwards. Example:


function RemoveBuff(player)
{
	local scope = player.GetScriptScope()
	if ("remove_buff" in scope && scope.remove_buff)
	{
		player.RemoveCond(Constants.ETFCond.TF_COND_OFFENSEBUFF)
		scope.remove_buff = false
	}
}

events <-
{
	function OnScriptHook_OnTakeDamage(params)
	{
		local attacker = params.attacker
		if (!attacker)
			return

		local scope = attacker.GetScriptScope()
		if (!("force_minicrit" in scope) || !scope.force_minicrit)
			return

		if (attacker.InCond(Constants.ETFCond.TF_COND_OFFENSEBUFF))
			return

		if (params.const_entity.IsPlayer() ||
			params.const_entity instanceof NextBotCombatCharacter)
		{
			attacker.AddCond(Constants.ETFCond.TF_COND_OFFENSEBUFF)
			scope.remove_buff = true
		}
	}

	function OnGameEvent_player_hurt(params)
	{
		local attacker = GetPlayerFromUserID(params.attacker)
		if (!attacker)
			return

		RemoveBuff(attacker)
	}

	function OnGameEvent_npc_hurt(params)
	{
		local attacker = GetPlayerFromUserID(params.attacker_player)
		if (!attacker)
			return

		RemoveBuff(attacker)
	}
}
__CollectGameEventCallbacks(events)


local player = GetListenServerHost()
player.ValidateScriptScope()
local scope = player.GetScriptScope()

scope.force_minicrit <- true
scope.remove_buff <- false
Icon-Bug.pngBug:Only mini-crits if the owner was alive during the hit, e.g. firing a rocket and dying before the rocket lands will not result in a mini-crit. When hitting the players you can apply TF_COND_MARKEDFORDEATH on them instead which would fix this issue, however, any hits to the victim from other sources that were dealt in the same tick as your intended mini-crit hit will also turn into the mini-crits.The addconds cannot be applied on nextbots making this solution completely irrelevant to them.
Note.pngNote:Setting this to 1 makes the damage act as a mini-crit, while producing full crit sounds and visuals, this can be used for cases where the attacker is not a player since only physical aspect of the damage would matter. Setting it to 2 has no effect.
early_out bool If set to true by the script, the game's damage routine will not run and it will simply return the currently set damage.

Callbacks

OnDestroy

It is possible to setup an asynchronous hook which is fired when the entity is deleted, as shown below. It is processed at the end of the frame after the entity's own destroy callback, but before the entity is about to be removed from memory. The caveats are that it is not possible to rescue an entity nor its children in this callback, and the targetname of the entity is cleared (this can be workarounded by storing the name in the script scope if needed). A useful application of this hook is to stop looping sounds on an entity so they don't persist.


// Implementation
function SetDestroyCallback(entity, callback)
{
	entity.ValidateScriptScope()
	local scope = entity.GetScriptScope()
	scope.setdelegate({}.setdelegate({
			parent   = scope.getdelegate()
			id       = entity.GetScriptId()
			index    = entity.entindex()
			callback = callback
			_get = function(k)
			{
				return parent[k]
			}
			_delslot = function(k)
			{
				if (k == id)
				{
					entity = EntIndexToHScript(index)
					local scope = entity.GetScriptScope()
					scope.self <- entity
					callback.pcall(scope)
				}
				delete parent[k]
			}
		})
	)
}

// Example
local entity = SpawnEntityFromTable("prop_dynamic",
{
	model = "models/player/heavy.mdl"
	origin = Vector(1, 2, 3)
})

SetDestroyCallback(entity, function()
{
	printf("Entity %s at %s was destroyed\n", self.GetClassname(), self.GetOrigin().ToKVString())
})
Note.pngNote:All handles to the entity are destroyed when inside the callback. You must access the entity by using self only.

Alternatively: if entities need to be rescued from a deletion on a round restart, for example a player parented to a vehicle, the scorestats_accumulated_update event can be used. This event is fired on round restart right before all entities are removed. Add the EFL_KILLME eflag to the entities to rescue, then remove it after entities have spawned.

CBaseAnimating

Extends CBaseEntity ↑

Script handle class for animatable entities, such as props.

Methods

Function Signature Description
DispatchAnimEvents void DispatchAnimEvents(CBaseAnimating entity) Dispatch animation events to a CBaseAnimating entity.
FindBodygroupByName int FindBodygroupByName(string name) Find a bodygroup ID by name. Returns -1 if the bodygroup does not exist.
GetAttachmentAngles QAngle GetAttachmentAngles(int id) Get an attachment's angles as a QAngle, by ID.
GetAttachmentBone int GetAttachmentBone(int id) Get an attachment's parent bone index by ID.
GetAttachmentOrigin Vector GetAttachmentOrigin(int id) Get an attachment's origin as a Vector, by ID.
GetBodygroup int GetBodygroup(int id) Get the bodygroup value by bodygroup ID.
GetBodygroupName string GetBodygroupName(int id) Get the bodygroup's name by ID.
GetBodygroupPartName string GetBodygroupPartName(int group, int part) Get the bodygroup's name by group and part.
GetBoneAngles QAngle GetBoneAngles(int id) Get the bone's angles as a QAngle, by ID.
Warning.pngWarning:For performance, bone transforms are cached by the game. The cache is updated once per frame. Setting new sequences, cycles etc may cause this to access stale bone data. If this is a problem, then call SetModelSimple first, which will update the bone cache.
GetBoneOrigin Vector GetBoneOrigin(int id) Get the bone's origin Vector by ID.
Warning.pngWarning:See above.
GetCycle float GetCycle() Gets the model's current animation cycle rate. Ranges from 0.0 to 1.0.
GetModelScale float GetModelScale() Get the model's scale.
GetPlaybackRate float GetPlaybackRate() Get the current animation's playback rate.
GetSequence int GetSequence() Get the current-playing sequence's ID.
GetSequenceActivityName string GetSequenceActivityName(int id) Get the activity name for a sequence by sequence ID.
GetSequenceDuration float GetSequenceDuration(int id) Get a sequence duration in seconds by sequence ID.
GetSequenceName string GetSequenceName(int id) Get a sequence name by sequence ID. Returns "Not Found!" if ID is -1, "Unknown" if the sequence doesn't exist or "No model!" if no model is assigned.
GetSkin int GetSkin() Gets the current skin index.
IsSequenceFinished bool IsSequenceFinished() Ask whether the main sequence is done playing.
LookupActivity int LookupActivity(string activity) Get the named activity index. Returns -1 if the activity does not exist.
LookupAttachment int LookupAttachment(string name) Get the named attachment index. Returns 0 if the attachment does not exist.
LookupBone int LookupBone(string bone) Get the named bone index. Returns -1 if the bone does not exist.
LookupPoseParameter int LookupPoseParameter(string name) Gets the pose parameter's index. Returns -1 if the pose parameter does not exist.
LookupSequence int LookupSequence(string name) Looks up a sequence by names of sequences or activities. Returns -1 if the sequence does not exist.
ResetSequence void ResetSequence(int id) Reset a sequence by sequence ID. If the ID is different than the current sequence, switch to the new sequence.
SetBodygroup void SetBodygroup(int id, int value) Set the bodygroup by ID.
SetCycle void SetCycle(float cycle) Sets the model's current animation cycle from 0 to 1.
Note.pngNote:This only works if the entity has m_bClientSideAnimation set to false. Some entities such as prop_dynamic have this true by default and therefore SetCycle will visually not do anything until that netprop is turned off.
SetModelSimple void SetModelSimple(string model_name) Set a model for this entity. Matches easier behaviour of the SetModel input, automatically precaches, maintains sequence/cycle if possible. Also clears the bone cache.
Note.pngNote:Does nothing on players. Use SetCustomModel in that case.
SetModelScale void SetModelScale(float scale, float change_duration) Changes a model's scale over time. Set the change duration to 0.0 to change the scale instantly.
SetPlaybackRate void SetPlaybackRate(float rate) Set the current animation's playback rate.
SetPoseParameter float SetPoseParameter(int id, float value) Sets a pose parameter value. Returns the effective value after clamping or looping.
Note.pngNote:Does nothing on players. Pose parameters aren't networked on players.
Icon-Bug.pngBug:prop_dynamic will have visual glitches with server-sided pose parameters. Use point_posecontroller, or another entity like base_boss or funCBaseFlex.
SetSequence void SetSequence(int id) Plays a sequence by sequence ID.
Warning.pngWarning:This can cause animation stutters when transitioning between sequences, or sequences to not be set at all on some entities (such as obj_sentrygun). Using ResetSequence instead will prevent this. Only tested on base_boss.
Note.pngNote:Does nothing on players. Players use a different animation system.
SetSkin void SetSkin(int index) Sets the model's skin.
StopAnimation void StopAnimation() Stop the current animation (same as SetPlaybackRate 0.0).
StudioFrameAdvance void StudioFrameAdvance() Advance animation frame to some time in the future with an automatically calculated interval.
StudioFrameAdvanceManual void StudioFrameAdvanceManual(float dt) Advance animation frame to some time in the future with a manual interval.

CBaseCombatWeapon

Extends CBaseAnimating ↑

Script handle class for any weapon entities that can be part of a player's inventory.
Team Fortress 2's weapons leave Clip2 unused, so those functions can be ignored

Methods

Function Signature Description
CanBeSelected bool CanBeSelected() Can this weapon be selected.
Clip1 int Clip1() Current ammo in clip1.
Clip2 int Clip2() Current ammo in clip2.
GetDefaultClip1 int GetDefaultClip1() Default size of clip1.
GetDefaultClip2 int GetDefaultClip2() Default size of clip2.
GetMaxClip1 int GetMaxClip1() Max size of clip1.
GetMaxClip2 int GetMaxClip2() Max size of clip2.
GetName string GetName() Gets the weapon's internal name (not the targetname!)
Warning.pngWarning:This conflicts with CBaseEntity's GetName function. To get the targetname of the weapon, call it like this instead CBaseEntity.GetName.call(weapon). Alternatively you can fetch the property directly NetProps.GetPropString(weapon, "m_iName").
GetPosition int GetPosition() Gets the weapon's current position.
GetPrimaryAmmoCount int GetPrimaryAmmoCount() Current primary ammo count if no clip is used or to give a player if they pick up this weapon legacy style (not TF).
GetPrimaryAmmoType int GetPrimaryAmmoType() Returns the primary ammo type.
GetPrintName string GetPrintName() Gets the weapon's print name.
GetSecondaryAmmoCount int GetSecondaryAmmoCount() Current secondary ammo count if no clip is used or to give a player if they pick up this weapon legacy style (not TF).
GetSecondaryAmmoType int GetSecondaryAmmoType() Returns the secondary ammo type.
GetSlot int GetSlot() Gets the weapon's current slot.
GetSubType int GetSubType() Get the weapon subtype.
GetWeaponFlags int GetWeaponFlags() Get the weapon flags.
GetWeight int GetWeight() Get the weapon weighting/importance.
HasAnyAmmo bool HasAnyAmmo() Do we have any ammo?
HasPrimaryAmmo bool HasPrimaryAmmo() Do we have any primary ammo?
HasSecondaryAmmo bool HasSecondaryAmmo() Do we have any secondary ammo?
IsAllowedToSwitch bool IsAllowedToSwitch() Are we allowed to switch to this weapon?
IsMeleeWeapon bool IsMeleeWeapon() Returns whether this is a melee weapon.
Note.pngNote:tf_weapon_buff_item (entity for Soldier's banner items), are considered melee in the code.
PrimaryAttack void PrimaryAttack() Force a primary attack.
Tip.pngTip:This allows arbitrarily firing weapons that do not actually belong to any player. This can be useful for creating entities that might not fully work on their own, for example rockets. Most weapons will work as long as the m_hOwner netprop on the weapon is set to an existing player. Weapons spawned manually might also need SetClip(-1), and m_flNextPrimaryAttack (or m_flSecondaryPrimaryAttack) set to 0 before calling this function to always allow firing without delays.
Warning.pngWarning:Hitscan and melee weapons require lag compensation information to be present, or the game will crash! Calling this from a player's think function or OnTakeDamage hook (whose source is a player's hitscan weapon) is sufficient. Alternatively, lag compensation can be temporarily disabled which allows calling this function from anywhere, with the side effect of poor hit registration for high latency players. This can be achieved by setting the m_bLagCompensation netprop ↓ on the player to to false, calling this function, and reverting it back to true.
Warning.pngWarning:This will play the weapon's fire sound to everyone except the owner. If the sound is desired, the sound can be played to the owner exclusively via EmitSoundEx. If the sound is not desired, it can be stopped by calling StopSound after this function.
SecondaryAttack void SecondaryAttack() Force a secondary attack.
Warning.pngWarning:See above.
SetClip1 void SetClip1(int amount) Set current ammo in clip1.
SetClip2 void SetClip2(int amount) Set current ammo in clip2.
SetCustomViewModel void SetCustomViewModel(string model_name) Sets a custom view model for this weapon by model name.
SetCustomViewModelModelIndex void SetCustomViewModelModelIndex(int model_index) Sets a custom view model for this weapon by modelindex.
SetSubType void SetSubType(int subtype) Set the weapon subtype.
UsesClipsForAmmo1 bool UsesClipsForAmmo1() Do we use clips for ammo 1?
UsesClipsForAmmo2 bool UsesClipsForAmmo2() Do we use clips for ammo 2?
UsesPrimaryAmmo bool UsesPrimaryAmmo() Do we use primary ammo?
UsesSecondaryAmmo bool UsesSecondaryAmmo() Do we use secondary ammo?
VisibleInWeaponSelection bool VisibleInWeaponSelection() Is this weapon visible in weapon selection?

CBaseFlex

Extends CBaseAnimating ↑

Animated characters who have vertex flex capability (e.g., facial expressions).

Methods

Function Signature Description
PlayScene float PlayScene(string scene_file, float delay) Play the specified .vcd file, causing the related characters to speak and subtitles to play.
Tip.pngTip:Open tf2_misc_dir.vpk and browse the files in scripts/talker/... to find .vcd files. Alternatively, use the rr_debugresponses 1 command with developer 1 to find .vcds from in-game voicelines.

CBaseCombatCharacter

Extends CBaseFlex ↑

Combat entities with similar movement capabilities to a player.

Methods

Function Signature Description
GetLastKnownArea handle GetLastKnownArea() Return the last nav area occupied, NULL if unknown.

See CTFNavArea ↓.

CBasePlayer

Extends CBaseCombatCharacter ↑

Script handle class for player entities.

Methods

Function Signature Description
GetForceLocalDraw bool GetForceLocalDraw() Whether the player is being forced by SetForceLocalDraw to be drawn.
GetPlayerMaxs Vector GetPlayerMaxs() Get a vector containing max bounds of the player in local space. The player's model scale will affect the result.
GetPlayerMins Vector GetPlayerMins() Get a vector containing min bounds of the player in local space. The player's model scale will affect the result.
GetScriptOverlayMaterial string GetScriptOverlayMaterial() Gets the current overlay material set by SetScriptOverlayMaterial.
IsNoclipping bool IsNoclipping() Returns true if the player is in noclip mode.
SetForceLocalDraw void SetForceLocalDraw(bool toggle) Forces the player to be drawn as if they were in thirdperson.
SetScriptOverlayMaterial void SetScriptOverlayMaterial(string material) Sets the overlay material that can't be overriden by other overlays. E.g. Jarate.
SnapEyeAngles void SnapEyeAngles(QAngle angles) Snap the player's eye angles to this.
Note.pngNote:Do not use this if you are setting the angles temporarily and reverting it in the same frame (for example if firing projectiles at a specific angle). This will cause camera jitter in multiplayer. Instead, modify the pl.v_angle netprop and then revert that (which is what the game reads for eye angles internally). Example:

local eye_angles = player.LocalEyeAngles()
NetProps.SetPropVector(player, "pl.v_angle", angles + Vector())

NetProps.SetPropEntity(flaregun, "m_hOwner", player)
NetProps.SetPropFloat(flaregun, "m_flNextPrimaryAttack", 0)
flaregun.PrimaryAttack()

NetProps.SetPropVector(player, "pl.v_angle", eye_angles + Vector())
ViewPunch void ViewPunch(QAngle angle_offset) Ow! Punches the player's view.
ViewPunchReset void ViewPunchReset(float tolerance) Reset's the player's view punch if the offset stays below the given tolerance.

CBaseMultiplayerPlayer

Extends CBasePlayer ↑

Script handle sub-class for player entities in multiplayer games. No additional methods.


CEconEntity

Extends CBaseAnimating ↑

Script handle class for economic exquisite equippables, meaning hats and weapons.

Methods

Function Signature Description
AddAttribute void AddAttribute(string name, float value, float duration) Add an attribute to the entity. Set duration to 0 or lower for the attribute to be applied forever See the bug below. The attribute must be one that exists in the game, invalid ones will not be added.
Note.pngNote:For players the attribute functions are named AddCustomAttribute, GetCustomAttribute, and RemoveCustomAttribute.
Icon-Bug.pngBug:This method will always produce attributes with infinite duration, making the duration parameter non-functional.
Warning.pngWarning:Some integer-valued attributes aren't being casted from floating point input number to an integer correctly. The game doesn't do a smart conversion from float to an integer (e.g. 230.0 -> 230), instead it just takes a bit representation of the input value and simply does a data type change (so 230.0 would actually become 1130758144, while they look a lot different in decimal, the bit representation of both numbers is the exact same). You're not allowed to pass in an integer as a value and the Squirrel does smart conversion to a float if you try to do so. The workaround is to wrap your integer value into casti2f which would do the same literal type change, but now from integer to the float, allowing the game to read it properly afterwards.
weapon.AddAttribute("paintkit_proto_def_index", casti2f(230), 0)
GetAttribute float GetAttribute(string name, float default_value) Get an attribute float from the entity. If the attribute does not exist, returns default_value.
Warning.pngWarning:See above, but in this case to receive the proper integer value use castf2i. Also make sure to restrict the number to 32 bit:
castf2i(weapon.GetAttribute("paintkit_proto_def_index", 0.0)) & 0xFFFFFFFF
RemoveAttribute void RemoveAttribute(string name) Remove an attribute from the entity.
Note.pngNote:Static attributes (i.e. attributes that exist by default on the item) cannot be removed with this method.
PlacementTip.pngWorkaround:Instead, set m_AttributeManager.m_Item.m_bOnlyIterateItemViewAttributes netprop ↓ to true to remove all static attributes from the item. This allows for re-application of attributes.
ReapplyProvision void ReapplyProvision() Relinks attributes to provisioners, e.g. calling this on a weapon will add it's attributes to the player.

CTFPlayer

Extends CBaseMultiplayerPlayer ↑

Script handle class for player entities of Team Fortress 2.

Methods

Function Signature Description
AddCond void AddCond(ETFCond cond)
AddCondEx void AddCondEx(ETFCond cond, float duration, handle provider)
AddCurrency void AddCurrency(int amount) Kaching! Give the player some cash for game modes with upgrades, ie. MvM. The new value is bounded between 0-30000.
Note.pngNote:Using RemoveCurrency/SetCurrency instead or setting the m_nCurrency netprop directly will bypass the bounds checking.
AddCustomAttribute void AddCustomAttribute(string name, float value, float duration) Add a custom attribute to the player. Set duration to 0 or lower for the attribute to be applied forever. The attribute must be one that exists in the game, invalid ones will not be added.
Note.pngNote:This does not work when applied in the player_spawn event, because custom attributes are cleared immediately after the event. As a workaround, it can be applied with a delay. See the example code.
Note.pngNote:For weapons and cosmetics, the attribute functions are named AddAttribute, GetAttribute, and RemoveAttribute.
AddHudHideFlags void AddHudHideFlags(FHideHUD flags) Hides a hud element(-s).
ApplyPunchImpulseX bool ApplyPunchImpulseX(float impulse) Apply a view punch along the pitch angle. Used to flinch players when hit. If the player is a fully charged scoped-in sniper and the weapon has the aiming_no_flinch attribute, the punch will not apply. Returns true if the punch was applied.
BleedPlayer void BleedPlayer(float duration) Make a player bleed for a set duration of time.
BleedPlayerEx void BleedPlayerEx(float duration, int damage, bool endless, ETFDmgCustom custom_damage_type) Make a player bleed for a set duration of time, or forever, with specific damage per tick and damage_custom index.
CancelTaunt void CancelTaunt() Cancels any taunt in progress.
CanAirDash bool CanAirDash() Can the player air dash/double jump?
CanBeDebuffed bool CanBeDebuffed()
CanBreatheUnderwater bool CanBreatheUnderwater()
CanDuck bool CanDuck() Can the player duck?
CanGetWet bool CanGetWet() Can the player get wet by jarate/milk?
CanJump bool CanJump() Can the player jump? Returns false if the player is taunting or if the no_jump attribute is present and non-zero. There is other conditions that prevent jumping but this function by itself doesn't check those.
ClearCustomModelRotation void ClearCustomModelRotation()
ClearSpells void ClearSpells()
ClearTauntAttack void ClearTauntAttack() Stops active taunt from damaging or cancels Rock-Paper-Scissors result.
CanPlayerMove bool CanPlayerMove() Can the player move?
DoTauntAttack void DoTauntAttack() Performs taunts attacks if available. Player must be already taunting and taunt must have a valid attack assigned (taunt attack name attribute).
DropFlag void DropFlag(bool silent) Force player to drop the flag (intelligence).
DropRune void DropRune(bool apply_force, ETFTeam team) Force player to drop the rune.
Tip.pngTip:This can be abused to spawn arbitrary Mannpower powerups. See the example.
EndLongTaunt void EndLongTaunt() Stops a looping taunt (obeys minimum time rules and plays outro animation if available).
EquipWearableViewModel void EquipWearableViewModel(handle entity) Equips a wearable on the viewmodel. Intended to be used with tf_wearable_vm entities.
ExtinguishPlayerBurning void ExtinguishPlayerBurning()
FiringTalk void FiringTalk() Makes eg. a heavy go AAAAAAAAAAaAaa like they are firing their minigun.
Note.pngNote:This only works in a few situations as it requires certain gameplay conditions to be true. An example of when this will work: when the player is invulnerable.
Icon-Bug.pngBug:Unfortunately does not work for Heavy's minigun due to the above quirk.
PlacementTip.pngWorkaround:The input SpeakResponseConcept can be used to play voicelines by supplying a Concept.
ForceChangeTeam void ForceChangeTeam(ETFTeam team, bool full_team_switch) Force player to change their team. Setting the bool to true will not remove nemesis relationships or reset the player's class, as well as not slaying the player.
Note.pngNote:This will not work if a player is in a duel. Setting the m_bIsCoaching netprop ↓ to true on the player and reverting it afterwards is a workaround.
ForceRegenerateAndRespawn void ForceRegenerateAndRespawn() Force regenerates and respawns the player.
Note.pngNote:This will not work if the player does not have a desired class set. This can be worked around by setting the m_Shared.m_iDesiredPlayerClass netprop to a class index.
ForceRespawn void ForceRespawn() Force respawns the player.
Note.pngNote:This will not work if the player does not have a desired class set. This can be worked around by setting the m_Shared.m_iDesiredPlayerClass netprop to a class index.
GetActiveWeapon CTFWeapon GetActiveWeapon() Get the player's current weapon.
GetBackstabs int GetBackstabs()
GetBonusPoints int GetBonusPoints()
GetBotType int GetBotType()
GetBuildingsDestroyed int GetBuildingsDestroyed()
GetCaptures int GetCaptures()
GetClassEyeHeight Vector GetClassEyeHeight() Gets the eye height of the player.
GetCondDuration float GetCondDuration(ETFCond cond) Returns duration of the condition. Returns 0 if the cond is not applied. Returns -1 if the cond is infinite.
GetCustomAttribute float GetCustomAttribute(string name, float default_value) Get an attribute float from the player. If the attribute does not exist, returns default_value.
GetCurrency int GetCurrency() Get player's cash for game modes with upgrades, ie. MvM.
GetCurrentTauntMoveSpeed float GetCurrentTauntMoveSpeed()
GetDefenses int GetDefenses()
GetDisguiseAmmoCount int GetDisguiseAmmoCount()
GetDisguiseTarget CTFPlayer GetDisguiseTarget()
GetDisguiseTeam int GetDisguiseTeam()
GetDominations int GetDominations()
GetGrapplingHookTarget handle GetGrapplingHookTarget() What entity is the player grappling?
GetHeadshots int GetHeadshots()
GetHealPoints int GetHealPoints()
GetHealTarget handle GetHealTarget() Who is the medic healing?
GetHudHideFlags int GetHudHideFlags() Gets current hidden hud elements.

See Constants.FHideHUD.

GetInvulns int GetInvulns()
GetKillAssists int GetKillAssists()
GetLastWeapon CTFWeapon GetLastWeapon()
GetNextChangeClassTime float GetNextChangeClassTime() Get next change class time.
GetNextChangeTeamTime float GetNextChangeTeamTime() Get next change team time.
GetNextRegenTime float GetNextRegenTime() Get next health regen time.
GetPlayerClass int GetPlayerClass()
GetRageMeter float GetRageMeter()
GetResupplyPoints int GetResupplyPoints()
GetRevenge int GetRevenge()
GetScoutHypeMeter float GetScoutHypeMeter()
GetSpyCloakMeter float GetSpyCloakMeter()
GetTeleports int GetTeleports()
GetTauntAttackTime float GetTauntAttackTime() Timestamp until a taunt attack "lasts". 0 if unavailable.
GetTauntRemoveTime float GetTauntRemoveTime() Timestamp until taunt is stopped.
GetVehicleReverseTime float GetVehicleReverseTime() Timestamp when kart was reversed.
GetTimeSinceCalledForMedic float GetTimeSinceCalledForMedic() When did the player last call medic.
GrantOrRemoveAllUpgrades void GrantOrRemoveAllUpgrades(bool remove, bool refund)
HasItem bool HasItem() Currently holding an item? Eg. capture flag.
Tip.pngTip:Fetch the m_hItem netprop to get the entity handle.
HandleTauntCommand void HandleTauntCommand(int taunt_slot) Spoofs a taunt command from the player, as if they selected this taunt. This can be abused to give the player any taunt, see the examples page.
IgnitePlayer void IgnitePlayer() Supposed to set the player on fire, but...
Icon-Bug.pngBug:Does nothing except play on-fire sound and voicelines.
PlacementTip.pngWorkaround:Create a trigger_ignite and EntFire StartTouch input on it.
InAirDueToExplosion bool InAirDueToExplosion()
InAirDueToKnockback bool InAirDueToKnockback()
InCond bool InCond(ETFCond cond)
IsAirDashing bool IsAirDashing()
IsAllowedToRemoveTaunt bool IsAllowedToRemoveTaunt() Returns true if the taunt will be stopped.
IsAllowedToTaunt bool IsAllowedToTaunt()
IsBotOfType bool IsBotOfType(EBotType type) Returns true if the player matches this bot type. Only one type of bot exists which is reserved for AI bots (not puppet bots). 0 is used for real players or puppet bots. Use IsFakeClient to check for a puppet bot instead.
IsCallingForMedic bool IsCallingForMedic() Is this player calling for medic?
IsCarryingRune bool IsCarryingRune()
IsControlStunned bool IsControlStunned()
IsCritBoosted bool IsCritBoosted()
IsFakeClient bool IsFakeClient() Returns true if the player is a puppet or AI bot. To check if the player is a AI bot (CTFBot) specifically, use IsBotOfType instead.
IsFireproof bool IsFireproof()
IsFullyInvisible bool IsFullyInvisible()
IsHypeBuffed bool IsHypeBuffed()
IsImmuneToPushback bool IsImmuneToPushback()
IsInspecting bool IsInspecting()
IsInvulnerable bool IsInvulnerable()
IsJumping bool IsJumping()
IsMiniBoss bool IsMiniBoss() Is this player an MvM mini-boss?
IsParachuteEquipped bool IsParachuteEquipped()
IsPlacingSapper bool IsPlacingSapper() Returns true if we placed a sapper in the last few moments.
IsRageDraining bool IsRageDraining()
IsRegenerating bool IsRegenerating()
IsSapping bool IsSapping() Returns true if we are currently sapping.
IsSnared bool IsSnared()
IsStealthed bool IsStealthed()
IsTaunting bool IsTaunting()
IsUsingActionSlot bool IsUsingActionSlot()
IsViewingCYOAPDA bool IsViewingCYOAPDA()
Regenerate void Regenerate(bool refill_health_ammo) Resupplies a player. If refill health/ammo is set, clears negative conds, gives back player health/ammo.
RemoveAllItems void RemoveAllItems(bool unused)
Icon-Bug.pngBug:This does not actually remove all items. It only drops the passtime ball, intelligence, disables radius healing, and hides the Spy invis watch.
PlacementTip.pngWorkaround:Iterate through player's children, and destroy subclass instances of CEconEntity.

function RemoveAllItems(player)
{
	// If you destroy an entity it becomes invalid
	// It will not longer keep a track of the next child and .NextMovePeer method becomes unavailable so the next iteration will fail
	// To prevent this you can store a reference the next child
	for (local next, current = player.FirstMoveChild(); current != null; current = next)
	{
		NetProps.SetPropBool(current, "m_bForcePurgeFixedupStrings", true)
		// Store the next handle
		next = current.NextMovePeer()
		if (current instanceof CEconEntity)
			current.Destroy()
	}
}

//Example
RemoveAllItems(GetListenServerHost())
RemoveAllObjects void RemoveAllObjects(bool explode) Remove all player objects. Eg. dispensers/sentries.
RemoveCond void RemoveCond(ETFCond cond) Removes a condition. Does not remove a condition if the minimum duration has not passed. Does nothing if the condition isn't added (interally does InCond check).
RemoveCondEx void RemoveCondEx(ETFCond cond, bool ignore_duration) Extended version of above function. Allows forcefully removing the condition even if minimum duration is not met.
RemoveCurrency void RemoveCurrency(int amount) Take away money from a player for reasons such as ie. spending. Lower bounded to 0.
Note.pngNote:Unlike AddCurrency, negative values will go past the 30000 limit.
RemoveCustomAttribute void RemoveCustomAttribute(string name) Remove a custom attribute to the player.
RemoveDisguise void RemoveDisguise() Undisguise a spy.
RemoveHudHideFlags void RemoveHudHideFlags(FHideHUD flags) Unhides a hud element(-s).
RemoveInvisibility void RemoveInvisibility() Un-invisible a spy.
RemoveTeleportEffect void RemoveTeleportEffect()
ResetScores void ResetScores()
RollRareSpell void RollRareSpell()
SetCondDuration void SetCondDuration(ETFCond cond, float duration)
SetCurrency void SetCurrency(int amount) Set player's cash for game modes with upgrades, ie. MvM. Does not have any bounds checking.
SetCurrentTauntMoveSpeed void SetCurrentTauntMoveSpeed(float speed)
SetCustomModel void SetCustomModel(string model_name) Sets a custom player model without animations (model will T-pose). To enable animations, use SetCustomModelWithClassAnimations instead.
SetCustomModelOffset void SetCustomModelOffset(Vector offset)
SetCustomModelRotates void SetCustomModelRotates(bool toggle)
SetCustomModelRotation void SetCustomModelRotation(QAngle angles)
SetCustomModelVisibleToSelf void SetCustomModelVisibleToSelf(bool toggle)
SetCustomModelWithClassAnimations void SetCustomModelWithClassAnimations(string model_name) Sets a custom player model with full animations.
SetDisguiseAmmoCount void SetDisguiseAmmoCount(int count)
SetForcedTauntCam void SetForcedTauntCam(int toggle)
SetGrapplingHookTarget void SetGrapplingHookTarget(handle entity, bool bleed) Set the player's target grapple entity.
SetHudHideFlags void SetHudHideFlags(FHideHUD flags) Force hud hide flags to a value.
SetIsMiniBoss void SetIsMiniBoss(bool toggle) Make this player an MvM mini-boss.
SetNextChangeClassTime void SetNextChangeClassTime(float time) Set next change class time.
SetNextChangeTeamTime void SetNextChangeTeamTime(float time) Set next change team time.
SetNextRegenTime void SetNextRegenTime(float time) Set next available resupply time.
SetPlayerClass void SetPlayerClass(ETFClass class_index) Sets the player class. Updates the player's visuals and model.
Note.pngNote:Does not force the class to be changed and can be buggy for server-side scripts. This can be resolved by calling NetProps.SetPropInt(player, "m_Shared.m_iDesiredPlayerClass", class_index) after SetPlayerClass and before ForceRegenerateAndRespawn. This resolves issues like the player respawning as their "desired" class instead or loadout showing the desired class rather than what they are.
Note.pngNote:Does not regenerate class properties, such as health or weapons. This can be done by calling ForceRegenerateAndRespawn afterwards.
Warning.pngWarning:If the player is not respawned, the hitbox set will be used from the old class! Calling SetCustomModel with a blank parameter is sufficient to update it.
SetRageMeter void SetRageMeter(float percent) Sets rage meter from 0 - 100.
SetRPSResult void SetRPSResult(int result) Rig the result of Rock-Paper-Scissors (0 - rock, 1 - paper, 2 - scissors).
SetScoutHypeMeter void SetScoutHypeMeter(float percent) Sets hype meter from 0 - 100.
SetSpyCloakMeter void SetSpyCloakMeter(float) Sets cloakmeter from 0 - 100.
SetVehicleReverseTime void SetVehicleReverseTime(float time) Set the timestamp when kart was reversed.
SetUseBossHealthBar void SetUseBossHealthBar(bool toggle)
StopTaunt void StopTaunt(bool remove_prop) Stops current taunt. If remove_prop is true, the taunt prop will be immediately deleted instead of potentially delaying.
StunPlayer void StunPlayer(float duration, float move_speed_reduction, TF_STUN flags, handle attacker) Stuns the player for a specified duration. Move speed reduction is a fraction (0 = no reduction. 1 = total reduction, no movement). Flag combinations control the stun type and behavior.
Tip.pngTip:To produce "scared" particle effects and sounds use the combination TF_STUN_LOSER_STATE|TF_STUN_BY_TRIGGER as stun flags.
Taunt void Taunt(FTaunts taunt_index, MP_CONCEPT taunt_concept) Performs a taunt if allowed. Concept is the "voiceline" index to use with the taunt. For TAUNT_SHOW_ITEM and TAUNT_BASE_WEAPON this is set automatically. TAUNT_LONG is not supported.
Tip.pngTip:TAUNT_MISC_ITEM with a concept of MP_CONCEPT_TAUNT_LAUGH will make the player laugh. Concept MP_CONCEPT_TAUNT_REPLAY will play the replay taunt.
Tip.pngTip:To perform any taunt such as conga, see the examples page.
TryToPickupBuilding bool TryToPickupBuilding() Make the player attempt to pick up a building in front of them.
UpdateSkin void UpdateSkin(int skin)
WasInCond bool WasInCond(ETFCond cond)
Weapon_CanUse bool Weapon_CanUse(CTFWeapon weapon)
Weapon_Drop void Weapon_Drop(CTFWeapon weapon) Does nothing!
Weapon_DropEx void Weapon_DropEx(CTFWeapon weapon, Vector target, Vector velocity) Does nothing!
Weapon_Equip void Weapon_Equip(CTFWeapon weapon) Equips a weapon in the player. This places it inside the m_hMyWeapons array.
Weapon_SetLast void Weapon_SetLast(CTFWeapon weapon)
Weapon_ShootPosition Vector Weapon_ShootPosition() The same as calling EyePosition.
Note.pngNote:While the weapon shoot position matches with eye position for hitscan and melee weapons, it does not reflect the actual shoot position of most projectile weapons since they have an additional offset from the eye location. To get the exact shoot position you can use the following function:

function GetWeaponShootPosition(player)
{
	local weapon = player.GetActiveWeapon()
	local offset = null

	switch (NetProps.GetPropInt(weapon, "m_AttributeManager.m_Item.m_iItemDefinitionIndex"))
	{
	case 441: // The Cow Mangler
		offset = Vector(23.5, 8.0, player.GetFlags() & Constants.FPlayer.FL_DUCKING ? 8.0 : -3.0)
		break
	case 513: // The Original
		offset = Vector(23.5, 0.0, player.GetFlags() & Constants.FPlayer.FL_DUCKING ? 8.0 : -3.0)
		break
	case 18: // Rocket Launcher
	case 127: // The Direct Hit
	case 1104: // The Air Strike
	case 205: // Rocket Launcher (Renamed/Strange)
	case 228: // The Black Box
	case 237: // Rocket Jumper
	case 414: // The Liberty Launcher
	case 658: // Festive Rocket Launcher
	case 730: // The Beggar's Bazooka
	case 800: // Silver Botkiller Rocket Launcher Mk.I
	case 809: // Gold Botkiller Rocket Launcher Mk.I
	case 889: // Rust Botkiller Rocket Launcher Mk.I
	case 898: // Blood Botkiller Rocket Launcher Mk.I
	case 907: // Carbonado Botkiller Rocket Launcher Mk.I
	case 916: // Diamond Botkiller Rocket Launcher Mk.I
	case 965: // Silver Botkiller Rocket Launcher Mk.II
	case 974: // Gold Botkiller Rocket Launcher Mk.II
	case 1085: // Festive Black Box
	case 15006: // Woodland Warrior
	case 15014: // Sand Cannon
	case 15028: // American Pastoral
	case 15043: // Smalltown Bringdown
	case 15052: // Shell Shocker
	case 15057: // Aqua Marine
	case 15081: // Autumn
	case 15104: // Blue Mew
	case 15105: // Brain Candy
	case 15129: // Coffin Nail
	case 15130: // High Roller's
	case 15150: // Warhawk
	case 39: // The Flare Gun
	case 351: // The Detonator
	case 595: // The Manmelter
	case 740: // The Scorch Shot
	case 1081: // Festive Flare Gun
		offset = Vector(23.5, 12.0, player.GetFlags() & Constants.FPlayer.FL_DUCKING ? 8.0 : -3.0)
		break
	case 56: // Hunstman
	case 1005: // Festive Huntsman
	case 1092: // The Fortified Compound
	case 997: // Rescue Ranger
	case 305: // Crusader's Crossbow
	case 1079: // Festive Crusader's Crossbow
		offset = Vector(23.5, 12.0, -3.0)
		break
	case 442: // The Righteous Bison
	case 588: // The Pomson 6000
		offset = Vector(23.5, 8.0, player.GetFlags() & Constants.FPlayer.FL_DUCKING ? 8.0 : -3.0)
		break
	case 222: // The Mad Milk
	case 1121: // Mutated Milk
	case 1180: // Gas Passer
	case 58: // Jarate
	case 751: // Festive Jarate
	case 1105: // The Self-Aware Beauty Mark
	case 19: // Grenade Launcher
	case 206: // Grenade Launcher (Renamed/Strange)
	case 308: // The Loch-n-Load
	case 996: // The Loose Cannon
	case 1007: // Festive Grenade Launcher
	case 1151: // The Iron Bomber
	case 15077: // Autumn
	case 15079: // Macabre Web
	case 15091: // Rainbow
	case 15092: // Sweet Dreams
	case 15116: // Coffin Nail
	case 15117: // Top Shelf
	case 15142: // Warhawk
	case 15158: // Butcher Bird
	case 20: // Stickybomb Launcher
	case 207: // Stickybomb Launcher (Renamed/Strange)
	case 130: // The Scottish Resistance
	case 265: // Sticky Jumper
	case 661: // Festive Stickybomb Launcher
	case 797: // Silver Botkiller Stickybomb Launcher Mk.I
	case 806: // Gold Botkiller Stickybomb Launcher Mk.I
	case 886: // Rust Botkiller Stickybomb Launcher Mk.I
	case 895: // Blood Botkiller Stickybomb Launcher Mk.I
	case 904: // Carbonado Botkiller Stickybomb Launcher Mk.I
	case 913: // Diamond Botkiller Stickybomb Launcher Mk.I
	case 962: // Silver Botkiller Stickybomb Launcher Mk.II
	case 971: // Gold Botkiller Stickybomb Launcher Mk.II
	case 1150: // The Quickiebomb Launcher
	case 15009: // Sudden Flurry
	case 15012: // Carpet Bomber
	case 15024: // Blasted Bombardier
	case 15038: // Rooftop Wrangler
	case 15045: // Liquid Asset
	case 15048: // Pink Elephant
	case 15082: // Autumn
	case 15083: // Pumpkin Patch
	case 15084: // Macabre Web
	case 15113: // Sweet Dreams
	case 15137: // Coffin Nail
	case 15138: // Dressed to Kill
	case 15155: // Blitzkrieg
		offset = Vector(16.0, 8.0, -6.0)
		break
	case 17: // Syringe Gun
	case 204: // Syringe Gun (Renamed/Strange)
	case 36: // The Blutsauger
	case 412: // The Overdose
		offset = Vector(16.0, 6.0, -8.0)
		break
	case 812: // The Flying Guillotine
	case 833: // The Flying Guillotine (Genuine)
		offset = Vector(32.0, 0.0, 15.0)
		break
	case 528: // The Short Curcuit
		offset = Vector(40.0, 15.0, -10.0)
		break
	case 44: // Sandman
	case 648: // The Wrap Assassin
		return player.GetOrigin() + player.GetModelScale() *
				(player.EyeAngles().Forward() * 32.0 + Vector(0.0, 0.0, 50.0))
	default:
		return player.EyePosition()
	}

	if (Convars.GetClientConvarValue("cl_flipviewmodels", player.entindex()) == "1")
		offset.y *= -1

	local eye_angles = player.EyeAngles()
	return player.EyePosition() +
			eye_angles.Up() * offset.z +
			eye_angles.Left() * offset.y +
			eye_angles.Forward() * offset.x
}

// Example usage
// Works only for the rocket launchers
local player = GetListenServerHost()
local eye_position = player.EyePosition()
local shoot_position = GetWeaponShootPosition(player)
local eye_vector = player.EyeAngles().Forward()

local trace =
{
	start = shoot_position
	end = eye_position + eye_vector * 32768.0
	ignore = player
	hullmin = Vector(-1.0, -1.0, -1.0)
	hullmax = Vector(1.0, 1.0, 1.0)
}
TraceHull(trace)

DebugDrawLine(shoot_position, trace.pos, 255, 255, 255, false, 5.0)
DebugDrawBox(trace.pos, Vector(-2.0, -2.0, -2.0), Vector(2.0, 2.0, 2.0), 255, 0, 0, 255, 5.0)
Weapon_Switch void Weapon_Switch(CTFWeapon weapon) Attempts a switch to the given weapon, if present in the player's inventory (m_hMyWeapons array).
Note.pngNote:Most of the time a weapon switch will succeed, except in these circumstances. Workarounds are provided in each case to allow a forced switch.
  • Revved with a minigun
  • Just fired with a sniper rifle
  • Blowing the horn of a banner item
  • Holding Half-Zatoichi and under 50 health
  • Backstab stun from a Razorback
-> Set m_hActiveWeapon netprop on the player to null.
Warning.pngWarning:Do not take the lazy way out and run this workaround for every weapon, it will break other weapons like the Huntsman. Only run this workaround for the specific class of weapons above.
  • Player has TF_COND_CANNOT_SWITCH_FROM_MELEE condition (from eating Buffalo Steak Sandvich) and is holding a melee

-> Remove TF_COND_CANNOT_SWITCH_FROM_MELEE condition.

  • Using the Thermal Thruster:
// assuming "weapon" is the thermal thruster
NetProps.SetPropEntity(player, "m_hActiveWeapon", null)
if (player.InCond(Constants.ETFCond.TF_COND_ROCKETPACK))
{
	// needed to stop air sound
	SendGlobalGameEvent("rocketpack_landed", { userid = GetPlayerUserID(player) })
	player.RemoveCond(Constants.ETFCond.TF_COND_ROCKETPACK)
}

CTFBot

Extends CTFPlayer ↑ and NextBotCombatCharacter ↓

Script handle class for bot-controlled players aka tf_bot. Beep boop.

Note.pngNote:Puppet bots do not inherit from this class.

Methods

Function Signature Description
AddBotAttribute void AddBotAttribute(FTFBotAttributeType attribute) Sets attribute flags on this TFBot.
AddBotTag void AddBotTag(string tag) Adds a bot tag.
AddWeaponRestriction void AddWeaponRestriction(TFBotWeaponRestrictionType flags) Adds weapon restriction flags.
ClearAllBotAttributes void ClearAllBotAttributes() Clears all attribute flags on this TFBot.
ClearAllBotTags void ClearAllBotTags() Clears bot tags.
ClearAllWeaponRestrictions void ClearAllWeaponRestrictions() Removes all weapon restriction flags.
ClearAttentionFocus void ClearAttentionFocus() Clear current focus.
ClearBehaviorFlag void ClearBehaviorFlag(TFBOT_BEHAVIOR flags) Clear the given behavior flag(s) for this bot.
DelayedThreatNotice void DelayedThreatNotice(handle threat, float delay) Notice the threat after a delay in seconds.
DisbandCurrentSquad void DisbandCurrentSquad() Forces the current squad to be entirely disbanded by everyone.
FindVantagePoint CTFNavArea FindVantagePoint(float max_distance) Get the nav area of the closest vantage point (within distance).
GenerateAndWearItem void GenerateAndWearItem(string item_name) Give me an item!
GetActionPoint handle GetActionPoint() Get the given action point for this bot.
GetAllBotTags void GetAllBotTags(table result) Get all bot tags. The key is the index, and the value is the tag.
GetHomeArea CTFNavArea GetHomeArea() Sets the home nav area of the bot.
GetDifficulty int GetDifficulty() Returns the bot's difficulty level. See Constants.ETFBotDifficultyType.
GetMaxVisionRangeOverride float GetMaxVisionRangeOverride() Gets the max vision range override for the bot
Warning.pngWarning:MaxVisionRange overrides, as well as certain other bot modifiers, can persist after a bot has been moved to spectator and assigned a new class/loadout in MvM! Identifying MvM bots by the MaxVisionRange override set in a popfile may not be reliable.
GetMission int GetMission() Get this bot's current mission. See ETFBotMissionType.
GetMissionTarget handle GetMissionTarget() Get this bot's current mission target.
GetNearestKnownSappableTarget handle GetNearestKnownSappableTarget() Gets the nearest known sappable target.
GetPrevMission int GetPrevMission() Get this bot's previous mission. See ETFBotMissionType.
GetSpawnArea CTFNavArea GetSpawnArea() Return the nav area of where we spawned.
GetSquadFormationError float GetSquadFormationError() Gets our formation error coefficient.
HasBotAttribute bool HasBotAttribute(FTFBotAttributeType attribute) Checks if this TFBot has the given attributes.
HasBotTag bool HasBotTag(string tag) Checks if this TFBot has the given bot tag.
HasMission bool HasMission(ETFBotMissionType mission) Return true if the given mission is this bot's current mission.
HasWeaponRestriction bool HasWeaponRestriction(TFBotWeaponRestrictionType flags) Checks if this TFBot has the given weapon restriction flags.
IsAmmoFull bool IsAmmoFull()
IsAmmoLow bool IsAmmoLow()
IsAttentionFocused bool IsAttentionFocused() Is our attention focused right now?
IsAttentionFocusedOn bool IsAttentionFocusedOn(handle entity) Is our attention focused on this entity.
IsBehaviorFlagSet bool IsBehaviorFlagSet(TFBOT_BEHAVIOR flags) Return true if the given behavior flag(s) are set for this bot.
IsDifficulty bool IsDifficulty(ETFBotDifficultyType difficulty) Returns true/false if the bot's difficulty level matches.
IsInASquad bool IsInASquad() Checks if we are in a squad.
IsOnAnyMission bool IsOnAnyMission() Return true if this bot has a current mission.
IsWeaponRestricted bool IsWeaponRestricted(handle weapon) Checks if the given weapon is restricted for use on the bot.
LeaveSquad void LeaveSquad() Makes us leave the current squad (if any).
PressAltFireButton void PressAltFireButton(float duration = -1)
PressFireButton void PressFireButton(float duration = -1)
PressSpecialFireButton void PressSpecialFireButton(float duration = -1)
RemoveBotAttribute void RemoveBotAttribute(FTFBotAttributeType attribute) Removes attribute flags on this TFBot.
RemoveBotTag void RemoveBotTag(string tag) Removes a bot tag.
RemoveWeaponRestriction void RemoveWeaponRestriction(TFBotWeaponRestrictionType flags) Removes weapon restriction flags.
SetActionPoint void SetActionPoint(handle entity) Set the given action point for this bot.
SetAttentionFocus void SetAttentionFocus(handle entity) Sets our current attention focus to this entity.
SetAutoJump void SetAutoJump(float min_time, float max_time) Sets if the bot should automatically jump, and how often.
SetBehaviorFlag void SetBehaviorFlag(TFBOT_BEHAVIOR flags) Set the given behavior flag(s) for this bot.
SetDifficulty void SetDifficulty(ETFBotDifficultyType difficulty) Sets the bots difficulty level.
SetHomeArea void SetHomeArea(CTFNavArea area) Set the home nav area of the bot, may be null.
SetMaxVisionRangeOverride void SetMaxVisionRangeOverride(float range) Sets max vision range override for the bot.
SetMission void SetMission(ETFBotMissionType mission, bool reset_behavior) Set this bot's current mission to the given mission.
SetMissionTarget void SetMissionTarget(handle entity) Set this bot's mission target to the given entity.
SetPrevMission void SetPrevMission(ETFBotMissionType mission) Set this bot's previous mission to the given mission.
SetScaleOverride void SetScaleOverride(float scale) Sets the scale override for the bot.
SetShouldQuickBuild void SetShouldQuickBuild(bool toggle) Sets if the bot should build instantly.
SetSquadFormationError void SetSquadFormationError(float coefficient) Sets our formation error coefficient.
ShouldAutoJump bool ShouldAutoJump() Returns if the bot should automatically jump.
ShouldQuickBuild bool ShouldQuickBuild() Returns if the bot should build instantly.
UpdateDelayedThreatNotices void UpdateDelayedThreatNotices()

CTFBaseBoss

Extends NextBotCombatCharacter ↓

Base class intended for custom NPCs. Officially this is only used as part of MvM tank.

Methods

Function Signature Description
SetResolvePlayerCollisions void SetResolvePlayerCollisions(bool toggle) Sets whether the entity should push away players intersecting its bounding box. On by default.
Note.pngNote:There's more methods in input form. See base_boss page.

Convars

Game Instance: Convars

An interface to manipulate the convars on the server.

Note.pngNote:Protected convars (e.g. rcon_password) cannot be accessed.

Methods

Function Signature Description
GetBool bool GetBool(string name) Returns the convar as a bool. May return null if no such convar.
GetClientConvarValue string GetClientConvarValue(string name, int entindex) Returns the convar value for the entindex as a string. Only works on client convars with the FCVAR_USERINFO flag.
Tip.pngTip:The list of available client convars can be printed in console using the findflags USERINFO command.
Note.pngNote:Notable client convars available:
  • cl_autoreload : Whether the client wants autoreload after each shot
  • cl_autorezoom : Whether the client wants auto scope-in after firing a sniper rifle
  • cl_connectmethod : How the client joined the server. E.g. listenserver, serverbrowser_internet, serverbrowser_favorites
    Todo: List all of them
  • cl_flipviewmodels : Whether the client has flipped viewmodels
  • cl_language : The client's language setting
  • cl_spec_mode : Currently observer mode, corresponds to the ESpectatorMode.
  • fov_desired : The client's FOV
  • hud_classautokill : If the client wants to suicide after choosing a new class
  • hud_combattext : Whether damage numbers are enabled
  • name : The client's name
  • closecaption : Whether the client has closed captions enabled.
GetInt int GetInt(string name) Returns the convar as an int. May return null if no such convar.
Warning.pngWarning:The entire convar list is searched each time this is called (which is slow!). If you are going to be using it several times per frame, cache off the result.
GetStr string GetStr(string name) Returns the convar as a string. May return null if no such convar. Returns hunter2 if a protected convar is accessed.
Warning.pngWarning:See above.
GetFloat float GetFloat(string name) Returns the convar as a float. May return null if no such convar.
Warning.pngWarning:See above.
IsConVarOnAllowList bool IsConVarOnAllowList(string name) Checks if the convar is allowed to be used and is in cfg/vscript_convar_allowlist.txt. Please be nice with this and use it for *compatibility* if you need check support and NOT to force server owners to allow hostname to be set... or else this will simply lie and return true in future. ;-) You have been warned!
SetValue void SetValue(string name, any value) Sets the value of the convar. The convar must be in cfg/vscript_convar_allowlist.txt to be set. Convars marked as cheat-only can be set even if sv_cheats is off. Convars marked as dev-only (i.e. not visible in console) can also be set. Supported types are bool, int, float, string. The original value of the convar is saved and is reset on map change, in other words convar changes will not persist across maps.
Warning.pngWarning:For changes intended to persist for the whole map, set these at the start of each round instead of only once. Otherwise, custom server configs may load after the initial script and not use the correct settings.

CEntities

Game Instance: Entities

An interface to find and iterate over the script handles for the entities in play. To iterate over a set of entities, pass null to the previous parameter in the appropriate method to start an iteration. A reference to a previously-found entity can be used instead to continue a search.

The following are two equivalent examples and iterate over all weapons on the map:

local ent = null
while ( ent = Entities.FindByClassname(ent, "tf_weapon_*") )
{
  // ...
}
for (local ent; ent = Entities.FindByName(ent, "tf_weapon_*"); )
{
  // ...
}
Note.pngNote:
  • The variable name ent is arbitrary.
  • Indeed, we mean "=" and not "==" in the loop conditions! The loops end if ent becomes null, which happens when no matching entities have an entity index higher to the one in previous parameter.
  • Semicolons are optional, except in the header of the for statement.
  • The string parameters of the FindBy... functions support the wildcard star *. In the above example, FindByClassname only returns either a handle of an entity whose classname begins with "tf_weapon_" or it returns null.

Methods

Function Signature Description
CreateByClassname handle CreateByClassname(string classname) Creates an entity by classname.
Tip.pngTip:Example usage:
local prop = Entities.CreateByClassname("prop_dynamic")
DispatchSpawn void DispatchSpawn(handle entity) Dispatches spawn of an entity! Use this on entities created via CreateByClassname to actually spawn them into the world.
Note.pngNote:Calling this on players will cause them to respawn. In Counter-Strike: Source, set the m_iPlayerState netprop to 0 before calling this to fully respawn.
FindByClassname handle FindByClassname(handle previous, string classname) Find entities by the string of their classname keyvalue. Pass 'null' value to start an iteration, or reference to a previously found entity to continue a search.
Note.pngNote:The classname keyvalue of an entity can be manipulated and does not necessarily reflect its code class. There might be entities that have a different classname than the one they are created with. For example you can spawn a "prop_dynamic" then change its classname to "my_prop", and it will retain the functionality of its code class while also not showing up when searching for "prop_dynamic".
FindByClassnameNearest handle FindByClassnameNearest(string classname, Vector center, float radius) Find entities by classname nearest to a point within a radius.
FindByClassnameWithin handle FindByClassnameWithin(handle previous, string classname, Vector center, float radius) Find entities by classname within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
FindByModel handle FindByModel(handle previous, string model_name) Find entities by the string of their model keyvalue. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
FindByName handle FindByName(handle previous, string targetname) Find entities by the string of their targetname keyvalue. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
FindByNameNearest handle FindByNameNearest(string targetname, Vector center, float radius) Find entities by targetname nearest to a point within a radius.
FindByNameWithin handle FindByNameWithin(handle previous, string targetname, Vector center, float radius) Find entities by targetname within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
FindByTarget handle FindByTarget(handle previous, string target) Find entities by the string of their target keyvalue.[confirm] Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
FindInSphere handle FindInSphere(handle previous, Vector center, float radius) Find entities within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
First handle First() Begin an iteration over the list of entities. The first entity is always worldspawn.
Next handle Next(handle previous) At the given reference of a previously-found entity, returns the next one after it in the list.

CTFNavArea

Script handle class for areas part of the navigation mesh.

Methods

Function Signature Description
AddIncomingConnection void AddIncomingConnection(CTFNavArea area, ENavDirType dir) Add areas that connect TO this area by a ONE-WAY link.
ClearAttributeTF void ClearAttributeTF(FTFNavAttributeType bits) Clear TF-specific area attribute bits.
ComputeClosestPointInPortal Vector ComputeClosestPointInPortal(CTFNavArea to, ENavDirType dir, Vector close_pos) Compute closest point within the "portal" between to an area's direction from the given position.
ComputeDirection int ComputeDirection(Vector point) Return direction from this area to the given point.
ConnectTo void ConnectTo(CTFNavArea area, ENavDirType dir) Connect this area to given area in given direction.
Contains bool Contains(CTFNavArea area) Return true if other area is on or above this area, but no others.
ContainsOrigin bool ContainsOrigin(Vector point) Return true if given point is on or above this area, but no others.
DebugDrawFilled void DebugDrawFilled(int r, int g, int b, int a, float duration, bool no_depth_test, float margin) Draw area as a filled rectangle of the given color.
Disconnect void Disconnect(CTFNavArea area) Disconnect this area from given area.
FindRandomSpot Vector FindRandomSpot() Get random origin within extent of area.
GetAdjacentArea handle GetAdjacentArea(ENavDirType dir, int n) Return the n'th adjacent area in the given direction.
Note.pngNote:'Adjacent area' really means outgoing connection. Adjacent areas don't necessarily have to physically be touching, there can be a height discrepancy (e.g. at a drop ledge).
GetAdjacentAreas void GetAdjacentAreas(ENavDirType dir, table result) Fills a passed in table with all adjacent areas in the given direction.
GetAdjacentCount int GetAdjacentCount(ENavDirType dir) Get the number of adjacent areas in the given direction.
GetAttributes int GetAttributes() Get area attribute bits.

See FNavAttributeType.

GetAvoidanceObstacleHeight float GetAvoidanceObstacleHeight() Returns the maximum height of the obstruction above the ground.
GetCenter Vector GetCenter() Get center origin of area.
GetCorner Vector GetCorner(ENavDirType dir) Get corner origin of area.
GetDistanceSquaredToPoint float GetDistanceSquaredToPoint(Vector pos) Return shortest distance between point and this area.
GetDoor CBaseAnimating GetDoor() Returns the door entity above the area.
GetElevator CBaseAnimating GetElevator() Returns the elevator if in an elevator's path.
GetElevatorAreas void GetElevatorAreas(table result) Fills table with a collection of areas reachable via elevator from this area.
GetID int GetID() Get area ID.
GetIncomingConnections void GetIncomingConnections(ENavDirType dir, table result) Fills a passed in table with areas connected TO this area by a ONE-WAY link (ie: we have no connection back to them).
GetParent CTFNavArea GetParent() Returns the area just prior to this one in the search path.
GetParentHow int GetParentHow() Returns how we get from parent to us.
GetPlaceName string GetPlaceName() Get place name if it exists, null otherwise.
GetPlayerCount int GetPlayerCount(ETFTeam team) Return number of players of given team currently within this area (team of zero means any/all).
GetRandomAdjacentArea CTFNavArea GetRandomAdjacentArea(ENavDirType dir) Return a random adjacent area in the given direction.
GetSizeX float GetSizeX() Return the area size along the X axis.
GetSizeY float GetSizeY() Return the area size along the Y axis.
GetTravelDistanceToBombTarget float GetTravelDistanceToBombTarget() Gets the travel distance to the MvM bomb target.
GetZ float GetZ(Vector pos) Return Z of area at (x,y) of 'pos'.
HasAttributeTF bool HasAttributeTF(FTFNavAttributeType bits) Has TF-specific area attribute bits of the given ones. The name is slightly misleading, think of this one as "HasAttributesTF".
HasAttributes bool HasAttributes(FNavAttributeType bits) Has area attribute bits of the given ones?.
HasAvoidanceObstacle bool HasAvoidanceObstacle(float max_height) Returns true if there's a large, immobile object obstructing this area.
IsBlocked bool IsBlocked(ETFTeam team, bool affects_flow) Return true if team is blocked in this area.
IsBottleneck bool IsBottleneck() Returns true if area is a bottleneck. (tiny narrow areas with only one path).
IsCompletelyVisibleToTeam bool IsCompletelyVisibleToTeam(ETFTeam team) Return true if given area is completely visible from somewhere in this area by someone on the team.
IsConnected bool IsConnected(handle area, ENavDirType dir) Return true if this area is connected to other area in given direction. (If you set direction to -1 or 4, it will automatically check all directions for a connection).
IsCoplanar bool IsCoplanar(handle area) Return true if this area and given. area are approximately co-planar.
IsDamaging bool IsDamaging() Return true if this area is marked to have continuous damage.
IsDegenerate bool IsDegenerate() Return true if this area is badly formed.
IsEdge bool IsEdge(ENavDirType dir) Return true if there are no bi-directional links on the given side.
IsFlat bool IsFlat() Return true if this area is approximately flat.
IsOverlapping bool IsOverlapping(handle area) Return true if 'area' overlaps our 2D extents.
IsOverlappingOrigin bool IsOverlappingOrigin(Vector pos, float tolerance) Return true if 'pos' is within 2D extents of area.
IsPotentiallyVisibleToTeam bool IsPotentiallyVisibleToTeam(ETFTeam team) Return true if any portion of this area is visible to anyone on the given team.
IsReachableByTeam bool IsReachableByTeam(ETFTeam team) Is this area reachable by the given team?
IsRoughlySquare bool IsRoughlySquare() Return true if this area is approximately square.
IsTFMarked bool IsTFMarked() Is this nav area marked with the current marking scope?
IsUnderwater bool IsUnderwater() Return true if area is underwater.
IsValidForWanderingPopulation bool IsValidForWanderingPopulation() Returns true if area is valid for wandering population.
IsVisible bool IsVisible(Vector point) Return true if area is visible from the given eyepoint.
MarkAsBlocked void MarkAsBlocked(ETFTeam team) Mark this area as blocked for team.
MarkAsDamaging void MarkAsDamaging(float duration) Mark this area is damaging for the next 'duration' seconds.
MarkObstacleToAvoid void MarkObstacleToAvoid(float height) Marks the obstructed status of the nav area.
RemoveAttributes void RemoveAttributes(FNavAttributeType bits) Removes area attribute bits.
RemoveOrthogonalConnections void RemoveOrthogonalConnections(ENavDirType dir) Removes all connections in directions to left and right of specified direction.
SetAttributeTF void SetAttributeTF(FTFNavAttributeType bits) Set TF-specific area attributes.
SetAttributes void SetAttributes(FNavAttributeType bits) Set area attribute bits.
SetPlaceName void SetPlaceName(string name) Set place name. If you pass null, the place name will be set to nothing.
TFMark void TFMark() Mark this nav area with the current marking scope.
UnblockArea void UnblockArea() Unblocks this area.

CNavMesh

Game Instance: NavMesh

An interface to collect nav areas from, especially for pathfinding needs.

Methods

Function Signature Description
FindNavAreaAlongRay CTFNavArea FindNavAreaAlongRay(Vector start_pos, Vector end_pos, handle ignore_area) Get nav area from ray.
GetAllAreas void GetAllAreas(table result) Fills a passed in table of all nav areas.
GetAreasWithAttributes void GetAreasWithAttributes(FNavAttributeType bits, table result) Fills a passed in table of all nav areas that have the specified attributes.
GetNavArea CTFNavArea GetNavArea(Vector origin, float beneath) Given a position in the world, return the nav area that is closest to or below that height.
GetNavAreaByID CTFNavArea GetNavAreaByID(int area_id) Get nav area by ID.
GetNavAreaCount int GetNavAreaCount() Return total number of nav areas.
GetNavAreasFromBuildPath bool GetNavAreasFromBuildPath(CTFNavArea start_area, CTFNavArea end_area, Vector goal_pos, float max_path_length, ETFTeam team, bool ignore_nav_blockers, table result) Fills the table with areas from a path. Returns whether a path was found. If 'end_area' is NULL, will compute a path as close as possible to 'goal_pos'.
Note.pngNote:The areas are passed from end area to the start area.
GetNavAreasInRadius void GetNavAreasInRadius(Vector origin, float radius, table result) Fills a passed in table of nav areas within radius.
GetNavAreasOverlappingEntityExtent void GetNavAreasOverlappingEntityExtent(handle entity, table result) Fills passed in table with areas overlapping entity's extent.
GetNearestNavArea CTFNavArea GetNearestNavArea(Vector origin, float max_distance, bool check_los, bool check_ground) Given a position in the world, return the nav area that is closest to or below that height.
GetObstructingEntities void GetObstructingEntities(table result) Fills a passed in table of all obstructing entities.
NavAreaBuildPath bool NavAreaBuildPath(CTFNavArea start_area, CTFNavArea end_erea, Vector goal_pos, float max_path_length, ETFTeam team, bool ignore_nav_blockers) Returns true if a path exists.
NavAreaTravelDistance float NavAreaTravelDistance(CTFNavArea start_area, CTFNavArea end_area, float max_path_length) Compute distance between two areas. Return -1.0 if can't reach 'end_area' from 'start_area'.
RegisterAvoidanceObstacle void RegisterAvoidanceObstacle(handle entity) Registers avoidance obstacle.
UnregisterAvoidanceObstacle void UnregisterAvoidanceObstacle(handle entity) Unregisters avoidance obstacle.

CNetPropManager

Game Instance: NetProps

Allows reading and updating the network properties and data-maps of an entity. A brief explanation: all entities in the game have 2 types of internal properties: networked and saved (called "data" by the game). Networked properties are transmitted to the client, while data properties are a leftover from singleplayer games, which are properties that get saved to a save file (that can be re-loaded later). Some properties may exist in both lists, or one list but not the other and vice versa, so it's best to check both lists. Entities follow an inheritance tree, and they inherit the properties of their parent(s). For organization/optimization purposes, properties also tend to be nested inside "tables".

Netprops nested in a table can be accessed using dot notation similar to a Squirrel table. Example: to access the netprop m_bJumping on a player, you would specify m_Shared.m_bJumping.

Note.pngNote:Sometimes the table structure is figured out automatically and doesn't need to be specified explicitly. The easiest way to check is to use HasProp to see if its correct. For example, LocalWeaponData and LocalActiveWeaponData don't need to be specified. But on the contrary, m_Collision, m_Shared and m_AttributeManager (+ m_Item) must be explicitly specified.
Tip.pngTip:Resources for finding netprops and datamaps of entities:
Warning.pngWarning:Each netprop has a set size in bits, exceeding the size may desync the clients from the server causing unpredictable behavior.
Note.pngNote:Netprops containing the substring EntityQuality or AccountID are banned and cannot be set nor fetched, to prevent spoofing economy items as legitimate.
Tip.pngTip:Run the code below to fold netprop functions for easier and more efficient usage. E.g. NetProps.GetPropInt would simply become GetPropInt.
foreach (name, method in ::NetProps.getclass())
	if (name != "IsValid")
		getroottable()[name] <- method.bindenv(::NetProps)

Methods

Function Signature Description
GetPropArraySize int GetPropArraySize(handle entity, string property_name) Returns the size of an netprop array, or -1.
GetPropEntity handle GetPropEntity(handle entity, string property_name) Reads an EHANDLE-valued netprop (21 bit integer). Returns the script handle of the entity.
GetPropEntityArray handle GetPropEntityArray(handle entity, string property_name, int array_element) Reads an EHANDLE-valued netprop (21 bit integer) from an array. Returns the script handle of the entity.
GetPropBool bool GetPropBool(handle entity, string property_name) Reads a boolean-valued netprop.
GetPropBoolArray bool GetPropBoolArray(handle entity, string property_name, int array_element) Reads a boolean-valued netprop from an array.
GetPropFloat float GetPropFloat(handle entity, string property_name) Reads a float-valued netprop.
GetPropFloatArray float GetPropFloatArray(handle entity, string property_name, int array_element) Reads a float-valued netprop from an array.
GetPropInfo bool GetPropInfo(handle entity, string property_name, int array_element, table result) Fills in a passed table with property info for the provided entity.
GetPropInt int GetPropInt(handle entity, string property_name) Reads an integer-valued netprop.
GetPropIntArray int GetPropIntArray(handle entity, string property_name, int array_element) Reads an integer-valued netprop from an array.
GetPropString string GetPropString(handle entity, string property_name) Reads an string-valued netprop.
GetPropStringArray string GetPropStringArray(handle entity, string property_name, int array_element) Reads an string-valued netprop from an array.
GetPropType string GetPropType(handle entity, string property_name) Returns the name of the netprop type as a string.
GetPropVector Vector GetPropVector(handle entity, string property_name) Reads a 3D vector-valued netprop.
GetPropVectorArray Vector GetPropVectorArray(handle entity, string property_name, int array_element) Reads a 3D vector-valued netprop from an array.
GetTable void GetTable(handle entity, int prop_type, table result) Fills in a passed table with all props of a specified type for the provided entity (set prop_type to 0 for SendTable or 1 for DataMap).
HasProp bool HasProp(handle entity, string property_name) Checks if a netprop exists.
SetPropBool void SetPropBool(handle entity, string property_name, bool value) Sets a netprop to the specified boolean.
SetPropBoolArray void SetPropBoolArray(handle entity, string property_name, bool value, int array_element) Sets a netprop from an array to the specified boolean.
SetPropEntity void SetPropEntity(handle entity, string property_name, handle value) Sets an EHANDLE-valued netprop (21 bit integer) to reference the specified entity.
SetPropEntityArray void SetPropEntityArray(handle entity, string property_name, handle value, int array_element) Sets an EHANDLE-valued netprop (21 bit integer) from an array to reference the specified entity.
SetPropFloat void SetPropFloat(handle entity, string property_name, float value) Sets a netprop to the specified float.
SetPropFloatArray void SetPropFloatArray(handle entity, string property_name, float value, int array_element) Sets a netprop from an array to the specified float.
SetPropInt void SetPropInt(handle entity, string property_name, int value) Sets a netprop to the specified integer.
Warning.pngWarning:Do not override m_iTeamNum netprops on players or Engineer buildings permanently. Use ForceChangeTeam or SetTeam or respectively. Not doing so will result in unpredictable server crashes later on. Overriding m_iTeamNum temporarily and then reverting it in the same frame is safe however.
SetPropIntArray void SetPropIntArray(handle entity, string property_name, int value, int array_element) Sets a netprop from an array to the specified integer.
SetPropString void SetPropString(handle entity, string property_name, string value) Sets a netprop to the specified string.
SetPropStringArray void SetPropStringArray(handle entity, string property_name, string value, int array_element) Sets a netprop from an array to the specified string.
SetPropVector void SetPropVector(handle entity, string property_name, Vector value) Sets a netprop to the specified vector.
SetPropVectorArray void SetPropVectorArray(handle entity, string property_name, Vector value, int array_element) Sets a netprop from an array to the specified vector.

CScriptEntityOutputs

Game Instance: EntityOutputs

Allows reading and manipulation of entity output data.

Methods

Function Signature Description
AddOutput void AddOutput(handle entity, string output_name, string targetname, string input_name, string parameter, float delay, int times_to_fire) Adds a new output to the entity.
GetNumElements int GetNumElements(handle entity, string output_name) Returns the number of array elements.
GetOutputTable void GetOutputTable(handle entity, string output_name, table, int array_element) Fills the passed table with output information.
HasAction bool HasAction(handle entity, string output_name) Returns true if an action exists for the output.
HasOutput bool HasOutput(handle entity, string output_name) Returns true if the output exists.
RemoveOutput void RemoveOutput(handle entity, string output_name, string targetname, string input_name, string parameter) Removes an output from the entity.
Note.pngNote:The order of the internal output data may change after this is performed, which can be problematic if iterating outputs. As a workaround, all the outputs can be stored in an array of tables first and then removed while iterating the array.

CScriptKeyValues

Script handle representation of a model's $keyvalues block. All sub-keys are instances of the same class.

Methods

Function Signature Description
FindKey CScriptKeyValues FindKey(string key) Find a sub key by the key name.
GetFirstSubKey CScriptKeyValues GetFirstSubKey() Return the first sub key object.
GetKeyBool bool GetKeyBool(string key) Return the key value as a bool.
GetKeyFloat float GetKeyFloat(string key) Return the key value as a float.
GetKeyInt int GetKeyInt(string key) Return the key value as an integer.
GetKeyString string GetKeyString(string key) Return the key value as a string.
GetNextKey CScriptKeyValues GetNextKey() Return the next neighbor key object to the one the method is called on.
IsKeyEmpty bool IsKeyEmpty(string key) Returns true if the named key has no value.
IsValid bool IsValid() Whether the handle belongs to a valid key.
ReleaseKeyValues void ReleaseKeyValues() Releases the contents of the instance.


CPlayerVoiceListener

Game Instance: PlayerVoiceListener

Tracks if any player is using voice and for how long.

Methods

Function Signature Description
GetPlayerSpeechDuration float GetPlayerSpeechDuration(int player_index) Returns the number of seconds the player has been continuously speaking.
IsPlayerSpeaking bool IsPlayerSpeaking(int player_index) Returns whether the player specified is speaking.

CEnvEntityMaker

Extends CBaseEntity ↑

Script handle class for env_entity_maker.

Methods

Function Signature Description
SpawnEntity void SpawnEntity() Create an entity at the location of the maker.
SpawnEntityAtEntityOrigin void SpawnEntityAtEntityOrigin(handle entity) Create an entity at the location of a specified entity instance.
SpawnEntityAtLocation void SpawnEntityAtLocation(Vector origin, Vector orientation) Create an entity at a specified location and orientation, orientation is Euler angle in degrees (pitch, yaw, roll).
SpawnEntityAtNamedEntityOrigin void SpawnEntityAtNamedEntityOrigin(string targetname) Create an entity at the location of a named entity. If multiple entities have the same name, only the one with the lowest entity index will be targeted.

CPointTemplate

Extends CBaseEntity ↑

Script handle class for point_template.

Hooks

table PreSpawnInstance(string entity_class, string entity_name)
If this is defined, it will be called right before the entity is created, and any keyvalues returned will be assigned to the entity.

function PreSpawnInstance(entity_class, entity_name)
{
	local keyvalues =
	{
		rendercolor = "0 255 0",
		targetname = "my_spawned_entity"
	}

	return keyvalues
}
void PostSpawn(table entities)
Called after the entities are spawned. A table with the handles of the spawned entities indexed by name is passed to the function. Could use this to connect outputs or do whatever needs to be done after the entity was created.
Note.pngNote:PostSpawn() will not be called unless the PreSpawnInstance() function is also defined in the script.

function PostSpawn( entities )
{
	foreach(targetname, handle in entities)
	{
		printl(targetname + ": " + handle)
	}
}
Example

Spawned entities can be accessed synchronously in script by using an entity maker. The following generalised example creates a global SpawnMyEntity() function which spawns and returns the templated entity. It can be modified to support multiple templated entities.


m_hSpawnedEntity <- null
m_KeyValues <- null

m_hSpawner <- Entities.CreateByClassname("env_entity_maker")
m_hSpawner.__KeyValueFromString("EntityTemplate", self.GetName())

function PreSpawnInstance(classname, targetname)
{
	return m_KeyValues
}

function PostSpawn(entities)
{
	foreach (targetname, entity in entities)
	{
		m_hSpawnedEntity = entity
		break
	}
}

::SpawnMyEntity <- function(keyvalues = null)
{
	m_KeyValues = keyvalues
	m_hSpawner.SpawnEntity()
	return m_hSpawnedEntity
}.bindenv(this)

Spawn templated entities from any script.


local ent = SpawnMyEntity({
	rendercolor = Vector(RandomInt(0, 255), RandomInt(0, 255), RandomInt(0, 255))
})

printl( ent )

CFuncTrackTrain

Extends CBaseEntity ↑

Script handle class for func_tracktrain.

Methods

Function Signature Description
GetFuturePosition Vector GetFuturePosition(float x, float speed) Get a position on the track X seconds in the future.


CPointScriptTemplate

Extends CBaseEntity ↑

Script handle class for point_script_template.

Methods

Function Signature Description
AddTemplate void AddTemplate(string classname, table keyvalues) Add an entity with the given keyvalues to the template spawner, similar to SpawnEntityFromTable. The number of templates allowed is unlimited.
SetGroupSpawnTables void SetGroupSpawnTables(table group, table spawn) Unused. This only stores a reference to the two tables which is removed when the point_script_template is deleted.
Note.pngNote:To spawn every added template, fire the ForceSpawn input onto the point_script_template with AcceptInput.

Hooks

PreSpawnInstance hook from point_template is not available.

void PostSpawn(table entities)
Called after the entities are spawned. A table with the handles of the spawned entities indexed by name is passed to the function.
Icon-Bug.pngBug:As the PreSpawnInstance hook is not implemented, this callback is never fired. This can be fixed however by defining an entity table named __EntityMakerResult in the entity's scope.
Tip.pngTip:Due to tables requiring unique keys, templated entities that have no targetname or have conflicting ones will not be present in the table. A workaround is to intercept the __EntityMakerResult table and add every entity to an array instead, as shown in the following example:

local template = SpawnEntityFromTable("point_script_template", {})
template.SetGroupSpawnTables({})

local scope = template.GetScriptScope()
scope.Entities <- []
scope.__EntityMakerResult <- {entities = scope.Entities}.setdelegate({_newslot = function(_, value) {entities.append(value)}})
scope.PostSpawn <- function(named_entities)
{
	__DumpScope(0, Entities)
}

template.AddTemplate("prop_dynamic",
{
	model = "models/player/heavy.mdl",
	origin = Vector(247, -281, -123)
})

template.AddTemplate("prop_dynamic",
{
	model = "models/player/spy.mdl",
	origin = Vector(247, -381, -123)
})

template.AcceptInput("ForceSpawn", "", null, null)


CSceneEntity

Extends CBaseEntity ↑

Script handle class for scripted_scene, which make use of VCD data.

Methods

Function Signature Description
AddBroadcastTeamTarget void AddBroadcastTeamTarget(int index) Adds a team (by index) to the broadcast list.
EstimateLength float EstimateLength() Returns length of this scene in seconds.
FindNamedEntity handle FindNamedEntity(string reference) Given an entity reference, such as !target, get actual entity from scene object.
IsPaused bool IsPaused() If this scene is currently paused.
IsPlayingBack bool IsPlayingBack() If this scene is currently playing.
LoadSceneFromString bool LoadSceneFromString(string scene_name, string scene) Given a dummy scene name and a vcd string, load the scene.
RemoveBroadcastTeamTarget void RemoveBroadcastTeamTarget(int index) Removes a team (by index) from the broadcast list.


CCallChainer

CCallChainer objects collect all functions with a matching prefix in a given scope, then inserts it all into the chains table with the prefix removed. All collected unprefixed functions can then be called in a chain using the class's Call() method, given the method's event argument matches the functions' name.

Whenever a CCallChainer object is created, a function named Dispatch followed by its given prefix will also be created, which the class binds the environment of its Call() method to.

Methods

Function Signature Description
constructor CCallChainer(string function_prefix, table scope = null) Creates a CCallChainer object that'll collect functions that have a matching prefix in the given scope.
PostScriptExecute void PostScriptExecute() Search for all non-native functions with matching prefixes, then push them into the chains table.
Call bool Call(string event, any ...) Find an unprefixed function name in the chains table and call it with the given arguments.

Members

Instance Type Description
chains table Contains names of unprefixed functions, each with an array of functions to call.
prefix string Prefix that functions should have to be added into the chains table. Set by the constructor.
scope table If set, seek functions in this scope instead. Set by the constructor.

CSimpleCallChainer

Intended to be simpler to use than CCallChainer ↑, the class CSimpleCallChainer holds only a single chain of functions inside an array instead of multiple inside a table. As such, its Call() method does not need a function's name.

This class is also used internally by these CBaseEntity ↑ hooks: Precache() and OnPostSpawn().

Methods

Function Signature Description
constructor CSimpleCallChainer(string prefix, table scope = null, exactMatch = false) Creates a CSimpleCallChainer object that'll collect functions that have a matching prefix in the given scope, unless it seek for an exact name match.
PostScriptExecute void PostScriptExecute() Begin searching for all non-native functions with matching prefixes, then push them into the chain array.
Call bool Call(any ...) Call all functions inside the chain array with the given arguments.

Members

Instance Type Description
chain array All functions to be called by the Call() method.
exactMatch bool If set, names of non-native functions and prefix must be an exact match. Set by the constructor.
prefix string Prefix that functions should have to be added into the chain array. Set by the constructor.
scope table If set, seek functions in this scope instead. Set by the constructor.

NextBotCombatCharacter

Extends CBaseCombatCharacter ↑

Script handle class for non-playable combat characters operating under the NextBot system.

Methods

Function Signature Description
ClearImmobileStatus void ClearImmobileStatus() Clear immobile status.
FlagForUpdate void FlagForUpdate(bool toggle) Flag this bot for update (or not to update if toggle is false).
Tip.pngTip:Use this in a think function to update nextbots faster than nb_update_frequency. 0.05 is enough to make existing nextbots such as Ghost look smooth.
GetBodyInterface INextBotComponent GetBodyInterface() Get this bot's body interface.
Note.pngNote:Not actually exposed, no functions exist.
GetBotId int GetBotId() Get this bot's id.
GetImmobileDuration float GetImmobileDuration() How long have we been immobile.
GetImmobileSpeedThreshold float GetImmobileSpeedThreshold() Return units/second below which this actor is considered immobile.
GetIntentionInterface INextBotComponent GetIntentionInterface() Get this bot's intention interface.
Note.pngNote:Not actually exposed, no functions exist.
GetLocomotionInterface ILocomotion GetLocomotionInterface() Get this bot's locomotion interface.
GetTickLastUpdate int GetTickLastUpdate() Get last update tick.
GetVisionInterface INextBotComponent GetVisionInterface() Get this bot's vision interface.
Note.pngNote:Not actually exposed, no functions exist.
IsEnemy bool IsEnemy(handle entity) Return true if given entity is our enemy.
IsFlaggedForUpdate bool IsFlaggedForUpdate() Is this bot flagged for update.
IsFriend bool IsFriend(handle entity) Return true if given entity is our friend.
IsImmobile bool IsImmobile() Return true if we haven't moved in awhile.

INextBotComponent

Base script handle class for any interfaces belonging to an individual NextBotCombatCharacter ↑ entity.

Methods

Function Signature Description
ComputeUpdateInterval bool ComputeUpdateInterval() Recomputes the component update interval.
GetUpdateInterval float GetUpdateInterval() Returns the component update interval.
Reset void Reset() Resets the internal update state

ILocomotion

Extends INextBotComponent ↑

The interface for interacting with a specific NextBot's movement brain.

Methods

Function Signature Description
Approach void Approach(Vector goal, float goal_weight) The primary locomotive method. Goal determines the destination position to move towards. goal_weight determines the priority of this path, you can set this to 1.0 generally speaking.
Tip.pngTip:To make the entity move smoothly towards its destination make sure to put this under a think function.
ClearStuckStatus void ClearStuckStatus(string reason) Reset stuck status to un-stuck. Reason message is shown when debugging nextbots.
ClimbUpToLedge bool ClimbUpToLedge(Vector goal_pos, Vector goal_forward, handle obstacle) Initiate a jump to an adjacent high ledge, return false if climb can't start.
ComputeUpdateInterval bool ComputeUpdateInterval() Returns false if no time has elapsed.
DriveTo void DriveTo(Vector pos) Move the bot to the precise given position immediately, updating internal state.
FaceTowards void FaceTowards(Vector target) Rotate body to face towards target.
Tip.pngTip:To make the entity look smoothly towards a spot make sure to put this under a think function, as using the function only once makes the entity only look towards it a bit but not fully, rotating ever so slightly.
FractionPotentialGap float FractionPotentialGap(Vector from, Vector to) If the locomotor cannot jump over the gap, returns the fraction of the jumpable ray.
FractionPotentiallyTraversable float FractionPotentiallyTraversable(Vector from, Vector to, bool immediately) If the locomotor could not move along the line given, returns the fraction of the walkable ray. If immediately is true, breakables are considered non-traverseable.
GetDeathDropHeight float GetDeathDropHeight() Distance at which we will die if we fall.
GetDesiredSpeed float GetDesiredSpeed() Get desired speed for locomotor movement.
GetFeet Vector GetFeet() Return position of feet - the driving point where the bot contacts the ground.
GetGround handle GetGround() Return the current ground entity or NULL if not on the ground.
GetGroundMotionVector Vector GetGroundMotionVector() Return unit vector in XY plane describing our direction of motion - even if we are currently not moving.
GetGroundNormal Vector GetGroundNormal() Surface normal of the ground we are in contact with.
GetGroundSpeed float GetGroundSpeed() Return current world space speed in XY plane.
GetMaxAcceleration float GetMaxAcceleration() Return maximum acceleration of locomotor.
GetMaxDeceleration float GetMaxDeceleration() Return maximum deceleration of locomotor.
GetMaxJumpHeight float GetMaxJumpHeight() Return maximum height of a jump.
Tip.pngTip:If using a base_boss entity, as there is currently no available method to modify this value, you can fire the input SetMaxJumpHeight to change it.
GetMotionVector Vector GetMotionVector() Return unit vector describing our direction of motion - even if we are currently not moving.
GetRunSpeed float GetRunSpeed() Get maximum running speed.
GetSpeed float GetSpeed() Return current world space speed (magnitude of velocity).
GetSpeedLimit float GetSpeedLimit() Get maximum speed bot can reach, regardless of desired speed.
GetStepHeight float GetStepHeight() If delta Z is lower than this, we can step up the surface (like a stair step), but if delta Z is greater than this, we have to jump to get up.
Tip.pngTip:If using a base_boss entity, as there is currently no available method to modify this value, you can fire the input SetStepHeight to change it.
GetStuckDuration float GetStuckDuration() Return how long we've been stuck.
GetTraversableSlopeLimit float GetTraversableSlopeLimit() Return Z component of unit normal of steepest traversable slope.
GetUpdateInterval float GetUpdateInterval() Returns time between updates.
GetVelocity Vector GetVelocity() Return current world space velocity.
GetWalkSpeed float GetWalkSpeed() Get maximum walking speed.
HasPotentialGap float HasPotentialGap(Vector from, Vector to) Checks if there is a possible gap that will need to be jumped over. Returns fraction of ray from 0 to 1.
IsAbleToClimb bool IsAbleToClimb() Return true if this bot can climb arbitrary geometry it encounters.
IsAbleToJumpAcrossGaps bool IsAbleToJumpAcrossGaps() Return true if this bot can jump across gaps in its path.
IsAreaTraversable bool IsAreaTraversable(handle area) Return true if given area can be used for navigation.
IsAttemptingToMove bool IsAttemptingToMove() Return true if we have tried to Approach() or DriveTo() very recently.
IsClimbingOrJumping bool IsClimbingOrJumping() Is jumping in any form.
IsClimbingUpToLedge bool IsClimbingUpToLedge() Is climbing up to a high ledge.
IsEntityTraversable bool IsEntityTraversable(handle entity, bool immediately) Return true if the entity handle is traversable. If immediately is true, breakables are considered non-traverseable.
IsGap bool IsGap(Vector pos, Vector forward) Return true if there is a gap at this position.
Note.pngNote:forward is unused.
.
IsJumpingAcrossGap bool IsJumpingAcrossGap() Is jumping across a gap to the far side.
IsOnGround bool IsOnGround() Return true if standing on something.
IsPotentiallyTraversable float IsPotentiallyTraversable(Vector from, Vector to, bool immediately) Checks if this locomotor could potentially move along the line given. Returns fraction of trace result (1 = clear). If immediately is true, breakables are considered non-traverseable.
IsRunning bool IsRunning() Is running?
IsScrambling bool IsScrambling() Is in the middle of a complex action (climbing a ladder, climbing a ledge, jumping, etc) that shouldn't be interrupted.
IsStuck bool IsStuck() Return true if bot is stuck. If the locomotor cannot make progress, it becomes stuck and can only leave this stuck state by successfully movingand becoming un-stuck.
Jump void Jump() Initiate a simple undirected jump in the air.
JumpAcrossGap void JumpAcrossGap(Vector goal_pos, Vector goal_forward) Initiate a jump across an empty volume of space to far side.
Note.pngNote:goal_forward is unused.
OnLandOnGround void OnLandOnGround(handle ground) Manually run the OnLandOnGround callback. Typically invoked when bot lands on the ground after being in the air.
OnLeaveGround void OnLeaveGround(handle ground) Manually run the OnLeaveGround callback. Typically invoked when bot leaves ground for any reason.
Reset void Reset() Resets motion, stuck state etc.
Run void Run() Set desired movement speed to running.
SetDesiredSpeed void SetDesiredSpeed(float speed) Set desired speed for locomotor movement.
SetSpeedLimit void SetSpeedLimit(float limit) Set maximum speed bot can reach, regardless of desired speed.
Stop void Stop() Set desired movement speed to stopped.
Walk void Walk() Set desired movement speed to walking

LateBinder

Methods

Function Signature Description
Begin
End
EstablishDelegation
HookRootMetamethod
UnhookRootMetamethod
RemoveDelegation
Resolve

Members

Instance Type Description
m_bindNamesStack array
m_fixupSet array
m_log bool
m_logIndent int
m_targetTable table?(null)

Data Types

Vector

Squirrel equivalent of the C++ Vector class. A three-dimensional vector with overloaded arithmetic operations for both Vectors and scalar values.

Methods

Function Signature Description
constructor Vector(float x = 0.0, float y = 0.0, float z = 0.0) Creates a new vector with the specified Cartesian coordiantes.
Cross Vector Cross(Vector factor) The vector product of two vectors. Returns a vector orthogonal to the input vectors.
Dot float Dot(Vector factor) The scalar product of two vectors.
Length float Length() Magnitude of the vector.
LengthSqr float LengthSqr() The magnitude of the vector squared.
Tip.pngTip:This can be used to quickly check if the vector is equal to 0 0 0, by checking if the magnitude is 0.
Length2D float Length2D() Returns the magnitude of the vector on the x-y plane.
Length2DSqr float Length2DSqr() Returns the square of the magnitude of the vector on the x-y plane.
Norm float Norm() Normalizes the vector in place and returns it's length.
Scale Vector Scale(float factor) Scales the vector magnitude.
ToKVString string ToKVString() Returns a string without separations commas.
tostring string tostring() Returns a human-readable string.

Members

Instance Type Description
x float Cartesian X axis.
y float Cartesian Y axis.
z float Cartesian Z axis.

Operations

Operation Return Type Description
Vector + Vector Vector Returns the sum of both classes's members.
QAngle + Vector
Vector - Vector Vector Returns the subtraction of both classes's members.
QAngle - Vector
Vector * integer Vector Returns the multiplication of a Vector against a scalar.
Vector * float

QAngle

Squirrel equivalent of the C++ QAngle class. Represents a three-dimensional orientation as Euler angles.

Has overloaded arithmetic operations with both QAngles and scalar values.

Methods

Function Signature Description
constructor QAngle(float pitch = 0.0, float yaw = 0.0, float roll = 0.0) Creates a new QAngle.
Forward Vector Forward() Returns the Forward Vector of the angles.
Left Vector Left()
Note.pngNote:Returns the right Vector of the angles.
Pitch float Pitch() Returns the pitch angle in degrees.
Roll float Roll() Returns the roll angle in degrees.
ToKVString string ToKVString() Returns a string with the values separated by one space.
ToQuat Quaternion ToQuat() Returns a quaternion representaion of the orientation.
Up Vector Up() Returns the Up Vector of the angles.
Yaw float Yaw() Returns the yaw angle in degrees.

Members

Instance Type Description
x float Pitch in degrees.
y float Yaw in degrees.
z float Roll in degrees.

Operations

Operation Return Type Description
QAngle + QAngle QAngle Sum of both classes's members (XYZ).
Vector + QAngle
QAngle - QAngle QAngle Subtraction of both classes's members (XYZ).
Vector - QAngle
QAngle * int QAngle QAngle multiplied by a number.
QAngle * float


Vector2D, Vector4D

Two and four-dimensional equivalents to Vector with less amount of methods.

Methods

Function Signature Description
constructor Vector2D(float x = 0.0, float y = 0.0) Creates a new 2-dimensional vector with the specified Cartesian coordiantes.
constructor Vector4D(float x = 0.0, float y = 0.0, float z = 0.0, float w = 0.0) Creates a new 4-dimensional vector with the specified Cartesian coordiantes.
Dot float Dot(VectorXD factor) The scalar product of two vectors.
Length float Length() Magnitude of the vector.
LengthSqr float LengthSqr() The magnitude of the vector squared.
Tip.pngTip:This can be used to quickly check if the vector's members are all 0, by checking if the magnitude is 0.
Norm float Norm() Normalizes the vector in place and returns it's length.
ToKVString string ToKVString() Returns a string without separations commas.


Quaternion

Quaternion represents rotations in three-dimensional space.

Methods

Function Signature Description
constructor Quaternion() Creates a new identity quaternion. (0, 0, 0, 1)
constructor Quaternion(float x, float y = 0.0, float z = 0.0, float w = 0.0) Creates a new quaternion of the form w + xi + yj + zk.
Dot float Dot(Quaternion factor) The 4D scalar product of two quaternions. represents the angle between the quaternions in the range [1, 0].
Invert Quaternion Invert() Returns a quaternion with the complimentary rotation.
Norm float Norm() Normalizes the quaternion.
SetPitchYawRoll void SetPitchYawRoll(float pitch, float yaw, float roll) Recomputes the quaternion from the supplied Euler angles.
ToKVString string ToKVString() Returns a string with the values separated by one space.
ToQAngle QAngle ToQAngle() Returns the angles resulting from the rotation.

Members

Instance Type Description
x float Vector component along the i axis.
y float Vector component along the j axis.
z float Vector component along the k axis.
w float Scalar part.

Operations

Todo: Descriptions of the operations are lacking details.
Operation Return Type Description
Quaternion + Quaternion Quaternion Sum of the two Quaternions.
Quaternion - Quaternion Quaternion Subtraction of the two Quaternions.
Quaternion * integer Quaternion Quaternion multiplied by a number.
Quaternion * float

Globals

Function Signature Description
AddThinkToEnt void AddThinkToEnt(handle entity, string function_name) Sets a function in the entity's script to rerun by itself constantly. Pass null as the function name to remove a think function.

The default think interval is 0.1s, unless overridden by returning a different time interval in seconds in the think function. TF2 runs at 66 ticks per second, so the lowest possible interval is 0.015 seconds. Return -1 to think every tick (do not return 0 or 0.015, this will give inconsistent intervals). The highest interval where all clients will interpolate entities. regardless of network settings, is 0.05 (20 times per second).

Note.pngNote:If trying to clear a think function while inside a think function, AddThinkToEnt will not work as the think function is restored on the entity after it's finished.
NetProps.SetPropString(self, "m_iszScriptThinkFunction", "") must be used to remove the think function.
Warning.pngWarning:This can apply to events if they are chained from a think function, for example killing a player with TakeDamage and then trying to clear the think function in player_death event. The think function will not be cleared unless the line above is also added.
Note.pngNote:Some entities are sensitive to when this think function executes within a frame. A notable example is modifying the tf_player_manager entity. The think function must be applied to the manager entity for netprop changes to work correctly, and not any other entity, otherwise modifying its properties will be inconsistent.
Icon-Bug.pngBug:The think function name stored in the entity is not reset if null is passed as the function name. However this is harmless, and it will only show a warning in console.
Warning.pngWarning:Entities with EFL_KILLME and/or EFL_NO_THINK_FUNCTION entity flags set do not process thinks.
AddToScriptHelp void AddToScriptHelp(table help)
Assert void Assert(bool value, string optional_message = null) Test value and if not true, throws exception, optionally with message.
ClearGameEventCallbacks void ClearGameEventCallbacks() Empties the tables of game event callback functions.
Obsolete-notext.pngDeprecated:Do NOT use this! It removes all events, including those from other scripts, and is a common source of script conflicts. Instead, update your event code to use a namespace (define and contain your callback functions inside of a table), which will clean up automatically when this table is removed without interfering with other scripts. Refer to the examples page and expand the example for Team Fortress 2 for guidance on how to set an automatic system for this.
CreateProp CBaseAnimating CreateProp(string classname, Vector origin, string model_name, int activity) Create a prop.
CreateSceneEntity CBaseAnimating CreateSceneEntity(string scene) Create a scene entity to play the specified scene.
developer int developer() The current level of the developer console variable.
DispatchParticleEffect void DispatchParticleEffect(string name, Vector origin, Vector direction) Dispatches a one-off particle system. To pass angles into this, use the .Forward() method on a QAngle.
Note.pngNote:For more control over particles such as parenting them to entities, see the examples page for alternative methods.
Warning.pngWarning:Does NOT work if called from a player think or OnTakeDamage caused by hitscan/melee due to prediction suppressing it. Can be workarounded by spawning the particle with a 0 delayed EntFire or spawning info_particle_system entity
Warning.pngWarning:This does not precache custom particles. As a result, custom particles may show as a burst of red Xs instead on dedicated servers. To precache a particle, use the following function:

function PrecacheParticle(name)
{
	PrecacheEntityFromTable({ classname = "info_particle_system", effect_name = name })
}
Document void Document(unknown symbol_or_table, unknown item_if_symbol = null, string description_if_symbol = null)
DoEntFire void DoEntFire(string target, string action, string value, float delay, handle activator, handle caller) Generate an entity I/O event. The caller and activator argument takes a CBaseEntity script handle, and entities assigned can receive inputs with target set to !self, or !activator / !caller. Negative delays are clamped to 0.
Note.pngNote:Does not work if the target string is point_servercommand.
DoIncludeScript bool DoIncludeScript(string file, handle/table scope) Execute a script and put all its content for the argument passed to thescopeparameter. The file must have the .nut extension.
Warning.pngWarning:Do not put uppercase letters in the path, doing so will cause Linux to fail loading the script from loose directories.
IncludeScript bool IncludeScript(string file, table scope = null) Wrapper for DoIncludeScript.
EmitAmbientSoundOn void EmitAmbientSoundOn(string sound_name, float volume, int soundlevel, int pitch, handle entity) Play named sound on an entity using configurations similar to ambient_generic. Soundlevel is in decibels, see this page for real world equivalents.
Tip.pngTip:Sounds may be hard to hear even at full volume. Naming custom sounds according to the soundmixer can be used to make them naturally louder.
Tip.pngTip:To convert radius in Hammer units to decibels (similar to ambient_generic), use the following formula:
local soundlevel = (40 + (20 * log10(radius / 36.0))).tointeger()
StopAmbientSoundOn void StopAmbientSoundOn(string sound_name, handle entity) Stop named sound on an entity using configurations similar to ambient_generic.
EmitSoundEx void EmitSoundEx(table params) Play a sound. Takes in a script table of params: sound_name, channel, volume, sound_level, flags, pitch, special_dsp, origin, delay, sound_time, entity, speaker_entity, filter_type, filter_param. All parameters are optional except sound_name. See the main page for more details.
EmitSoundOn void EmitSoundOn(string sound_script, handle entity) Play named sound on given entity. The sound must be precached first for it to play (using PrecacheSound or PrecacheScriptSound).
Warning.pngWarning:Looping sounds will not stop on the entity when it's destroyed and will persist forever! To workaround this, run StopSound in the OnDestroy callback.
StopSoundOn void StopSoundOn(string sound_script, handle entity) Stop named sound on an entity.
EmitSoundOnClient void EmitSoundOnClient(string sound_script, handle player) Play named sound only on the client for the specified player. The sound must be precached first for it to play (PrecacheScriptSound).
Note.pngNote:This only supports soundscripts.
EntFire void EntFire(string target, string action, string value = null, float delay = 0, handle activator = null) Wrapper for DoEntFire() that setsactivator to null, but has nocallerparam. Negative delays are clamped to 0.
Note.pngNote:Does not work if the target string is point_servercommand.
EntFireByHandle void EntFireByHandle(handle entity, string action, string value, float delay, handle activator, handle caller) Generate an entity I/O event. First parameter is an entity instance. Negative delays are clamped to 0.
Note.pngNote:With a 0 delay, this will be processed at the end of the frame rather than instantly. If you need an instant, synchronous I/O event then use AcceptInput instead.
Warning.pngWarning:Calling RunScriptCode input will add the value provided to the string table. If your code uses a big range of distinct values provided to this input (for example passing a float like timestamp) the string table will eventually exceed it's limit of 65k strings causing the server to crash (CUtlRBTree overflow). To prevent this issue from occurring you can use custom delay function, such as the one implemented in Source SDK 2013 VScript Examples.
Note.pngNote:This also affects SetText input on game_text, but accounting for it is not as vital.
EntIndexToHScript handle EntIndexToHScript(int entindex) Turn an entity index integer to an HScript representing that entity's script instance.
FileToString string FileToString(string file) Reads a string from file located in the game's scriptdata folder. Returns the string from the file, null if no file or file is greater than 16384 bytes.
Note.pngNote:Files packed inside the BSP cannot be read.
Note.pngNote:This opens files in text mode, therefore binary files will not be parsed correctly.
FindCircularReference FindCircularReference()
FindCircularReferences FindCircularReferences()
FireGameEvent bool FireGameEvent(string name, table params) Fire a game event to a listening callback function in script. Parameters are passed in a squirrel table.
Note.pngNote:The name might be misleading. This does not fire an event that the game will pick up, the function that sends a real game event is named SendGlobalGameEvent.
FireScriptHook bool FireScriptHook(string name, table params) Fire a script hook to a listening callback function in script. Parameters are passed in a squirrel table.
FireScriptEvent void FireScriptEvent(string event, table params) Wrapper for __RunEventCallbacks().
FrameTime float FrameTime() Get the time spent on the server in the last frame. Usually this will be 0.015 (the default tickrate).
GetDeveloperLevel int GetDeveloperLevel() Gets the level of 'developer'
GetFrameCount int GetFrameCount() Returns the engines current frame count. The counter does not reset between map changes. This is NOT the tick count.
Tip.pngTip:To get the current tick count, read the m_nSimulationTick netprop from any player or moving entity.
GetFriction float GetFriction(CTFPlayer player) Returns the Friction on a player entity, meaningless if not a player.
GetFunctionSignature string GetFunctionSignature(function func, string prefix)
GetListenServerHost CTFPlayer GetListenServerHost() Get the local player on a listen server. Returns null on dedicated servers.
Note.pngNote:This depends on the player entity, and therefore this might return null on a listen server if the player doesn't exist yet during map load. Use IsDedicatedServer instead to check if the server is a listen or dedicated server, as it checks it in a different way.
Tip.pngTip:Alternatively, use PlayerInstanceFromIndex(1) to fetch the first player on the server. For convenience sake (e.g. for script compatibility), you can map this to that function using the following:
::GetListenServerHost <- @() PlayerInstanceFromIndex(1)
GetMapName string GetMapName() Get the name of the map without extension, e.g. ctf_2fort. For workshop maps, this will be in the format workshop/[name].ugc[id].
GetModelIndex int GetModelIndex(string model_name) Returns the index of the named model.
Obsolete GetPhysAngularVelocity Vector GetPhysAngularVelocity(handle entity) Returns the Angular velocity of the entity. Deprecated, use the GetPhysAngularVelocity method on the entity instead.
Obsolete GetPhysVelocity Vector GetPhysVelocity(handle entity) Returns the velocity of the entity. Deprecated, use the GetPhysVelocity method on the entity instead.
GetPlayerFromUserID CTFPlayer GetPlayerFromUserID(int userid) Given a user id, return the entity, or null.
Note.pngNote:The 'fake' SourceTV player will always be returned as null. If you need to actually retrieve the SourceTV player, use EntIndexToHScript.
Tip.pngTip:For the opposite, getting the user id from an entity, see the examples page.
GetSoundDuration float GetSoundDuration(string sound_name, string actor_model_name) Returns float duration of the sound. Actor model name is optional and can be left null.
Todo: Actor model name is likely a leftover from Half-Life 2 Half-Life 2
Warning.pngWarning:Does not work on dedicated servers as they do not have audio libraries built-in to load sounds.
IsDedicatedServer bool IsDedicatedServer() Returns true if this server is a dedicated server.
IsModelPrecached bool IsModelPrecached(string model_name) Checks if the model_name is precached.
IsSoundPrecached bool IsSoundPrecached(string sound_name) Checks if the sound_name is precached.
IsPlayerABot bool IsPlayerABot(CTFPlayer player) Is this player/entity a puppet or AI bot. To check if the player is a AI bot (CTFBot) specifically, use IsBotOfType instead.
IsWeakref bool IsWeakref()
LocalTime void LocalTime(table result) Fills out a table with the local time (second, minute, hour, day, month, year, dayofweek, dayofyear, daylightsavings). This mirrors the tm structure in C++, see the reference page for more information.
Warning.pngWarning:The month will be 1-12 rather than 0-11.
MakeNamespace MakeNamespace()
MaxClients float MaxClients() Get the current number of max clients set by the maxplayers command.
Icon-Bug.pngBug:The return value is mistakenly defined as a float. It is best to use .tointeger() after calling this.
PickupObject void PickupObject(CTFPlayer player, handle entity) Object from world is put into the "Held" slot of the player. Warning: it will smoothly interpolate from where it is to the players hand - which is a bit goofy if it is on other side of level.
Note.pngNote:Does nothing in Team Fortress 2 Team Fortress 2 as the code is not implemented.
PlayerInstanceFromIndex CTFPlayer PlayerInstanceFromIndex(int index) Get a script handle of a player using the player index.
Note.pngNote:The 'fake' SourceTV player will always be returned as null. If you need to actually retrieve the SourceTV player, use EntIndexToHScript.
PrecacheEntityFromTable bool PrecacheEntityFromTable(table keyvalues) Precache an entity from KeyValues in a table. Internally this function creates the entity, fire DispatchSpawn and removes it instantly. Returns false if the table has no classname key, if the value of classname is null or empty, or if the entity failed to be created.
Tip.pngTip:Can be used to precache gibs for a model on any entity by using tf_generic_bomb. Example:
PrecacheEntityFromTable({ classname = "tf_generic_bomb", model = MODEL_NAME })
PrecacheModel int PrecacheModel(string model_name) Precache a model (.mdl) or sprite (.vmt) and return model index. The extension must be specified. Returns -1 if null or empty model_name is passed in. Missing models/sprites will still return a new index.
Note.pngNote:Does not precache gibs. See PrecacheEntityFromTable instead.
PrecacheScriptSound bool PrecacheScriptSound(string sound_name) Precache a soundscript. Returns false if soundscript is missing, or if a null or empty sound name is passed in.
PrecacheSound bool PrecacheSound(string sound_name) Precache a raw sound. Returns false if a null or empty sound name is passed in.
PrintHelp void PrintHelp() Equivalent to running script_help command.
RandomFloat float RandomFloat(float min, float max) Generate a random floating-point number within a range, inclusive.
RandomInt int RandomInt(int min, int max) Generate a random integer within a range, inclusive.
RegisterFunctionDocumentation void RegisterFunctionDocumentation(function func, string name, string signature, string description)
RegisterScriptGameEventListener void RegisterScriptGameEventListener(string event_name) Register as a listener for a game event from script. It's what __CollectGameEventCallbacks() uses to register event callbacks to the C++ code.
Note.pngNote:This cannot be used to register non-existent game events.
RegisterScriptHookListener void RegisterScriptHookListener(string name) Register as a listener for a script hook from script.
RetrieveNativeSignature string RetrieveNativeSignature(function func)
RotateOrientation QAngle RotateOrientation(QAngle initial, QAngle rotation) Rotate a QAngle by another QAngle.
RotatePosition Vector RotatePosition(Vector origin, QAngle rotation, Vector input) Rotate the input Vector around an origin.
Icon-Bug.pngBug:This is not calculated correctly and the rotation will always be relative to (0, 0, 0). As a workaround, subtract the origin from the input, call this function and then add the origin back which will perform the expected result.
ScreenFade void ScreenFade(CTFPlayer player, int red, int green, int blue, int alpha, float fade_time, float fade_hold, FFADE flags) Start a customisable screenfade. If no player is specified, the fade will apply to all players.
ScreenShake void ScreenShake(Vector center, float amplitude, float frequency, float duration, float radius, SHAKE_COMMAND command, bool air_shake) Start a customisable screenshake. Set command to 0 to start a shake, or 1 to stop an existing shake. air_shake determines whether the airborne players should be affected by the shake as well.
ScriptHooksEnabled bool ScriptHooksEnabled() Returns whether script hooks are currently enabled.
SendGlobalGameEvent bool SendGlobalGameEvent(string event_name, table params) Sends a real game event to everything. Parameters are passed in a squirrel table.
Warning.pngWarning:Certain events that are usually clientside only will not work when fired by this function, with an error complaining that "no listeners are registered for this event". However, defining an empty event listener will make it work.
Warning.pngWarning:Events that upload statistics to Steam servers such as player_escort_score can take as long as 1 millisecond to execute! This can be prevented by temporarily giving the player the FL_FAKECLIENT flag and reverting it afterwards (however be careful not to revert it on actual bots!).

Example:


local is_bot = player.IsFakeClient()
if (!is_bot) player.AddFlag(Constants.FPlayer.FL_FAKECLIENT)

SendGlobalGameEvent("player_escort_score",
{
	player = player.entindex(),
	points = 1
})

if (!is_bot) player.RemoveFlag(Constants.FPlayer.FL_FAKECLIENT)
SendToConsole void SendToConsole(string command) Issues a command to the local client, as if they typed in the command in their console. Does nothing on dedicated servers.
SendToServerConsole void SendToServerConsole(string command) Issues a command to the server, as if typed in the console.
Note.pngNote:This obeys the behavior of the sv_allow_point_servercommand convar. By default, this command will do nothing unless the server has this command to set to "always"
Todo: using this on listen servers without allowing point_servercommand is seemingly inconsistent, check IsDedicatedServer() and use SendToConsole instead.
SendToConsoleServer void SendToConsoleServer(string command) Copy of SendToServerConsole with another name for compat.
SetFakeClientConVarValue void SetFakeClientConVarValue(CTFBot bot, string cvar, string value) Sets a USERINFO client ConVar for a fakeclient.
Tip.pngTip:This can be used to change the name of a bot by using the name cvar.
SetSkyboxTexture void SetSkyboxTexture(string texture) Sets the current skybox texture. The path is relative to "materials/skybox/". Only the main name of a skybox texture is needed, for example "sky_gravel_01".
SpawnEntityFromTable handle SpawnEntityFromTable(string name, table keyvalues) Spawn entity from KeyValues in table - 'name' is entity name, rest are KeyValues for spawn.
Note.pngNote:Multiple keys of the same name can be specified by appending the key with an incremental #x suffix.
Note.pngNote:parentname is not resolved and therefore will not work. Instead, fire AcceptInput after spawning (with SetParent !activator parameters), or use SpawnEntityGroupFromTable.
Tip.pngTip:If spawning multiple entities at once, use SpawnEntityGroupFromTable as it will be more efficient.

Example:


SpawnEntityFromTable("logic_timer", {
	targetname = "cool"
	RefireTime = 60
	"OnTimer#1" : "entity,Trigger,,0,-1"
	"OnTimer#2" : "somethingelse,Disable,,0,-1"
})
Warning.pngWarning:If using commas inside the parameter field of a output key, it will not be parsed correctly as the comma will be treated as delimiter.

To fix this, an special delimiter also supported by the game can be used named 'ESC'. This cannot be typed on a keyboard normally, and must be copied from another source. The easiest way is to open this link, and copy + paste the character in a supporting editor such as Notepad++.
Example (the character will not display correctly on this page):
"OnTrigger#5": "res,RunScriptCode,NetProps.SetPropString(self, `m_iszMvMPopfileName`, `test`),0,-1"
would instead be changed to

"OnTrigger#5": "res�RunScriptCode�NetProps.SetPropString(self, `m_iszMvMPopfileName`, `test`)�0�-1"
Note.pngNote:If using a complex model, usually custom models, it might cause stutters to the server when spawning it. To work around this issue instead spawn it with CreateByClassname and set its netprops manually, and don't forget to make sure the model is precached properly too.
SpawnEntityGroupFromTable bool SpawnEntityGroupFromTable(table groups) Hierarchically spawn an entity group from a set of spawn tables. This computes a spawn order for entities so that parenting is resolved correctly.

The table for this must take the following format. group can be any name, as long as it's unique. Each group can only contain one entity. (The table is formatted like this as otherwise it wouldn't be possible to spawn multiple entities of the same classname). The function always returns true, even if entity spawning fails.

{
	<group> =
	{
		<classname> =
		{
			// key - values
		}
	},
	// ...
}

Example usage:


SpawnEntityGroupFromTable(
{
	a =
	{
		info_particle_system =
		{
			origin = GetListenServerHost().GetOrigin(),
			parentname = "mytarget",
			effect_name = "soldierbuff_blue_soldier",
			start_active = true
		}
	},
	b =
	{
		info_particle_system =
		{
			origin = GetListenServerHost().GetOrigin(),
			parentname = "mytarget",
			effect_name = "soldierbuff_red_soldier",
			start_active = true
		}
	},
})
Note.pngNote:You will need to hijack an unused string netprop and set the bounding box data for brush entities there, then run a script on the entity to parse it. Example:

Make a script file named "make_brush.nut" that contains the following:

function OnPostSpawn()
{
	local buf = split(NetProps.GetPropString(self, "m_iszResponseContext"), " ")
	self.SetSize(Vector(buf[0], buf[1], buf[2]), Vector(buf[3], buf[4], buf[5]))
	self.SetSolid(2)
}

Now you can set the min/max bounding box values for a brush ent directly in the ent key/values like so:

SpawnEntityGroupFromTable({
	[0] = {
		func_rotating =
		{
			message = "hl1/ambience/labdrone2.wav",
			responsecontext = "-1 -1 -1 1 1 1",
			vscripts = "make_brush",
			volume = 8,
			targetname = "crystal_spin",
			spawnflags = 65,
			solidbsp = 0,
			rendermode = 10,
			rendercolor = "255 255 255",
			renderamt = 255,
			maxspeed = 48,
			fanfriction = 20,
			angles = QAngle(),
			origin = Vector(),
		}
	},
	[1] = {
		trigger_multiple =
		{
			targetname = "trigger1",
			responsecontext = "-250 -250 -250 250 250 250",
			vscripts = "make_brush",
			parentname = "crystal_spin",
			spawnflags = 1,
			"OnStartTouchAll#1": "!activator�RunScriptCode�ClientPrint(self, 3, `I am in trigger1`)�0�-1",
		}
	},
	[2] = {
		prop_dynamic =
		{
			targetname = "crystal",
			solid = 6,
			renderfx = 15,
			rendercolor = "255 255 255",
			renderamt = 255,
			physdamagescale = 1.0,
			parentname = "crystal_spin",
			modelscale = 1.3,
			model = "models/props_moonbase/moon_gravel_crystal_blue.mdl",
			MinAnimTime = 5,
			MaxAnimTime = 10,
			fadescale = 1.0,
			fademindist = -1.0,
			origin = Vector(),
			angles = QAngle(45, 0, 0)
		}
	},
})
Tip.pngTip:If a list of entity handles created from this function is needed, there is two workarounds:
  • 1 - Assign a vscripts file that appends this to a global array.
  • 2 - Use a point_script_template, see the spawn hook example ↑.
StringToFile void StringToFile(string file, string string) Stores a string as a file, located in the game's scriptdata folder.
Warning.pngWarning:Since this writes to the disk, the performance will vary depending on the hardware (i.e. HDD or SSD). This function should only be called at checkpoints such as round restart or before level change, and not during gameplay to prevent hitches.
Warning.pngWarning:This writes files in text mode, therefore binary files will not be written correctly. As another consequence, if writing multi-line strings directly, this may cause issues due to Window's encoding new lines as \r\n, but Mac/Linux encodes as \n. This can be fixed by setting EOL (end-of-line) encoding to Unix or CR in your text editor.
Icon-Bug.pngBug:A single NULL byte will always be appended to the end of the file.
Time float Time() Get the current time since map load in seconds. The time resets on map change.

The time may be different compared to the global time if running in the context of a player, such as a player think function or damage callback caused by a player. This adjustment is for lag compensation and may be up to 1 second (sv_maxunlag). Therefore use GetFrameCount if you need to compare if events happened in the same tick.

TraceLine float TraceLine(Vector start, Vector end, handle ignore) Trace a ray. Return fraction along line that hits world or models. Optionally, ignore the specified entity.
Tip.pngTip:Specify the same start and end point to check whether a point is inside solid geometry/out of bounds.
TraceLinePlayersIncluded float TraceLinePlayersIncluded(Vector start, Vector end, handle ignore) Different version of TraceLine that also hits players and NPCs.
TraceLineEx bool TraceLineEx(table params) Extended version of TraceLine. See the main page for more details.
Warning.pngWarning:Setting any input parameters which expect an instance (vector or entity) to a primitive type like integer will lead to a server crash. Setting it to null however will not cause such issue.
TraceHull bool TraceHull(table params) Trace a box (AABB). See the main page for more details.
Warning.pngWarning:See above.
UniqueString string UniqueString(string suffix = null) Generate a string guaranteed to be unique across the life of the script VM, with an optional suffix. Useful for adding data to tables when not sure what keys are already in use in that table.

The format of the string is _%x%llx_%s, with arguments as follows: random number between 0 and 4095, an incrementing 64-bit counter, and suffix.

DoUniqueString string DoUniqueString(string suffix) Internal function called by UniqueString.
VSquirrel_OnCreateScope table VSquirrel_OnCreateScope(any value, table scope) Creates a new scope with the name of value in the submitted table (includes unique params).
VSquirrel_OnReleaseScope void VSquirrel_OnReleaseScope(table created_scope) Removes a scope created via VSquirrel_OnCreateScope.
__CollectEventCallbacks void __CollectEventCallbacks(scope, prefix, global_table_name, reg_func) Overloaded function. Its only used for this: __CollectEventCallbacks(scope, "OnGameEvent_", "GameEventCallbacks", ::RegisterScriptGameEventListener).
__CollectGameEventCallbacks void __CollectGameEventCallbacks(table scope) Wrapper that registers callbacks for both OnGameEvent_x and OnScriptEvent_ functions. Done using the __CollectEventCallbacks function.
__ReplaceClosures void __ReplaceClosures(script, scope)
__RunEventCallbacks void __RunEventCallbacks(event, params, prefix, global_table_name, bool warn_if_missing) Call all functions in the callback array for the given game event.
__RunGameEventCallbacks void __RunGameEventCallbacks(event, params) Wrapper for __RunEventCallbacks().
__RunScriptHookCallbacks void __RunScriptHookCallbacks(event, param)

Team Fortress 2

Function Signature Description
AllowThirdPersonCamera bool AllowThirdPersonCamera()
ArePlayersInHell bool ArePlayersInHell()
FlagsMayBeCapped bool FlagsMayBeCapped() May a flag be captured?
ForceEnableUpgrades void ForceEnableUpgrades(int state) Whether to force on MvM-styled upgrades on/off. 0 -> default, 1 -> force off, 2 -> force on.
ForceEscortPushLogic void ForceEscortPushLogic(int state) Forces payload pushing logic. 0 -> default, 1 -> force off, 2 -> force on.
GameModeUsesCurrency bool GameModeUsesCurrency() Does the current gamemode have currency?
GameModeUsesMiniBosses bool GameModeUsesMiniBosses() Does the current gamemode have minibosses?
GameModeUsesUpgrades bool GameModeUsesUpgrades() Does the current gamemode have upgrades?
GetClassLimit int GetClassLimit(ETFClass class) Get class limit for class.
GetGravityMultiplier float GetGravityMultiplier()
GetMannVsMachineAlarmStatus bool GetMannVsMachineAlarmStatus()
GetOvertimeAllowedForCTF bool GetOvertimeAllowedForCTF()
GetRoundState int GetRoundState() Get current round state. See Constants.ERoundState.
GetStopWatchState int GetStopWatchState() Get the current stopwatch state. See Constants.EStopwatchState.
GetWinningTeam int GetWinningTeam() Who won!
HaveStopWatchWinner bool HaveStopWatchWinner()
InMatchStartCountdown bool InMatchStartCountdown() Are we in the pre-match/setup state?
InOvertime bool InOvertime() Currently in overtime?
IsAttackDefenseMode bool IsAttackDefenseMode()
IsBirthday bool IsBirthday() Are we in birthday mode?
IsCompetitiveMode bool IsCompetitiveMode() Playing competitive?
IsDefaultGameMode bool IsDefaultGameMode() The absence of arena, mvm, tournament mode, etc.
IsHolidayActive bool IsHolidayActive(EHoliday holiday) Is the given holiday active?
IsHolidayMap bool IsHolidayMap(EHoliday holiday) Playing a holiday map?
IsInArenaMode bool IsInArenaMode() Playing arena mode?
IsInKothMode bool IsInKothMode() Playing king of the hill mode?
IsInMedievalMode bool IsInMedievalMode() Playing medieval mode?
IsInWaitingForPlayers bool IsInWaitingForPlayers() Are we waiting for some stragglers?
IsMannVsMachineMode bool IsMannVsMachineMode() Playing MvM? Beep boop.
IsMannVsMachineRespecEnabled bool IsMannVsMachineRespecEnabled() Are players allowed to refund their upgrades?
IsMatchTypeCasual bool IsMatchTypeCasual() Playing casual?
IsMatchTypeCompetitive bool IsMatchTypeCompetitive() Playing competitive?
IsPasstimeMode bool IsPasstimeMode() No ball games.
IsPowerupMode bool IsPowerupMode() Playing powerup mode? Not compatible with MvM.
IsPVEModeActive bool IsPVEModeActive()
IsQuickBuildTime bool IsQuickBuildTime() If an engie places a building, will it immediately upgrade? Eg. MvM pre-round etc.
IsTruceActive bool IsTruceActive()
IsUsingGrapplingHook bool IsUsingGrapplingHook()
IsUsingSpells bool IsUsingSpells()
MapHasMatchSummaryStage bool MapHasMatchSummaryStage()
MatchmakingShouldUseStopwatchMode bool MatchmakingShouldUseStopwatchMode()
PlayerReadyStatus_ArePlayersOnTeamReady bool PlayerReadyStatus_ArePlayersOnTeamReady(ETFTeam team)
PlayerReadyStatus_HaveMinPlayersToEnable bool PlayerReadyStatus_HaveMinPlayersToEnable()
PlayerReadyStatus_ResetState void PlayerReadyStatus_ResetState()
PlayersAreOnMatchSummaryStage bool PlayersAreOnMatchSummaryStage()
PointsMayBeCaptured bool PointsMayBeCaptured() Are points able to be captured?
SetGravityMultiplier void SetGravityMultiplier(float multiplier)
SetMannVsMachineAlarmStatus void SetMannVsMachineAlarmStatus(bool status)
SetOvertimeAllowedForCTF void SetOvertimeAllowedForCTF(bool state)
SetPlayersInHell void SetPlayersInHell(bool state)
SetUsingSpells void SetUsingSpells(bool state)
UsePlayerReadyStatusMode bool UsePlayerReadyStatusMode()

Printing and Drawing

Functions for printing out messages or drawing elements in the world, mostly for debugging reasons.

Warning.pngWarning:Any function with the Debug prefix requires the cvar developer be enabled and the game unpaused.
They also do not appear in multiplayer, only on a local server.
Function Signature Description
ClientPrint void ClientPrint(CTFPlayer player, EHudNotify destination, string message) Print a client message. If you pass null instead of a valid player, the message will be sent to all clients.

When printing to chat (HUD_PRINTTALK), the color of the text can be changed with certain hex codes:

  • \x01 - Default chat color
  • \x03 - Lime
  • \x04 - Green
  • \x05 - Olive
  • \x06 - Black
  • \x07 - custom color in hexadecimal RRGGBB format. Example: \x07FF3F3F
  • \x08 - custom color in hexadecimal RRGGBBAA format (i.e. with transparency). Example: \x08FF3F3FCC

Chat messages can contain multiple of these codes. If using color sequences, there MUST be a color sequence at the beginning of the string, or color codes won't work!.

Warning.pngWarning:Hammer Will not accept these escape sequences. As a result, you cannot print colored text with a simple RunScriptCode input.
PlacementTip.pngWorkaround:See the VScript Examples page for a workaround that replaces a normal character with \x07 at run-time.
Tip.pngTip:Standard chat colors:
  • Default: FBECCB
  • RED: FF3F3F
  • BLUE: 99CCFF
  • Unassigned/spectator: CCCCCC
DebugDrawBox void DebugDrawBox(Vector origin, Vector min, Vector max, int r, int g, int b, int alpha, float duration) Draw a debug overlay box.
DebugDrawBoxAngles void DebugDrawBoxAngles(Vector origin, Vector min, Vector max, QAngle direction, Vector rgb, int alpha, float duration) Draw a debug oriented box.
DebugDrawBoxDirection void DebugDrawBoxDirection(Vector center, Vector min, Vector max, Vector forward, Vector rgb, float alpha, float duration) Draw a debug forward box.
DebugDrawCircle void DebugDrawCircle(Vector center, Vector rgb, float alpha, float radius, bool ztest, float duration) Draw a debug circle.
DebugDrawClear void DebugDrawClear() Try to clear all the debug overlay info.
DebugDrawLine void DebugDrawLine(Vector start, Vector end, int red, int green, int blue', bool z_test, float time) Draw a debug overlay line.
DebugDrawLine_vCol void DebugDrawLine_vCol(Vector start, Vector end, Vector rgb, bool ztest, float duration) Draw a debug line using color vec.
DebugDrawScreenTextLine void DebugDrawScreenTextLine(float x, float y, int line_offset, string text, int r, int g, int b, int a, float duration) Draw text with a line offset.
DebugDrawText void DebugDrawText(Vector origin, string text, bool use_view_check, float duration) Draw text on the screen, starting on the position of origin.
__DumpScope void __DumpScope(int indentation, table scope) Dumps a scope's contents and expands all tables and arrays; this is what the ent_script_dump command uses.
Tip.pngTip:You can use this to print tables/arrays.
Example

Using this code:

local test_table =
{
	integer = 20,
	string = "hello",
	array = [1, 2, 3]
}

printl("{")
__DumpScope(1, test_table)
printl("}")

Will print the following in console:

{
   string = "hello"
   array(ARRAY)
   [
      0 = 1
      1 = 2
      2 = 3
   ]
   integer = 20
}
Note.pngNote:The output will be unordered and/or incorrectly indented with multithreading enabled. Set mat_queue_mode to 0 before using this for the expected output. This applies to all printing and drawing functions, but is most noticeable here
DumpObject void DumpObject(handle object) Dumps information about a class or instance.
Msg void Msg(string message) Prints message to console without any line feed after.
printf void printf(string format, args...) Prints message to console with C style formatting. The line feed is not included.
printl void printl(string message) Prints message to console with a line feed after.
realPrint void realPrint(string message) Identical to print. print seems to be a wrapper for this.
Say void Say(CTFPlayer player, string message, bool team_only) Calling this will have the specified player send the message to chat, either to team_only (true) or to everyone.
ShowMessage void ShowMessage(string message) Displays a HUD message defined in scripts/titles.txt to all clients, similar to an env_message entity.

Squirrel Standard Library

Squirrel Functions of both Squirrel's built-in functions and standard library.

Global

Function Signature Description
assert assert(bool exp) Throws an assertion error if the given expression evaluates to false (i.e. the values 0, 0.0, null and false).
callee function callee() Returns the currently running closure.
castf2i int castf2i(float value) Interprets the float's bytes as if it were a 32-bit integer representation.
Warning.pngWarning:This is a bit reinterpretation, i.e. 1.0 will not result in 1, it will be 1065353216! Use the tointeger() method for an actual conversion.
Icon-Bug.pngBug:Does not return correct results since it takes a 32-bit float and returns a 64-bit integer.
PlacementTip.pngWorkaround:Truncate the resulting number to 32-bit. Example:
castf2i(2.01787e-43) & 0xFFFFFFFF
casti2f float casti2f(int value) Interprets the integer's bytes as if it were a floating-point encoding.
Warning.pngWarning:This is a bit reinterpretation, i.e. 420 will not result in 420.0, it will be 5.88545e^-43! Use the tofloat() method for an actual conversion.
collectgarbage int collectgarbage() Runs the garbage collector and returns the number of reference cycles found(and deleted) This function only works on garbage collector builds.
compilestring any compilestring(string string, string buffer_name = null) Compiles a string containing a squirrel script into a function and returns it.
dummy dummy()
enabledebuginfo void enabledebuginfo(any enable) Enable/disable the debug line information generation at compile time. enable != null enables . enable == null disables.
error void error(string x) Prints x in the standard error output .
getconsttable table getconsttable() Returns the const table of the VM.
getroottable table getroottable() Returns the root table of the VM.
getstackinfos table getstackinfos(int level) Returns the stack frame informations at the given stack level (0 is the current function 1 is the caller and so on). If the stack level doesn't exist the function returns null.
Example
{
  func = "DoStuff",		// function name

  src = "test.nut",		// source file

  line = 10,			// line number

  locals =			// a table containing the local variables
  {
    a = 10,

    testy = "I'm a string"
  }
}
print void print(string message) Prints the given parameter but with no newline unlike printl().
resurrectunreachable array resurrectunreachable() Runs the garbage collector and returns an array containing all unreachable object found. If no unreachable object is found, null is returned instead. This function is meant to help debugging reference cycles. This function only works on garbage collector builds.
setconsttable table setconsttable(table new_const) Sets the const table of the VM which also returns the previous const table.
setdebughook void setdebughook(function<type, file, line, func_name> hook_func) Sets the debug hook.
seterrorhandler void seterrorhandler(function<error> error_handler) Sets the runtime error handler .
setroottable table setroottable(table new_root) Sets the root table of the VM which also returns the previous root table.
swap2 int swap2(int value) Swaps bytes 1 and 2 of the integer.
swap4 int swap4(int value) Reverse byte order of the four bytes.
swapfloat float swapfloat(float value) Reverse byte order of the four bytes.
type type(var) Returns var._typeof(), i.e. the type of the given parameter as a string

Math

Note.pngNote:Trigonometric functions (sin, cos, acos, etc.) operate on angles in radians. Use degrees * PI / 180 to convert degrees to radians when trying to pass the degrees into these functions, and radians * 180 / PI to convert radians to degrees if you want to receive degrees from inverse functions such as acos.
Function Signature Description
abs int abs(float x) Returns |x| as integer unlike fabs().
acos float acos(float x) Returns cos-1(x), -1 ≤ x ≤ 1.
asin float asin(float x) Returns sin-1(x), -1 ≤ x ≤ 1.
atan float atan(float x) Returns tan-1(x).
atan2 float atan2(float y, float x) (!) Returns the angle between the ray from the point (0, 0) through (x, y) and the positive x-axis, confined to (−PI, PI], See also atan2. Note the order of the parameters x and y!
ceil int ceil(float x) Returns the smallest integer that is ≥ x.
cos float cos(float x) Returns cos(x).
exp float exp(float x) Returns exp(x) = ex.
fabs float fabs(float x) Returns |x| as float unlike abs().
floor int floor(float x) Returns the largest integer that is ≤ x.
log float log(float x) Returns loge(x) = ln(x).
log10 float log10(float x) Returns log10(x).
pow float pow(float x, float y) Returns xy.
rand int rand() Returns a random integer with 0 ≤ rand() ≤ RAND_MAX.
Warning.pngWarning:The value of RAND_MAX is 32768 on Windows, but 2147483647 on Linux. This can cause undeterministic behavior between a server running on Windows vs Linux even if the same seed is used with srand. If determinism is needed, roll your own random number generator.
sin float sin(float x) Returns sin(x).
sqrt float sqrt(float x) Returns the square root of x.
srand void srand(int seed) Sets the starting point for generating a series of pseudorandom integers.
tan float tan(float x) Returns tan(x)

Integer

Function Signature Description
tofloat float tofloat() Converts the integer to float and returns it.
tostring string tostring() Converts the integer to string and returns it.
tochar string tochar() Returns a string containing a single character represented by the integer.

Float

Function Signature Description
tointeger int tointeger() Converts the float to integer and returns it.
tostring string tostring() Converts the integer to string and returns it.
tochar string tochar() Returns a string containing a single character represented by the integer part of the float.

Bool

Function Signature Description
tofloat float tofloat() Returns 1.0 for true 0.0 for false.
tointeger int tointeger() Returns 1 for true 0 for false.
tostring string tostring() Returns "true" for true and "false" for false.

String

The following belong as member methods of the string object, in other words they must be called with the dot operator on a string, e.g. str.slice(0, 5).

Function Signature Description
find int find(string search_string, int start_index = 0) Looks for the sub-string passed as its first parameter, starting at either the beginning of the string or at a specific character index if one is provided as a second parameter. If the sub-string is found, returns the index at which it first occurs, otherwise returns null.
len int len() Returns the length of the string, ie. the number of characters it comprises.
slice string slice(int start_index, int end_index = null) Creates a sub-string from a string. Copies characters from start_index to end_index. The sub-string includes the character at start_index, but excludes the one at end_index. If end_index is not specified, copies until the last character. If the provided end index is beyond the string, an exception is thrown. If the numbers are negative the count will start from the end of the string (e.g. -2 represents a second last character).
tofloat float tofloat() Returns float value represented by the string. Must only contain numeric characters and/or plus and minus symbols. An exception is thrown otherwise.
tointeger int tointeger(int base = 10) Returns integer value represented by the string. Must only contain numeric characters. An exception is thrown otherwise. Hexadecimal notation is supported (i.e. 0xFF). If a hexadecimal string contains more than 10 characters, including the 0x, returns -1.
tolower string tolower() Returns a new string with all upper-case characters converted to lower-case.
toupper string toupper() Returns a new string with all lower-case characters converted to upper-case.

The following belong as global string functions, e.g. str = format("%d", num).

Function Signature Description
endswith bool endswith(string str, string cmp) Returns true if the end of the string matches the comparison string.
escape string escape(string str) Returns a string with backslashes before characters that need to be escaped: “ a b t n v f r \ ” ’ 0 xNN.
format string format(string format, args...) Returns a formatted string. Same rules as the standard C functions (except * is not supported).
lstrip string lstrip(string str) Removes whitespace at the beginning of the given string.
rstrip string rstrip(string str) Removes whitespace at the end of the given string.
split array split(string str, string separator, bool skip_empty = false) Returns an array of strings split at each point where a separator character occurs in str. The separator is not returned as part of any array element. the parameter separators is a string that specifies the characters as to be used for the splitting. If skipempty is true, empty strings are not added to array.
Warning.pngWarning:Passing null as the first parameter will crash the server
startswith bool startswith(string str, string cmp) Returns true if the beginning of the string matches the comparison string.
strip string strip(string str) Removes whitespace at the beginning and end of the given string

Array

Function Signature Description
array array(int length, any fill = null) Returns a new array of the given length where each element is set to fill.
append void append(any item) Adds an item to the end of an array.
apply void apply(function<value, [index, array_ref]> func) Applies a function to all of an array's items and replace the original value of the element with the return value of the function. Provided func can accept up to 3 arguments: array item value (required), array item index (optional), reference to array itself (optional).
clear void clear() Removes all of the items from an array.
extend array extend(array other) Combines two arrays into one.
filter array filter(function<index, value> condition) Applies a filter function to an array's items, storing the results in a new array.
find int find(any element) Looks for the element passed as its parameter, starting at either the beginning of the array. If the element is found, returns the index at which it first occurs, otherwise returns null.
insert void insert(int index, any item) Inserts an item into an array at the specified index.
len int len() Returns the length of the array, ie. the number of elements it has.
map array map(function<value, [index, array_ref]> func) Creates a new array of the same size. For each element in the original array invokes the function ‘func’ and assigns the return value of the function to the corresponding element of the newly created array. Provided func can accept up to 3 arguments: array item value (required), array item index (optional), reference to array itself (optional).
pop any pop() Returns and removes the value at the end of the array.
push void push(any item) Adds an item to the end of an array.
reduce any reduce(function<pre_value, current_value> func, any init = null) This method applies the supplied function to all of the items in the target array, starting with the first two. The function returns a single value which is then combined with the next (third) item in the array — and so on until all of the items have been combined into a single value which the method returns.
remove any remove(int index) Returns and removes an array item at a specified index.
resize void resize(int new_size, any fill = null) Increases or decreases the size of an array. In case of increasing fills the new spots with fill parameter.
reverse void reverse() Reverses the order of the elements in an array.
slice array slice(int start_index, int end_index = null) Creates a new array from an array. Copies elements from start_index to end_index. The new array includes the element at start_index, but excludes the one at end_index. If end_index is not specified, copies until the last element. If the provided end index is beyond the array, an exception is thrown. If the numbers are negative the count will start from the end of the array (e.g. -2 represents a second last character).
sort void sort(function<a, b> compare = null) This method sorts the items within the target array into either a lowest-to-highest order or according to the results of an optional comparison function which may be passed to the method as a parameter. If the items are arrays, blobs, functions, objects and/or tables, they will be sorted by reference not value. The optional comparison function should take two parameters: two values which will be compared in some way. It should return the value -1 if the first value should be placed before the second, or 1 if it should follow the second value. Return 0 if the two values are equivalent. Spaceship operator <=> may come in handy if trying to sort by some field value. E.g.
arr.sort(@(a, b) a.distance <=> b.distance)
top any top() Returns the value at the end of an array.
tostring string tostring() Returns the string "(array : pointer)"

Table

Function Signature Description
clear void clear() Removes all of the items from a table.
filter table filter(function<key, value> func) Creates a new table with all values that pass the test implemented by the provided function. In detail, it creates a new table, invokes the specified function for each key-value pair in the original table; if the function returns ‘true’, then the value is added to the newly created table at the same key.
getdelegate table getdelegate() Returns a table's delegate.
keys array keys() Returns an array containing all the keys of the table slots.
len int len() Returns the length of the table, ie. the number of entries it has.
rawdelete any rawdelete(any key) This method deletes the target slot without employing delegation. If the table lacks the target slot, the methods returns null, otherwise it returns the value associated with that slot.
rawget any rawget(any key) Retrieves the value of the specified key without employing delegation.
rawin bool rawin(any key) Checks for the presence of the specified key in the table/class/handle without employing delegation.
rawset table rawset(any key, any value) Sets the value of the specified key without employing delegation. Returns table itself.
setdelegate table setdelegate(table delegate) This method assigns the passed table as the target’s new custom delegate. The method always returns the target.To remove a delegate, either assign the target with a new delegate, or pass null.
values array values() Returns an array containing all the values of the table slots.
tostring string tostring() Tries to invoke the _tostring metamethod. If that fails returns the string "(table: pointer)".

Function

Function Signature Description
acall any acall(array args) Calls the target function and passes array values into its parameters. First element of the array should be the non-default context object.
bindenv function bindenv(table environment) Clones the target function and binds it to a specified context object.
call any call(table environment, any args...) Calls the function with a non-default context object.
getinfos table getinfos() Returns a table containing informations about the function, like parameters, name and source name.
Example
//pure squirrel function
{
  native = false
  name = "zefuncname"
  src = "/somthing/something.nut"
  parameters = ["a","b","c"]
  defparams = [1,"def"]
  varargs = 2
}
//native C function
{
  native = true
  name = "zefuncname"
  paramscheck = 2
  typecheck = [83886082,83886384] //this is the typemask (see C defines OT_INTEGER,OT_FLOAT etc...)
}
getroot table getroot() Returns the root table of the closure.
pacall any pacall(array args) Calls the function with an array of parameters, bypassing Squirrel error callbacks. First element of the array should be the non-default context object.
pcall any pcall(table environment, any args...) Calls the function with a non-default context object, bypassing Squirrel error callbacks.
setroot void setroot(table root) Sets the root table of a closure.
tostring string tostring() Returns the string "(closure: pointer)".

Class

Function Signature Description
getattributes any getattributes(string member_name) Returns the attributes of the specified member. If the parameter member is null, the function returns the class-level attributes.
instance instance instance() Returns a new instance of the class. This function does not invoke the instance constructor. The constructor must be explicitly called (e.g., class_inst.constructor(class_inst)).
newmember void newmember(any key, any value, table attributes = {}, bool static = false) Sets/adds the slot key with the value val and attributes attributes and, if present, invokes the _newmember metamethod. If static is true, the slot will be added as static. If the slot does not exist, it will be created.
rawdelete any rawdelete(any key) Deletes the target slot without employing delegation. Returns null if the slot is missing; otherwise, returns the associated value.
rawget any rawget(any key) Retrieves the value of the specified key without employing delegation.
rawin bool rawin(any key) Checks for the presence of the specified key in the class without employing delegation.
rawnewmember void rawnewmember(any key, any value, table attributes = {}, bool static = false) Sets/adds the slot key with the value val and attributes attributes. If static is true, the slot will be added as static. If the slot does not exist, it will be created.
rawset class rawset(any key, any value) Sets the value of the specified key without employing delegation. Returns the class itself.
setattributes any setattributes(string member_name, any value) Sets the attribute of the specified member and returns the previous attribute value. If the parameter member is null, sets the class-level attributes.
tostring string tostring() Returns the string "(class: pointer)".

Class instance

Function Signature Description
getclass class getclass() Returns the class that created the instance.
rawget any rawget(any key) Retrieves the value of the specified key without employing delegation.
rawin bool rawin(any key) Checks for the presence of the specified key in the instance without employing delegation.
rawset instance rawset(any key, any value) Sets the value of the specified key without employing delegation. Returns the instance itself.
tostring string tostring() Tries to invoke the _tostring metamethod. If that fails returns the string "(instance: pointer)".

Generator

Function Signature Description
getstatus string getstatus() Returns the status of the generator as string: "running", "dead" or "suspended".
tostring string tostring() Returns the string "(generator : pointer)".

Thread

Function Signature Description
newthread thread newthread(function threadfunc) Creates a new cooperative thread object(coroutine) and returns it.
Warning.pngWarning:Coroutines introduce their own additional overhead and require very specific configuration to avoid server crashes.
PlacementTip.pngWorkaround:Use a generator function instead. Generators can spread expensive functions across multiple frames to avoid stutters/timeouts. Real world TF2 example
call any call(any args...) Starts the thread with the specified parameters. Returns either the first suspend value or the returned value of the function if none suspends were triggered.
getstackinfos table getstackinfos(int level) Returns the stack frame informations at the given stack level (0 is the current function 1 is the caller and so on). If the stack level doesn't exist the function returns null.
getstatus string getstatus() Returns the status of the thread ("idle", "running", "suspended").
tostring string tostring() Returns the string "(thread : pointer)".
wakeup any wakeup(any return = null) Wakes up a suspended thread, accepts a optional parameter that will be used as return value for the function that suspended the thread(suspend method). The returned value will be received on the next thread suspension depending on what was passed in the suspend method.
wakeupthrow any wakeupthrow(any obj_to_throw, propagate_error = true) Wakes up a suspended thread, throwing an exception in the awaken thread, throwing the object obj_to_throw.

This is meant to be used with the thread.

Function Signature Description
suspend any suspend(any return = this) Suspends the coroutine that called this function. Needs to be called inside the thread's function body. Accepts a optional parameter that will be used as return value for the function that woke up the thread(wakeup method). If nothing is passed defaults to this(the scope in which this function was called). The returned value will be received on the next thread wake up depending on what was passed in the wakeup method.

Weak reference

Weak references let you reference an object without preventing it from being garbage collected. They're useful when you want to refer to an object, but don't want to increase its reference count and keep it alive unnecessarily. When the object pointed by weak reference is destroyed, the weak reference is automatically set to null. weakref method that returns weak reference to an object exist on every object in squirrel, but primitive types like numbers will return itself since they're stored differently, therefore making this method redundant. Everything else works as expected.

Function Signature Description
ref instance ref() Returns the object that the weak reference is pointing at. null if the object that was point at was destroyed.
tostring string tostring() Returns the string "(weakref : pointer)".

regexp

Function Signature Description
regexp regexp(string pattern) Create and compile a regular expression represented by the pattern.
Note.pngNote:Make sure to use double back slashes (\\ instead of \) if you want to insert one in the regex instead of escaping a character.
Warning.pngWarning:Do not create a regular expression with empty string as it will lead to out of memory server crash.
capture table capture(string str, int start = 0) Returns an array of tables containing two indexes ("begin" and "end") of the first match of the regular expression in the string str. An array entry is created for each captured sub expressions. If no match occurs returns null. The search starts from the index start of the string, if start is omitted the search starts from the beginning of the string.
match bool match(string str) Returns a true if the regular expression matches the string str, otherwise returns false.
search table search(string str, int start = 0) Returns a table containing two indexes ("begin" and "end") of the first match of the regular expression in the string str, otherwise if no match occurs returns null. The search starts from the index start of the string, if start is omitted the search starts from the beginning of the string.
subexpcount int subexpcount() Counts the amount of groups present in the regular expression, note that the whole regex is considered a group so the result will always be ≥ 1.

Blob

A blob stores a block of binary data. See official documentation for more information.

Note.pngNote:Each blob is restricted to a maximum size of 16 megabytes. Blobs are also limited to 32 megabytes total at any given time.
Function Signature Description
blob blob(int init_size = 0)
eos int eos()
flush flush()
len int len()
readblob blob readblob(int number_of_bytes)
readn any readn(char data_type)
resize void resize(int new_size)
seek int seek(int offset, int offset_basis)
swap2 void swap2()
swap4 void swap4()
tell int tell()
writeblob void writeblob(blob blob)
writen void writen(number value, char data_type)

Script Debug

Functions for interacting with the debugger. Some of them are documented here.

Function Signature Description
BeginScriptDebug void BeginScriptDebug()
EndScriptDebug void EndScriptDebug()
ScriptDebugAddTextFilter void ScriptDebugAddTextFilter()
ScriptDebugAddTrace void ScriptDebugAddTrace()
ScriptDebugAddWatch void ScriptDebugAddWatch()
ScriptDebugAddWatches void ScriptDebugAddWatches()
ScriptDebugAddWatchPattern void ScriptDebugAddWatchPattern()
ScriptDebugClearTraces void ScriptDebugClearTraces()
ScriptDebugClearWatches void ScriptDebugClearWatches()
ScriptDebugDefaultWatchColor void ScriptDebugDefaultWatchColor()
ScriptDebugDraw void ScriptDebugDraw()
ScriptDebugDrawWatches void ScriptDebugDrawWatches()
ScriptDebugDumpKeys void ScriptDebugDumpKeys()
ScriptDebugHook void ScriptDebugHook()
ScriptDebugIterateKeys void ScriptDebugIterateKeys()
ScriptDebugIterateKeysRecursive void ScriptDebugIterateKeysRecursive()
ScriptDebugRemoveTextFilter void ScriptDebugRemoveTextFilter()
ScriptDebugRemoveTrace void ScriptDebugRemoveTrace()
ScriptDebugRemoveWatch void ScriptDebugRemoveWatch()
ScriptDebugRemoveWatches void ScriptDebugRemoveWatches()
ScriptDebugRemoveWatchPattern void ScriptDebugRemoveWatchPattern()
ScriptDebugText void ScriptDebugText()
ScriptDebugTextDraw void ScriptDebugTextDraw()
ScriptDebugTextPrint void ScriptDebugTextPrint()
ScriptDebugTextTrace void ScriptDebugTextTrace()
ScriptDebugTraceAll void ScriptDebugTraceAll()
ScriptDebugWatches void ScriptDebugWatches()
__VScriptServerDebugHook __VScriptServerDebugHook()

See also