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
m (Fixed two more formatting errors)
No edit summary
 
(510 intermediate revisions by 43 users not shown)
Line 1: Line 1:
{{stub}}
{{LanguageBar}}
{{TF2 topicon|docs}}
{{toc-right}}
{{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]].}}


{{warning|This page is still work-in-progress, many functions lack documentation and testing.}}
== Instances ==
{{note|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.}}
{| class = "standard-table"
{{todo|Copy over documentation from the [[List_of_L4D2_Script_Functions|L4D2 page]], since {{tf2}} is derived from the VScript version as {{l4d2}}.}}
! Name
 
! Class
{{todo|Constants and variables (e.g. PI)}}
 
{{todo|Figure out inheritance, currently some methods are listed redundantly on each derived child}}
 
{{todo|Format the constructors more nicely}}
 
<!-- These line breaks were always here, and are to put the section at the bottom of the TOC table -->
<!-- 25 line breaks here, currently -->
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
 
== Classes ==
=== 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:
* <code>[[#CEntities|Entities]]</code> instance.
* [[Entity Scripts]] only - The <code>self</code> keyword.
 
{| class = "standard-table" style = "width: 85%;"
! Function
! Signature
! Description
! Description
|-
|-
| <code>__KeyValueFromFloat</code>
| <code>Convars</code>
| <code>__KeyValueFromFloat(string, num)</code>
| <code>[[#Convars|Convars ↓]]</code>
|  
| Provides an interface to read and change the values of console variables.
|-
| <code>Entities</code>
| <code>[[#CEntities|CEntities ↓]]</code>
| Provides access to currently spawned entities.
|-
|-
| <code>__KeyValueFromInt</code>
| <code>EntityOutputs</code>
| <code>__KeyValueFromInt(string, num)</code>
| <code>[[#CScriptEntityOutputs|CScriptEntityOutputs ↓]]</code>
|  
| Allows manipulation of entity output data.
|-
|-
| <code>__KeyValueFromString</code>
| <code>NavMesh</code>
| <code>__KeyValueFromString(string, string)</code>
| <code>[[#CNavMesh|CNavMesh ↓]]</code>
|  
| Provides access to the maps NavMesh and NavAreas.
|-
|-
| <code>__KeyValueFromVector</code>
| <code>NetProps</code>
| <code>__KeyValueFromVector(string, Vector)</code>
| <code>[[#CNetPropManager|CNetPropManager ↓]]</code>
|  
| Allows reading and updating the network properties of an entity.
|-
|-
| <code>ApplyAbsVelocityImpulse</code>
| <code>PlayerVoiceListener</code>
| <code>void ApplyAbsVelocityImpulse(Vector)</code>
| <code>[[#CPlayerVoiceListener|CPlayerVoiceListener ↓]]</code>
| Apply a Velocity Impulse
| Tracks if any player is using voice and for how long.
|}
 
== Variables ==
{| class = "standard-table"
! Name
! Type
! Value / Description
|-
|-
| <code>ApplyLocalAngularVelocityImpulse</code>
| <code>__FILE__</code>
| <code>void ApplyLocalAngularVelocityImpulse(Vector)</code>
| string
| Apply an Ang Velocity Impulse
| File name of the currently executing script.
|-
|-
| <code>ConnectOutput</code>
| <code>__LINE__</code>
| <code>void ConnectOutput(string, string)</code>
| integer
| Adds an I/O connection that will call the named function when the specified output fires
| Line number of the currently executing code.
|-
|-
| <code>Destroy</code>
| <code>[[Team_Fortress_2/Scripting/Script_Functions/Constants|Constants]]</code>
| <code>void Destroy()</code>
| table
|  
| Enumerations for various function arguments or netprops.
|-
|-
| <code>DisableDraw</code>
| <code>Documentation</code>
| <code>void DisableDraw()</code>
| table
| Enable drawing (removes EF_NODRAW)
| Contains the printed strings from the <code>script_help</code> command.
|-
|-
| <code>DisconnectOutput</code>
| <code>GameEventCallbacks</code>
| <code>void DisconnectOutput(string, string)</code>
| table
| Removes a connected script function from an I/O event.
| Table of registered game event callbacks.
|-
|-
| <code>DispatchSpawn</code>
| <code>print_indent</code>
| <code>void DispatchSpawn()</code>
| integer
| Alternative dispatch spawn, same as the one in CEntities, for convenience.
| 0. Spaces to indent prints by, except ones from <code>realPrint</code>.
|-
|-
| <code>EmitSound</code>
| <code>_PublishedHelp</code>
| <code>void EmitSound(string)</code>
| table
| Plays a sound from this entity.
| NONE
|-
|-
| <code>EnableDraw</code>
| <code>ScriptEventCallbacks</code>
| <code>void EnableDraw()</code>
| table
| Disable drawing (sets EF_NODRAW)
| Table of registered script event callbacks.
|-
|-
| <code>entindex</code>
| <code>ScriptHookCallbacks</code>
| <code>int entindex()</code>
| table
|  
| Table of registered script hook callbacks.
|}
 
=== Script Debug ===
{| class = "standard-table"
! Name
! Type
! Value
|-
|-
| <code>EyePosition</code>
| <code>ScriptDebugDefaultWatchColor</code>
| <code>Vector EyePosition()</code>
| array
| Get vector to eye position - absolute coords
| [0, 192, 0]
|-
|-
| <code>FirstMoveChild</code>
| <code>ScriptDebugDrawTextEnabled</code>
| <code>handle FirstMoveChild()</code>
| bool
|  
| true
|-
|-
| <code>GetAbsAngles</code>
| <code>ScriptDebugDrawWatchesEnabled</code>
| <code>QAngle GetAbsAngles()</code>
| bool
| Get entity pitch, yaw, roll as QAngles
| true
|-
|-
| <code>GetAngles</code>
| <code>ScriptDebugInDebugDraw</code>
| <code>Vector GetAngles()</code>
| bool
| !!!LEGACY FOR COMPAT!!! DO NOT USE ME. Get entity pitch, yaw, roll as a vector
| false
|-
|-
| <code>GetAngularVelocity</code>
| <code>ScriptDebugText</code>
| <code>Vector GetAngularVelocity()</code>
| array
| Get the local angular velocity - returns a vector of pitch,yaw,roll
| NONE
|-
|-
| <code>GetBaseVelocity</code>
| <code>ScriptDebugTextIndent</code>
| <code>Vector GetBaseVelocity()</code>
| integer
| Get Base? velocity
| 0
|-
|-
| <code>GetBoundingMaxs</code>
| <code>ScriptDebugTextFilters</code>
| <code>Vector GetBoundingMaxs()</code>
| table
| Get a vector containing max bounds, centered on object
| NONE
|-
|-
| <code>GetBoundingMaxsOriented</code>
| <code>ScriptDebugTraces</code>
| <code>Vector GetBoundingMaxsOriented()</code>
| table
| Get a vector containing max bounds, centered on object, taking the object's orientation into account
| NONE
|-
|-
| <code>GetBoundingMins</code>
| <code>ScriptDebugTraceAllOn</code>
| <code>Vector GetBoundingMins()</code>
| bool
| Get a vector containing min bounds, centered on object
| false
|-
|-
| <code>GetBoundingMinsOriented</code>
| <code>ScriptDebugWatches</code>
| <code>Vector GetBoundingMinsOriented()</code>
| array
| Get a vector containing min bounds, centered on object, taking the object's orientation into account
| NONE
|}
 
=== Constants ===
A [https://en.wikipedia.org/wiki/Constant_(computer_programming) constant] is a variable whose value cannot be altered during program runtime, usually made to rid any instances of [https://en.wikipedia.org/wiki/Magic_number_(programming) magic numbers] by giving them self-documenting names.
 
{| class = "standard-table"
! Name
! Type
! Value
|-
|-
| <code>GetCenter</code>
| <code>_charsize_</code>
| <code>Vector GetCenter()</code>
| integer
| Get vector to center of object - absolute coords
| 1
|-
|-
| <code>GetClassname</code>
| <code>_floatsize_</code>
| <code>string GetClassname()</code>
| integer
|  
| 4
|-
|-
| <code>GetEntityHandle</code>
| <code>_intsize_</code>
| <code><unknown> GetEntityHandle()</code>
| integer
| Get the entity as an EHANDLE
| 32-bit: 4
64-bit: 8
|-
|-
| <code>GetEntityIndex</code>
| <code>_version_</code>
| <code>int GetEntityIndex()</code>
| string
|  
| "Squirrel 3.2 stable"
|-
|-
| <code>GetForwardVector</code>
| <code>_versionnumber_</code>
| <code>Vector GetForwardVector()</code>
| integer
| Get the forward vector of the entity
| 320
|-
|-
| <code>GetFriction</code>
| <code>RAND_MAX</code>
| <code>float GetFriction()</code>
| integer
| Get PLAYER friction, ignored for objects
| Windows: 32767
Linux: 2147483647
|-
|-
| <code>GetHealth</code>
| <code>PI</code>
| <code>int GetHealth()</code>
| float
|
| 3.14159
|-
|}
| <code>GetLeftVector</code>
 
| <code>Vector GetLeftVector()</code>
=== Enums ===
| !!!LEGACY FOR COMPAT!!! Get the **right** vector of the entity. This is purely for compatibility. DO NOT USE ME. Use GetRightVector!
:''See [[Team_Fortress_2/Scripting/Script_Functions/Constants|this page]] for all enums under the <code>Constants</code> table.''
|-
 
| <code>GetLocalAngles</code>
There are also [https://en.wikipedia.org/wiki/Enumerated_type enums] kept within the <code>Constants</code> table, all with their own constants. For an example of accessing an enum's constant, the <code>HIDEHUD_CROSSHAIR</code> constant of the enum <code>HideHUD</code> is accessed by doing ''<code>Constants.HideHUD.HIDEHUD_CROSSHAIR</code>''.
| <code>QAngle GetLocalAngles()</code>
 
|  
== 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 ===
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:
* <code>[[#CEntities|Entities ↓]]</code> instance.
* <code>EntIndexToHScript</code> function.
* [[Entity Scripts]] only - The <code>self</code> keyword.
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
|-
| <code>GetLocalOrigin</code>
| {{obs}} <code>__KeyValueFromFloat (&rarr; KeyValueFromFloat)</code>
| <code>Vector GetLocalOrigin()</code>
| <code>bool __KeyValueFromFloat(string ''key'', float ''value'')</code>
|  
| Behaves the same as <code>KeyValueFromFloat</code>, use that instead.
|-
|-
| <code>GetLocalVelocity</code>
| {{obs}} <code>__KeyValueFromInt (&rarr; KeyValueFromInt)</code>
| <code>Vector GetLocalVelocity()</code>
| <code>bool __KeyValueFromInt(string ''key'', int ''value'')</code>
| Get Entity relative velocity
| Behaves the same as <code>KeyValueFromInt</code>, use that instead.
|-
|-
| <code>GetMaxHealth</code>
| {{obs}} <code>__KeyValueFromString (&rarr; KeyValueFromString)</code>
| <code>int GetMaxHealth()</code>
| <code>bool __KeyValueFromString(string ''key'', string ''value'')</code>
|  
| Behaves the same as <code>KeyValueFromString</code>, use that instead.
|-
|-
| <code>GetModelKeyValues</code>
| {{obs}} <code>__KeyValueFromVector (&rarr; KeyValueFromVector)</code>
| <code>handle GetModelKeyValues()</code>
| <code>bool __KeyValueFromVector(string ''key'', Vector ''value'')</code>
| Get a KeyValue class instance on this entity's model
| Behaves the same as <code>KeyValueFromVector</code>, use that instead.
|-
|-
| <code>GetModelName</code>
| <code>AcceptInput</code>
| <code>string GetModelName()</code>
| <code>bool AcceptInput(string ''input'', string ''param'', handle ''activator'', handle ''caller'')</code>
| Returns the name of the model
| 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>GetMoveParent</code>
| <code>AddEFlags</code>
| <code>handle GetMoveParent()</code>
| <code>void AddEFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FEntityEFlags|FEntityEFlags]] ''flags'')</code>
| If in hierarchy, retrieves the entity's parent
| Adds the supplied ''flags'' to the '''Entity Flags''' in the entity. ''(m_iEFlags datamap)''
{{note|Adding <code>EFL_KILLME</code> will make the entity unkillable, even on round resets, until the flag is removed.}}
|-
|-
| <code>GetName</code>
| <code>AddFlag</code>
| <code>string GetName()</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)''
|-
|-
| <code>GetOrigin</code>
| <code>AddSolidFlags</code>
| <code>Vector GetOrigin()</code>
| <code>void AddSolidFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FSolid|FSolid]] ''flags'')</code>
| This is GetAbsOrigin with a funny script name for some reason. Not changing it for legacy compat though.
| Adds the supplied ''flags'' to the ''Solid Flags'' in the entity. ''(m_Collision.m_usSolidFlags datamap)''
|-
|-
| <code>GetOwner</code>
| <code>ApplyAbsVelocityImpulse</code>
| <code>handle GetOwner()</code>
| <code>void ApplyAbsVelocityImpulse(Vector ''impulse'')</code>
| Gets this entity's owner
| Apply a Velocity Impulse as a world space impulse vector. Works for most physics-based objects including dropped weapons and even dropped Sandviches.
|-
|-
| <code>GetPreTemplateName</code>
| <code>ApplyLocalAngularVelocityImpulse</code>
| <code>string GetPreTemplateName()</code>
| <code>void ApplyLocalAngularVelocityImpulse(Vector ''impulse'')</code>
| Get the entity name stripped of template unique decoration
| 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.
|-
|-
| <code>GetRightVector</code>
| <code>BecomeRagdollOnClient</code>
| <code>Vector GetRightVector()</code>
| <code>bool BecomeRagdollOnClient(Vector ''impulse'')</code>
| Get the right vector of the 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>GetRootMoveParent</code>
| <code>ClearFlags</code>
| <code>handle GetRootMoveParent()</code>
| <code>void ClearFlags()</code>
| If in hierarchy, walks up the hierarchy to find the root parent
| Sets the player-related entity flags to 0 on an entity, clearing them.
|-
|-
| <code>GetScriptId</code>
| <code>ClearSolidFlags</code>
| <code>string GetScriptId()</code>
| <code>void ClearSolidFlags()</code>
| Retrieve the unique identifier used to refer to the entity within the scripting system
| Sets ''Solid Flags'' to 0 on an entity, clearing them.
|-
|-
| <code>GetScriptScope</code>
| <code>ConnectOutput</code>
| <code>handle GetScriptScope()</code>
| <code>void ConnectOutput(string ''output_name'', string ''function_name'')</code>
| Retrieve the script-side data associated with an entity
| 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>GetSoundDuration</code>
| <code>Destroy</code>
| <code>float GetSoundDuration(string, string)</code>
| <code>void Destroy()</code>
| Returns float duration of the sound. Takes soundname and optional actormodelname.
| Removes the entity. Simply calls [[UTIL_Remove]].
|-
|-
| <code>GetTeam</code>
| <code>DisableDraw</code>
| <code>int GetTeam()</code>
| <code>void DisableDraw()</code>
|  
| Disable drawing and transmitting the entity to clients. ''(adds EF_NODRAW)''
|-
|-
| <code>GetUpVector</code>
| <code>DisconnectOutput</code>
| <code>Vector GetUpVector()</code>
| <code>void DisconnectOutput(string ''output_name'', string ''function_name'')</code>
| Get the up vector of the entity
| Removes a connected script function from an I/O event.
|-
|-
| <code>GetVelocity</code>
| <code>DispatchSpawn</code>
| <code>Vector GetVelocity()</code>
| <code>void DispatchSpawn()</code>
|  
| 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>IsPlayer</code>
| <code>EmitSound</code>
| <code>bool IsPlayer()</code>
| <code>void EmitSound(string ''sound_name'')</code>
|  
| 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>IsValid</code>
| <code>EnableDraw</code>
| <code>IsValid()</code>
| <code>void EnableDraw()</code>
|  
| Enable drawing and transmitting the entity to clients. ''(removes EF_NODRAW)''
|-
|-
| <code>KeyValueFromFloat</code>
| <code>entindex</code>
| <code>bool KeyValueFromFloat(string, float)</code>
| <code>int entindex()</code>
| Executes KeyValue with a float
| Returns the entity index.
|-
|-
| <code>KeyValueFromInt</code>
| <code>EyeAngles</code>
| <code>bool KeyValueFromInt(string, int)</code>
| <code>QAngle EyeAngles()</code>
| Executes KeyValue with an int
| Returns the entity's eye angles. Acts like <code>GetAbsAngles</code> if the entity does not support it.
|-
|-
| <code>KeyValueFromString</code>
| <code>EyePosition</code>
| <code>bool KeyValueFromString(string, string)</code>
| <code>Vector EyePosition()</code>
| Executes KeyValue with a string
| Get vector to eye position - absolute coords. Acts like <code>GetOrigin</code> if the entity does not support it.
|-
|-
| <code>KeyValueFromVector</code>
| <code>FirstMoveChild</code>
| <code>bool KeyValueFromVector(string, Vector)</code>
| <code>handle FirstMoveChild()</code>
| Executes KeyValue with a vector
| Returns the most-recent entity parented to this one.
{{tip|Example usage: <source lang=js>for (local child = entity.FirstMoveChild(); child != null; child = child.NextMovePeer())</source>}}
|-
|-
| <code>Kill</code>
| <code>GetAbsAngles</code>
| <code>void Kill()</code>
| <code>QAngle GetAbsAngles()</code>
|  
| Get the entity's pitch, yaw, and roll as '''QAngles'''.
|-
|-
| <code>NextMovePeer</code>
| <code>GetAbsVelocity</code>
| <code>handle NextMovePeer()</code>
| <code>Vector GetAbsVelocity()</code>
|  
| Returns the current absolute velocity of the entity.
|-
|-
| <code>PrecacheModel</code>
| {{obs}} <code>GetAngles (&rarr; GetAbsAngles)</code>
| <code>void PrecacheModel(string)</code>
| <code>Vector GetAngles()</code>
|  
| Get the entity's pitch, yaw, and roll as a '''Vector'''.
|-
|-
| <code>PrecacheScriptSound</code>
| <code>GetAngularVelocity</code>
| <code>void PrecacheScriptSound(string)</code>
| <code>Vector GetAngularVelocity()</code>
|  
| Get the local angular velocity - returns a '''Vector''' of pitch, yaw, and roll.
|-
|-
| <code>PrecacheSoundScript</code>
| <code>GetBaseVelocity</code>
| <code>void PrecacheSoundScript(string)</code>
| <code>Vector GetBaseVelocity()</code>
| Precache a sound for later playing.
| 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>SetAbsAngles</code>
| <code>GetBoundingMaxs</code>
| <code>void SetAbsAngles(QAngle)</code>
| <code>Vector GetBoundingMaxs()</code>
| Set entity pitch, yaw, roll as QAngles
| Get a vector containing max bounds, centered on object.
|-
|-
| <code>SetAbsOrigin</code>
| <code>GetBoundingMaxsOriented</code>
| <code>void SetAbsOrigin(Vector)</code>
| <code>Vector GetBoundingMaxsOriented()</code>
| SetAbsOrigin
| 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>SetAngles</code>
| <code>GetBoundingMins</code>
| <code>void SetAngles(float, float, float)</code>
| <code>Vector GetBoundingMins()</code>
| !!!LEGACY FOR COMPAT!!! DO NOT USE ME. Set entity pitch, yaw, roll
| Get a vector containing min bounds, centered on object.
|-
|-
| <code>SetAngularVelocity</code>
| <code>GetBoundingMinsOriented</code>
| <code>void SetAngularVelocity(float, float, float)</code>
| <code>Vector GetBoundingMinsOriented()</code>
| Set the local angular velocity - takes float pitch,yaw,roll velocities
| 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>SetDrawEnabled</code>
| <code>GetCenter</code>
| <code>void SetDrawEnabled(bool)</code>
| <code>Vector GetCenter()</code>
| Enables drawing if you pass true, disables drawing if you pass false.
| Gets center point of the entity in world coordinates.
|-
|-
| <code>SetForwardVector</code>
| <code>GetClassname</code>
| <code>void SetForwardVector(Vector)</code>
| <code>string GetClassname()</code>
| Set the orientation of the entity to have this forward vector
|
|-
|-
| <code>SetFriction</code>
| <code>GetCollisionGroup</code>
| <code>void SetFriction(float)</code>
| <code>int GetCollisionGroup()</code>
| Set PLAYER friction, ignored for objects
| Gets the current collision group of the entity.
See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ECollisionGroup|Constants.ECollisionGroup]]
|-
|-
| <code>SetGravity</code>
| <code>GetEFlags</code>
| <code>void SetGravity(float)</code>
| <code>int GetEFlags()</code>
| Set PLAYER gravity, ignored for objects
| Get the entity's engine flags.
See [[Team_Fortress_2/Scripting/Script_Functions/Constants#FEntityEFlags|Constants.FEntityEFlags]].
|-
|-
| <code>SetHealth</code>
| <code>GetFlags</code>
| <code>void SetHealth(int)</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>SetLocalAngles</code>
| <code>GetEntityHandle</code>
| <code>void SetLocalAngles(QAngle)</code>
| <code>ehandle GetEntityHandle()</code>
|  
| Get the entity as an EHANDLE.
{{deprecated|Leftover from earlier versions of VScript.}}
|-
|-
| <code>SetLocalOrigin</code>
| <code>GetEntityIndex</code>
| <code>void SetLocalOrigin(Vector)</code>
| <code>int GetEntityIndex()</code>
|  
|
|-
|-
| <code>SetMaxHealth</code>
| <code>GetForwardVector</code>
| <code>void SetMaxHealth(int)</code>
| <code>Vector GetForwardVector()</code>
|  
| 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>SetModel</code>
| <code>GetFriction</code>
| <code>void SetModel(string)</code>
| <code>float GetFriction()</code>
| Set a model for this entity
| Get PLAYER friction, ignored for objects.
|-
|-
| <code>SetOrigin</code>
| <code>GetGravity</code>
| <code>void SetOrigin(Vector)</code>
| <code>float GetGravity()</code>
| THIS DOESNT CALL SetAbsOrigin IT CALLS Teleport
|
|-
|-
| <code>SetOwner</code>
| <code>GetHealth</code>
| <code>void SetOwner(handle)</code>
| <code>int GetHealth()</code>
| Sets this entity's owner
|
|-
|-
| <code>SetSize</code>
|style=white-space:nowrap| {{obs}} <code>GetLeftVector (&rarr; GetRightVector)</code>
| <code>void SetSize(Vector, Vector)</code>
| <code>Vector GetLeftVector()</code>
|  
| Get the ''right'' vector of the entity. This is purely for compatibility.
|-
|-
| <code>SetTeam</code>
| <code>GetLocalAngles</code>
| <code>void SetTeam(int)</code>
| <code>QAngle GetLocalAngles()</code>
|  
|
|-
|-
| <code>SetVelocity</code>
| <code>GetLocalOrigin</code>
| <code>void SetVelocity(Vector)</code>
| <code>Vector GetLocalOrigin()</code>
|  
|
|-
|-
| <code>StopSound</code>
| <code>GetLocalVelocity</code>
| <code>void StopSound(string)</code>
| <code>Vector GetLocalVelocity()</code>
| Stops a sound on this entity.
| Get Entity relative velocity.
|-
|-
| <code>TakeDamage</code>
| <code>GetMaxHealth</code>
| <code>void TakeDamage(float, int, handle)</code>
| <code>int GetMaxHealth()</code>
| (flDamage, nDamageType, hAttacker)
|
|-
|-
| <code>TakeDamageEx</code>
| <code>GetModelKeyValues</code>
| <code>void TakeDamageEx(handle, handle, handle, Vector, Vector, float, int)</code>
| <code>CScriptKeyValues GetModelKeyValues()</code>
| (hInflictor, hAttacker, hWeapon, vecDamageForce, vecDamagePosition, flDamage, nDamageType)
| Get a KeyValue class instance on this entity's model.
|-
|-
| <code>ValidateScriptScope</code>
| <code>GetModelName</code>
| <code>bool ValidateScriptScope()</code>
| <code>string GetModelName()</code>
| Ensure that an entity's script scope has been created
| 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()


=== CBaseAnimating ===
local model = wearable.GetModelName()
Extends [[#CBaseEntity|CBaseEntity]]


Script handle class for animatable entities, such as props.
wearable.Destroy()


{| class = "standard-table" style = "width: 85%;"
return model
! Function
}
! Signature
</source>}}
! Description
}}
|-
|-
| <code>FindBodygroupByName</code>
| <code>GetMoveParent</code>
| <code>int FindBodygroupByName(string)</code>
| <code>handle GetMoveParent()</code>
| Find a bodygroup id by name
| If in hierarchy, retrieves the entity's parent.
|-
|-
| <code>GetAttachmentAngles</code>
| <code>GetMoveType</code>
| <code>QAngle GetAttachmentAngles(int)</code>
| <code>int GetMoveType()</code>
| Get the attachement id's angles as a p,y,r vector
|
|-
|-
| <code>GetAttachmentBone</code>
| <code>GetName</code>
| <code>int GetAttachmentBone(int)</code>
| <code>string GetName()</code>
| Get the named attachement's parent bone index
| Get entity's targetname.
|-
|-
| <code>GetAttachmentOrigin</code>
| <code>GetOrigin</code>
| <code>Vector GetAttachmentOrigin(int)</code>
| <code>Vector GetOrigin()</code>
| Get the attachement id's origin vector
| This is <code>GetAbsOrigin</code> with a funny script name for some reason. Not changing it for legacy compat though.
|-
|-
| <code>GetBodygroup</code>
| <code>GetOwner</code>
| <code>int GetBodygroup(int)</code>
| <code>handle GetOwner()</code>
| Get a bodygroup by id
| 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>GetBodygroupName</code>
| <code>GetPhysAngularVelocity</code>
| <code>string GetBodygroupName(int)</code>
| <code>Vector GetPhysAngularVelocity()</code>
| Get the bodygroup id's name
|
|-
|-
| <code>GetBodygroupPartName</code>
| <code>GetPhysVelocity</code>
| <code>string GetBodygroupPartName(int, int)</code>
| <code>Vector GetPhysVelocity()</code>
| Get name by group and part
|
|-
|-
| <code>GetBoneAngles</code>
| <code>GetPreTemplateName</code>
| <code>QAngle GetBoneAngles(int)</code>
| <code>string GetPreTemplateName()</code>
| Get the bone id's angles as a p,y,r vector
| Get the entity name stripped of template unique decoration.
|-
|-
| <code>GetBoneOrigin</code>
| <code>GetRightVector</code>
| <code>Vector GetBoneOrigin(int)</code>
| <code>Vector GetRightVector()</code>
| Get the bone id's origin vector
| Get the right vector of the entity.
|-
|-
| <code>GetModelScale</code>
| <code>GetRootMoveParent</code>
| <code>float GetModelScale()</code>
| <code>handle GetRootMoveParent()</code>
|  
| If in hierarchy, walks up the hierarchy to find the root parent.
|-
|-
| <code>GetSequence</code>
| <code>GetScriptId</code>
| <code>int GetSequence()</code>
| <code>string GetScriptId()</code>
| Get the current sequence id
| Retrieve the unique identifier used to refer to the entity within the scripting system.
|-
|-
| <code>GetSequenceActivityName</code>
| <code>GetScriptScope</code>
| <code>string GetSequenceActivityName(int)</code>
| <code>table GetScriptScope()</code>
| Get the activity name for a sequence by id
| Retrieve the script-side data associated with an entity.
|-
|-
| <code>GetSequenceDuration</code>
| <code>GetScriptThinkFunc</code>
| <code>float GetSequenceDuration(int)</code>
| <code>string GetScriptThinkFunc()</code>
| Get a sequence duration by id
| Retrieve the name of the current script think func.
|-
|-
| <code>GetSequenceName</code>
| <code>GetSolid</code>
| <code>string GetSequenceName(int)</code>
| <code>int GetSolid()</code>
| Get a sequence name by id
| See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ESolidType|ESolidType]].
|-
|-
| <code>GetSkin</code>
| <code>GetSoundDuration</code>
| <code>int GetSkin()</code>
| <code>float GetSoundDuration(string ''sound_name'', string ''actor_model_name'')</code>
| Gets the current skin index.
| 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.}}
|-
|-
| <code>IsSequenceFinished</code>
| <code>GetTeam</code>
| <code>bool IsSequenceFinished()</code>
| <code>int GetTeam()</code>
| Ask whether the main sequence is done playing
| See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]].
|-
|-
| <code>LookupActivity</code>
| <code>GetUpVector</code>
| <code>int LookupActivity(string)</code>
| <code>Vector GetUpVector()</code>
| Get the named activity index
| Get the up vector of the entity.
|-
|-
| <code>LookupAttachment</code>
| {{obs}} <code>GetVelocity (&rarr; GetAbsVelocity)</code>
| <code>int LookupAttachment(string)</code>
| <code>Vector GetVelocity()</code>
| Get the named attachement id
|
|-
|-
| <code>LookupBone</code>
| <code>GetWaterLevel</code>
| <code>int LookupBone(string)</code>
| <code>int GetWaterLevel()</code>
| Get the named bone index
| 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>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>LookupSequence</code>
| <code>IsEFlagSet</code>
| <code>int LookupSequence(string)</code>
| <code>bool IsEFlagSet([[Team_Fortress_2/Scripting/Script_Functions/Constants#FEntityEFlags|FEntityEFlags]] ''flag'')</code>
| Looks up a sequence by sequence name or activity name
|
|-
|-
| <code>ResetSequence</code>
| <code>IsPlayer</code>
| <code>void ResetSequence(int)</code>
| <code>bool IsPlayer()</code>
| Reset a sequence by id. If the id is different than the current sequence, switch to the new sequence
| Checks whether the entity is a player or not.
|-
|-
| <code>SetBodygroup</code>
| <code>IsSolid</code>
| <code>void SetBodygroup(int, int)</code>
| <code>bool IsSolid()</code>
| Sets a bodygroup
|
|-
|-
| <code>SetModelScale</code>
| <code>IsSolidFlagSet</code>
| <code>void SetModelScale(float, float)</code>
| <code>bool IsSolidFlagSet([[Team_Fortress_2/Scripting/Script_Functions/Constants#FSolid|FSolid]] ''flag'')</code>
| (scale, change_duration) Changes a model's scale over time
|
|-
|-
| <code>SetPoseParameter</code>
| <code>IsValid</code>
| <code>float SetPoseParameter(int, float)</code>
| <code>bool IsValid()</code>
| (id, value) Sets a pose parameter value
| Checks whether the entity still exists. Useful when storing entity handles and needing to check if the entity was not deleted.
{{note|This function is never necessary to call on handles returned from built-in script functions, as they are guaranteed to be valid or <code>null</code>.}}
|-
|-
| <code>SetSequence</code>
| <code>KeyValueFromFloat</code>
| <code>void SetSequence(int)</code>
| <code>bool KeyValueFromFloat(string ''key'', float ''value'')</code>
| Set a sequence by id
| 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. [[#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>SetSkin</code>
| <code>KeyValueFromInt</code>
| <code>void SetSkin(int)</code>
| <code>bool KeyValueFromInt(string ''key'', int ''value'')</code>
| Sets the skin.
| Executes KeyValue with an int.
|}
{{warning|See above.}}
 
 
=== CBasePlayer ===
Extends [[#CBaseAnimating|CBaseAnimating]]
 
Script handle class for player entities.
 
{| class = "standard-table" style = "width: 85%;"
! Function
! Signature
! Description
|-
|-
| <code>IsNoclipping</code>
| <code>KeyValueFromString</code>
| <code>bool IsNoclipping()</code>
| <code>bool KeyValueFromString(string ''key'', string ''value'')</code>
| Returns true if the player is in noclip mode.
| Executes KeyValue with a string.
|}
{{warning|See above.}}
 
 
=== CBaseMultiplayerPlayer ===
Extends [[#CBasePlayer|CBasePlayer]]
 
Script handle sub-classes for player entities in multiplayer games. No additional methods.
 
 
=== CTFPlayer ===
Extends [[#CBaseMultiplayerPlayer|CBaseMultiplayerPlayer]]
 
Script handle class for TF2s player entities.
 
{| class = "standard-table" style = "width: 85%;"
! Function
! Signature
! Description
|-
|-
| <code>AddCond</code>
| <code>KeyValueFromVector</code>
| <code>void AddCond(string)</code>
| <code>bool KeyValueFromVector(string ''key'', Vector ''value'')</code>
|  
| Executes KeyValue with a vector.
{{warning|See above.}}
|-
|-
| <code>AddCondEx</code>
| <code>Kill</code>
| <code>void AddCondEx(string, float, handle)</code>
| <code>void Kill()</code>
|  
| 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>AddCustomAttribute</code>
| <code>LocalEyeAngles</code>
| <code>void AddCustomAttribute(string, float, float)</code>
| <code>QAngle LocalEyeAngles()</code>
| Add a custom attribute to the player
| Returns the entity's local eye angles.
|-
|-
| <code>ApplyPunchImpulseX</code>
| <code>NextMovePeer</code>
| <code>bool ApplyPunchImpulseX(float)</code>
| <code>handle NextMovePeer()</code>
|  
| Returns the next entity parented ''with'' the entity. Intended for iteration use with <code>FirstMoveChild()</code>.
|-
|-
| <code>CanAirDash</code>
| <code>PrecacheModel</code>
| <code>bool CanAirDash()</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>CanBeDebuffed</code>
| <code>PrecacheScriptSound</code>
| <code>bool CanBeDebuffed()</code>
| <code>void PrecacheScriptSound(string ''sound_script'')</code>
|  
| Precache a sound script. Same as <code>PrecacheSoundScript</code>.
|-
|-
| <code>CanBreatheUnderwater</code>
| <code>PrecacheSoundScript</code>
| <code>bool CanBreatheUnderwater()</code>
| <code>void PrecacheSoundScript(string ''sound_script'')</code>
|  
| Precache a sound script. Same as <code>PrecacheScriptSound</code>.
|-
|-
| <code>CanDuck</code>
| <code>RemoveEFlags</code>
| <code>bool CanDuck()</code>
| <code>void RemoveEFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FEntityEFlags|FEntityEFlags]] ''flags'')</code>
| Can the player duck?
|
|-
|-
| <code>CanGetWet</code>
| <code>RemoveFlag</code>
| <code>bool CanGetWet()</code>
| <code>void RemoveFlag([[Team_Fortress_2/Scripting/Script_Functions/Constants#FPlayer|FPlayer]] ''flags'')</code>
|  
|
|-
|-
| <code>CanJump</code>
| <code>RemoveSolidFlags</code>
| <code>bool CanJump()</code>
| <code>void RemoveSolidFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FSolid|FSolid]] ''flags'')</code>
| Can the player jump?
|
|-
|-
| <code>CanPlayerMove</code>
| <code>SetAbsAngles</code>
| <code>bool CanPlayerMove()</code>
| <code>void SetAbsAngles(QAngle ''angles'')</code>
| Can the player move?
| Set entity pitch, yaw, roll as QAngles. Does not work on players, use <code>SnapEyeAngles</code> instead.
|-
|-
| <code>DropFlag</code>
| <code>SetAbsVelocity</code>
| <code>void DropFlag(bool)</code>
| <code>void SetAbsVelocity(Vector ''velocity'')</code>
| Force player to drop the flag.
| 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>DropRune</code>
| <code>SetAbsOrigin</code>
| <code>void DropRune(bool, int)</code>
| <code>void SetAbsOrigin(Vector ''origin'')</code>
| Force player to drop the rune.
| 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.}}
|-
|-
| <code>FiringTalk</code>
| {{obs}} <code>SetAngles (&rarr; SetAbsAngles)</code>
| <code>void FiringTalk()</code>
| <code>void SetAngles(float ''pitch'', float ''yaw'', float ''roll'')</code>
| Makes eg. a heavy go AAAAAAAAAAaAaa like they are firing their minigun.
| Set entity angles.
|-
|-
| <code>FirstMoveChild</code>
| <code>SetAngularVelocity</code>
| <code>FirstMoveChild()</code>
| <code>void SetAngularVelocity(float ''pitch'', float ''yaw'', float ''roll'')</code>
|  
| Set the local angular velocity.
|-
|-
| <code>ForceChangeTeam</code>
| <code>SetCollisionGroup</code>
| <code>void ForceChangeTeam(int, bool)</code>
| <code>void SetCollisionGroup([[Team_Fortress_2/Scripting/Script_Functions/Constants#ECollisionGroup|ECollisionGroup]] ''group'')</code>
| Force player to change their team.
| Set the current collision group of the entity.
|-
|-
| <code>GetBackstabs</code>
| <code>SetDrawEnabled</code>
| <code>int GetBackstabs()</code>
| <code>void SetDrawEnabled(bool ''toggle'')</code>
|  
| Enables drawing if you pass true, disables drawing if you pass false.
|-
|-
| <code>GetBuildingsDestroyed</code>
| <code>SetEFlags</code>
| <code>int GetBuildingsDestroyed()</code>
| <code>void SetEFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FEntityEFlags|FEntityEFlags]] ''flags'')</code>
|  
|
|-
|-
| <code>GetCaptures</code>
| <code>SetForwardVector</code>
| <code>int GetCaptures()</code>
| <code>void SetForwardVector(Vector ''forward'')</code>
|  
| 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>GetClassEyeHeight</code>
| <code>SetFriction</code>
| <code>Vector GetClassEyeHeight()</code>
| <code>void SetFriction(float ''friction'')</code>
| Gets the eye height of the player
|
|-
|-
| <code>GetCondDuration</code>
| <code>SetGravity</code>
| <code>float GetCondDuration(string)</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>GetCurrentTauntMoveSpeed</code>
| <code>SetHealth</code>
| <code>float GetCurrentTauntMoveSpeed()</code>
| <code>void SetHealth(int ''health'')</code>
|  
|
|-
|-
| <code>GetDefenses</code>
| <code>SetLocalAngles</code>
| <code>int GetDefenses()</code>
| <code>void SetLocalAngles(QAngle ''angles'')</code>
|  
|
|-
|-
| <code>GetDisguiseAmmoCount</code>
| <code>SetLocalOrigin</code>
| <code>int GetDisguiseAmmoCount()</code>
| <code>void SetLocalOrigin(Vector ''origin'')</code>
|  
|
|-
| <code>SetMaxHealth</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>GetDisguiseTarget</code>
| <code>SetModel</code>
| <code>handle GetDisguiseTarget()</code>
| <code>void SetModel(string ''model_name'')</code>
|  
| 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>GetDisguiseTeam</code>
| <code>SetMoveType</code>
| <code>int GetDisguiseTeam()</code>
| <code>void SetMoveType([[Team_Fortress_2/Scripting/Script_Functions/Constants#EMoveType|EMoveType]] ''movetype'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#EMoveCollide|EMoveCollide]] ''movecollide'')</code>
|  
|
|-
|-
| <code>GetDominations</code>
| {{obs}} <code>SetOrigin (&rarr; SetAbsOrigin)</code>
| <code>int GetDominations()</code>
| <code>void SetOrigin(Vector ''origin'')</code>
|  
|
|-
|-
| <code>GetGrapplingHookTarget</code>
| <code>SetOwner</code>
| <code>handle GetGrapplingHookTarget()</code>
| <code>void SetOwner(handle ''entity'')</code>
| What entity is the player grappling?
| 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>GetHeadshots</code>
| <code>SetPhysAngularVelocity</code>
| <code>int GetHeadshots()</code>
| <code>void SetPhysAngularVelocity(Vector ''angular_velocity'')</code>
|  
|
|-
|-
| <code>GetHealPoints</code>
| <code>SetPhysVelocity</code>
| <code>int GetHealPoints()</code>
| <code>void SetPhysVelocity(Vector ''velocity'')</code>
|  
|
|-
|-
| <code>GetHealTarget</code>
| <code>SetSize</code>
| <code>handle GetHealTarget()</code>
| <code>void SetSize(Vector ''mins'', Vector ''maxs'')</code>
| Who is the medic healing?
| 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>GetInvulns</code>
| <code>SetSolid</code>
| <code>int GetInvulns()</code>
| <code>void SetSolid([[Team_Fortress_2/Scripting/Script_Functions/Constants#ESolidType|ESolidType]] ''solid'')</code>
|  
|
|-
| <code>SetSolidFlags</code>
| <code>void SetSolidFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FSolid|FSolid]] ''flags'')</code>
|
|-
|-
| <code>GetKillAssists</code>
| <code>SetTeam</code>
| <code>int GetKillAssists()</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>GetNextChangeClassTime</code>
| {{obs}} <code>SetVelocity (&rarr; SetAbsVelocity)</code>
| <code>float GetNextChangeClassTime()</code>
| <code>void SetVelocity(Vector ''velocity'')</code>
| Get next change class time.
|
|-
|-
| <code>GetNextChangeTeamTime</code>
| <code>SetWaterLevel</code>
| <code>float GetNextChangeTeamTime()</code>
| <code>void SetWaterLevel(int ''water_level'')</code>
| Get next change team time.
| 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>GetNextRegenTime</code>
| <code>SetWaterType</code>
| <code>float GetNextRegenTime()</code>
| <code>void SetWaterType(int ''water_type'')</code>
| Get next health regen time.
| Set the type of water the entity is currently submerged in. Generic values to use are 32 for water and 16 for slime.
|-
|-
| <code>GetRageMeter</code>
| <code>StopSound</code>
| <code>float GetRageMeter()</code>
| <code>void StopSound(string ''sound_name'')</code>
|  
| Stops a sound on this entity.
|-
|-
| <code>GetResupplyPoints</code>
| <code>TakeDamage</code>
| <code>int GetResupplyPoints()</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>GetRevenge</code>
| <code>TakeDamageEx</code>
| <code>int GetRevenge()</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>GetScoutHypeMeter</code>
| <code>TakeDamageCustom</code>
| <code>float GetScoutHypeMeter()</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>GetSpyCloakMeter</code>
| <code>Teleport</code>
| <code>float GetSpyCloakMeter()</code>
| <code>void Teleport(bool ''use_origin'', Vector ''origin'', bool ''use_angles'', QAngle ''angles'', bool ''use_velocity'', Vector ''velocity'')</code>
|  
| Teleports this entity. For this function, set the bools to false if you want that entity's property unchanged. (do not use null arguments!)
|-
|-
| <code>GetTeleports</code>
| <code>TerminateScriptScope</code>
| <code>int GetTeleports()</code>
| <code>void TerminateScriptScope()</code>
|  
| Clear the current script scope for this entity.
|-
|-
| <code>GetTimeSinceCalledForMedic</code>
| <code>ToggleFlag</code>
| <code>float GetTimeSinceCalledForMedic()</code>
| <code>void ToggleFlag([[Team_Fortress_2/Scripting/Script_Functions/Constants#FPlayer|FPlayer]] ''flags'')</code>
| When did the player last call medic
|
|-
|-
| <code>HasItem</code>
| <code>ValidateScriptScope</code>
| <code>bool HasItem()</code>
| <code>bool ValidateScriptScope()</code>
| Currently holding an item? Eg. capture flag
| 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).}}
|}
 
==== 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.
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
|-
| <code>InAirDueToExplosion</code>
| <code>Input<''name''></code>
| <code>bool InAirDueToExplosion()</code>
| <code>bool Input<''name''>()</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.
|-
{{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).}}
| <code>InAirDueToKnockback</code>
{{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>.}}
| <code>bool InAirDueToKnockback()</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
 
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())
</source>}}
|}
}}
|-
|-
| <code>InCond</code>
| <code>OnGameEvent_<''name''></code>
| <code>bool InCond(string)</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>IsAirDashing</code>
| <code>Precache</code>
| <code>bool IsAirDashing()</code>
| <code>void Precache()</code>
|  
| 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>IsAllowedToTaunt</code>
| <code>ConnectOutputs</code>
| <code>bool IsAllowedToTaunt()</code>
| <code>void ConnectOutputs(table ''scope'')</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.
{{note|This is a ''global'' hook and therefore will only work in global scope, unlike <code>Precache</code> and <code>OnPostSpawn</code>.}}
|-
|-
| <code>IsCallingForMedic</code>
| <code>OnPostSpawn</code>
| <code>bool IsCallingForMedic()</code>
| <code>void OnPostSpawn()</code>
| Is this player calling for medic?
| 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>IsCarryingRune</code>
| <code>OnScriptHook_OnTakeDamage</code>
| <code>bool IsCarryingRune()</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:
{| class="standard-table" style="width:100%"
! Name
! Type
! Description
|-
|-
| <code>IsControlStunned</code>
| <code>const_entity</code>
| <code>bool IsControlStunned()</code>
| <code>handle</code>
|  
| The entity which took damage.
|-
|-
| <code>IsCritBoosted</code>
| <code>inflictor</code>
| <code>bool IsCritBoosted()</code>
| <code>handle</code>
|  
| The entity which dealt the damage, can be null.
|-
|-
| <code>IsFireproof</code>
| <code>weapon</code>
| <code>bool IsFireproof()</code>
| <code>handle</code>
|  
| The weapon which dealt the damage, can be null.
|-
|-
| <code>IsFullyInvisible</code>
| <code>attacker</code>
| <code>bool IsFullyInvisible()</code>
| <code>handle</code>
|  
| The owner of the damage, can be null.
|-
|-
| <code>IsHypeBuffed</code>
| <code>damage</code>
| <code>bool IsHypeBuffed()</code>
| <code>float</code>
|  
| Damage amount.
|-
|-
| <code>IsImmuneToPushback</code>
| <code>max_damage</code>
| <code>bool IsImmuneToPushback()</code>
| <code>float</code>
|  
| Damage cap.
|-
|-
| <code>IsInspecting</code>
| <code>damage_bonus</code>
| <code>bool IsInspecting()</code>
| <code>float</code>
|  
| Additional damage (e.g. from crits).
{{warning|Always 0 because this hook is run before this is calculated.}}
|-
|-
| <code>IsInvulnerable</code>
| <code>damage_bonus_provider</code>
| <code>bool IsInvulnerable()</code>
| <code>handle</code>
|  
| Owner of the damage bonus.
{{warning|Always 0 because this hook is run before this is calculated.}}
|-
|-
| <code>IsJumping</code>
| <code>const_base_damage</code>
| <code>bool IsJumping()</code>
| <code>float</code>
|  
| Base damage.
|-
| <code>damage_force</code>
| <code>Vector</code>
| Damage force.
|-
|-
| <code>IsMiniBoss</code>
| <code>damage_for_force_calc</code>
| <code>bool IsMiniBoss()</code>
| <code>float</code>
| Is this player an MvM mini-boss?
| {{bug|hidetested=1|This value does not seem to do anything.}}
|-
|-
| <code>IsParachuteEquipped</code>
| <code>damage_position</code>
| <code>bool IsParachuteEquipped()</code>
| <code>Vector</code>
|  
| World position of where the damage came from. E.g. end position of a bullet or a rocket.
|-
|-
| <code>IsPlacingSapper</code>
| <code>reported_position</code>
| <code>bool IsPlacingSapper()</code>
| <code>Vector</code>
| Returns true if we placed a sapper in the last few moments
| World position of where the damage supposedly came from.
|-
|-
| <code>IsPlayer</code>
| <code>damage_type</code>
| <code>IsPlayer()</code>
| <code>int</code>
|  
| Combination of damage types. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#FDmgType|Constants.FDmgType]]
|-
|-
| <code>IsRageDraining</code>
| <code>damage_custom</code>
| <code>bool IsRageDraining()</code>
| <code>int</code>
|  
| {{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>IsRegenerating</code>
| <code>damage_stats</code>
| <code>bool IsRegenerating()</code>
| <code>int</code>
|  
| 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>IsSapping</code>
| <code>force_friendly_fire</code>
| <code>bool IsSapping()</code>
| <code>bool</code>
| Returns true if we are currently sapping
| 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>IsSnared</code>
| <code>ammo_type</code>
| <code>bool IsSnared()</code>
| <code>int</code>
|  
| Unused.
|-
|-
| <code>IsStealthed</code>
| <code>player_penetration_count</code>
| <code>bool IsStealthed()</code>
| <code>int</code>
|  
| How many players the damage has penetrated so far.
|-
|-
| <code>IsUsingActionSlot</code>
| <code>damaged_other_players</code>
| <code>bool IsUsingActionSlot()</code>
| <code>int</code>
|  
| How many players other than the attacker has the damage been applied to. Used for rocket jump damage reduction.
|-
|-
| <code>IsViewingCYOAPDA</code>
| <code>crit_type</code>
| <code>bool IsViewingCYOAPDA()</code>
| <code>int</code>
|  
| 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>RemoveAllCond</code>
| <code>early_out</code>
| <code>void RemoveAllCond()</code>
| <code>bool</code>
|  
| If set to true by the script, the game's damage routine will not run and it will simply return the currently set damage.
|-
|-
| <code>RemoveAllObjects</code>
|}
| <code>void RemoveAllObjects(bool)</code>
|}
| Remove all player objects. Eg. dispensers/sentries.
 
|-
==== Callbacks ====
| <code>RemoveCond</code>
===== OnDestroy =====
| <code>void RemoveCond(string)</code>
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>
// 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())
})
</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 ===
Extends [[#CBaseEntity|CBaseEntity ↑]]
 
Script handle class for animatable entities, such as props.
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
|-
| <code>RemoveCondEx</code>
| <code>DispatchAnimEvents</code>
| <code>void RemoveCondEx(string, bool)</code>
| <code>void DispatchAnimEvents(CBaseAnimating ''entity'')</code>
|  
| Dispatch animation events to a CBaseAnimating entity.
|-
|-
| <code>RemoveCustomAttribute</code>
| <code>FindBodygroupByName</code>
| <code>void RemoveCustomAttribute(string)</code>
| <code>int FindBodygroupByName(string ''name'')</code>
| Remove a custom attribute to the player
| Find a bodygroup ID by name. Returns -1 if the bodygroup does not exist.
|-
|-
| <code>RemoveDisguise</code>
| <code>GetAttachmentAngles</code>
| <code>void RemoveDisguise()</code>
| <code>QAngle GetAttachmentAngles(int ''id'')</code>
| Undisguise a spy.
| Get an attachment's angles as a QAngle, by ID.
|-
|-
| <code>RemoveInvisibility</code>
| <code>GetAttachmentBone</code>
| <code>void RemoveInvisibility()</code>
| <code>int GetAttachmentBone(int ''id'')</code>
| Un-invisible a spy.
| Get an attachment's parent bone index by ID.
|-
|-
| <code>ResetScores</code>
| <code>GetAttachmentOrigin</code>
| <code>void ResetScores()</code>
| <code>Vector GetAttachmentOrigin(int ''id'')</code>
|  
| Get an attachment's origin as a Vector, by ID.
|-
|-
| <code>SetCondDuration</code>
| <code>GetBodygroup</code>
| <code>void SetCondDuration(string, float)</code>
| <code>int GetBodygroup(int ''id'')</code>
|  
| Get the bodygroup value by bodygroup ID.
|-
|-
| <code>SetCurrentTauntMoveSpeed</code>
| <code>GetBodygroupName</code>
| <code>void SetCurrentTauntMoveSpeed(float)</code>
| <code>string GetBodygroupName(int ''id'')</code>
|  
| Get the bodygroup's name by ID.
|-
|-
| <code>SetDisguiseAmmoCount</code>
| <code>GetBodygroupPartName</code>
| <code>void SetDisguiseAmmoCount(int)</code>
| <code>string GetBodygroupPartName(int ''group'', int ''part'')</code>
|  
| Get the bodygroup's name by group and part.
|-
|-
| <code>SetGrapplingHookTarget</code>
| <code>GetBoneAngles</code>
| <code>void SetGrapplingHookTarget(handle, bool)</code>
| <code>QAngle GetBoneAngles(int ''id'')</code>
| Set the player's target grapple entity
| 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>SetIsMiniBoss</code>
| <code>GetBoneOrigin</code>
| <code>void SetIsMiniBoss(bool)</code>
| <code>Vector GetBoneOrigin(int ''id'')</code>
| Make this player an MvM mini-boss.
| Get the bone's origin Vector by ID.
{{warning|See above.}}
|-
|-
| <code>SetNextChangeClassTime</code>
| <code>GetCycle</code>
| <code>void SetNextChangeClassTime(float)</code>
| <code>float GetCycle()</code>
| Set next change class time.
| Gets the model's current animation cycle rate. Ranges from 0.0 to 1.0.
|-
|-
| <code>SetNextChangeTeamTime</code>
| <code>GetModelScale</code>
| <code>void SetNextChangeTeamTime(float)</code>
| <code>float GetModelScale()</code>
| Set next change team time.
| Get the model's scale.
|-
|-
| <code>SetNextRegenTime</code>
| <code>GetPlaybackRate</code>
| <code>void SetNextRegenTime(float)</code>
| <code>float GetPlaybackRate()</code>
| Set next health regen time.
| Get the current animation's playback rate.
|-
|-
| <code>SetRageMeter</code>
| <code>GetSequence</code>
| <code>void SetRageMeter(float)</code>
| <code>int GetSequence()</code>
|  
| Get the current-playing sequence's ID.
|-
|-
| <code>SetScoutHypeMeter</code>
| <code>GetSequenceActivityName</code>
| <code>void SetScoutHypeMeter(float)</code>
| <code>string GetSequenceActivityName(int ''id'')</code>
|  
| Get the activity name for a sequence by sequence ID.
|-
|-
| <code>SetSpyCloakMeter</code>
| <code>GetSequenceDuration</code>
| <code>void SetSpyCloakMeter(float)</code>
| <code>float GetSequenceDuration(int ''id'')</code>
|  
| Get a sequence duration in seconds by sequence ID.
|-
|-
| <code>SetUseBossHealthBar</code>
| <code>GetSequenceName</code>
| <code>void SetUseBossHealthBar(bool)</code>
| <code>string GetSequenceName(int ''id'')</code>
|  
| 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>int GetSkin()</code>
| Gets the current skin index.
|-
|-
| <code>TryToPickupBuilding</code>
| <code>IsSequenceFinished</code>
| <code>bool TryToPickupBuilding()</code>
| <code>bool IsSequenceFinished()</code>
| Make the player attempt to pick up a building in front of them
| Ask whether the main sequence is done playing.
|-
|-
| <code>WasInCond</code>
| <code>LookupActivity</code>
| <code>bool WasInCond(string)</code>
| <code>int LookupActivity(string ''activity'')</code>
|  
| Get the named activity index. Returns -1 if the activity does not exist.
|}
 
 
=== Convars ===
Game Instance: <code>Convars</code>
 
Provides an interface for getting and setting [[Convar|convars]] on the server.
 
{{todo|The class for this doesn't seem to be directly available.}}
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function
! Signature
! Description
|-
|-
| <code>GetClientConvarValue</code>
| <code>LookupAttachment</code>
| <code>string GetClientConvarValue(string ''name'', int ''entindex'')</code>
| <code>int LookupAttachment(string ''name'')</code>
| Returns the convar value for the entindex as a string. Only works on client convars with the FCVAR_USERINFO flag.  
| Get the named attachment index. Returns 0 if the attachment does not exist.
|-
|-
| <code>GetStr</code>
| <code>LookupBone</code>
| <code>string GetStr(string ''name'')</code>
| <code>int LookupBone(string ''bone'')</code>
| Returns the convar as a string. May return null if no such convar.  
| Get the named bone index. Returns -1 if the bone does not exist.
|-
|-
| <code>GetFloat</code>
| <code>LookupPoseParameter</code>
| <code>float GetFloat(string ''name'')</code>
| <code>int LookupPoseParameter(string ''name'')</code>
| Returns the convar as a float. May return null if no such convar.
| Gets the pose parameter's index. Returns -1 if the pose parameter does not exist.
|-
|-
| <code>SetValue</code>
| <code>LookupSequence</code>
| <code>void SetValue(string ''name'', ''value'')</code>
| <code>int LookupSequence(string ''name'')</code>
| Sets the value of the convar. Supported types are bool, int, float, string.  
| Looks up a sequence by names of sequences or activities. Returns -1 if the sequence does not exist.
|-
| <code>ResetSequence</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.
|-
| <code>SetBodygroup</code>
| <code>void SetBodygroup(int ''id'', int ''value'')</code>
| Set the bodygroup by ID.
|-
| <code>SetCycle</code>
| <code>void SetCycle(float ''cycle'')</code>
| 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>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. Also clears the bone cache.
{{note|Does nothing on players. Use <code>SetCustomModel</code> in that case.}}
|-
| <code>SetModelScale</code>
| <code>void SetModelScale(float ''scale'', float ''change_duration'')</code>
| Changes a model's scale over time. Set the change duration to 0.0 to change the scale instantly.
|-
| <code>SetPlaybackRate</code>
| <code>void SetPlaybackRate(float ''rate'')</code>
| Set the current animation's playback rate.
|-
| <code>SetPoseParameter</code>
| <code>float SetPoseParameter(int ''id'', float ''value'')</code>
| 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>void SetSequence(int ''id'')</code>
| Plays a sequence by sequence ID.
{{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>void SetSkin(int ''index'')</code>
| Sets the model's skin.
|-
| <code>StopAnimation</code>
| <code>void StopAnimation()</code>
| Stop the current animation (same as SetPlaybackRate 0.0).
|-
| <code>StudioFrameAdvance</code>
| <code>void StudioFrameAdvance()</code>
| Advance animation frame to some time in the future with an automatically calculated interval.
|-
| <code>StudioFrameAdvanceManual</code>
| <code>void StudioFrameAdvanceManual(float ''dt'')</code>
| Advance animation frame to some time in the future with a manual interval.
|}
|}


=== CEntities ===
=== CBaseCombatWeapon ===
Game Instance: <code>Entities</code>
Extends [[#CBaseAnimating|CBaseAnimating ↑]]


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.
Script handle class for any weapon entities that can be part of a player's inventory.<br>
 
Team Fortress 2's weapons leave <code>Clip2</code> unused, so those functions can be ignored
The following are two equivalent examples and iterate over all weapons on the map:
==== Methods ====
 
{| class="standard-table" style="width:100%"
{| width=100%
|- style="position:sticky; z-index:10; top:0"
|- style="vertical-align:top;"
! Function
|
! Signature
<source lang=js>
! Description
local ent = null;
|-
while ( ent = Entities.FindByClassname(ent, "weapon_*") )
| <code>CanBeSelected</code>
{
| <code>bool CanBeSelected()</code>
  // ...
| Can this weapon be selected.
}
|-
</source>
| <code>Clip1</code>
|
| <code>int Clip1()</code>
<source lang=js>
| Current ammo in clip1.
for (local ent; ent = Entities.FindByName(ent, "weapon_*"); )
{
  // ...
}
</source>
|}
 
{{Note |
* 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.
* Semicolons are optional, except in the header of the <code>for</code> statement.
* The string parameters of the <code>FindBy...</code> functions support the wildcard star <code>*</code>. In the above example, <code>FindByClassname</code> only returns either a handle of an entity whose classname begins with "<code>weapon_</code>" or it returns <code>null</code>.
}}
 
{| class = "standard-table" style = "width: 85%;"
! Function
! Signature
! Description
|-
|-
| <code>CreateByClassname</code>
| <code>Clip2</code>
| <code>handle CreateByClassname(string)</code>
| <code>int Clip2()</code>
| Creates an entity by classname
| Current ammo in clip2.
|-
|-
| <code>DispatchSpawn</code>
| <code>GetDefaultClip1</code>
| <code>void DispatchSpawn(handle)</code>
| <code>int GetDefaultClip1()</code>
| Dispatches spawn of an entity!
| Default size of clip1.
|-
|-
| <code>FindByClassname</code>
| <code>GetDefaultClip2</code>
| <code>handle FindByClassname(handle, string)</code>
| <code>int GetDefaultClip2()</code>
| Find entities by class name. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Default size of clip2.
|-
|-
| <code>FindByClassnameNearest</code>
| <code>GetMaxClip1</code>
| <code>handle FindByClassnameNearest(string, Vector, float)</code>
| <code>int GetMaxClip1()</code>
| Find entities by class name nearest to a point.
| Max size of clip1.
|-
|-
| <code>FindByClassnameWithin</code>
| <code>GetMaxClip2</code>
| <code>handle FindByClassnameWithin(handle, string, Vector, float)</code>
| <code>int GetMaxClip2()</code>
| Find entities by class name within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Max size of clip2.
|-
|-
| <code>FindByModel</code>
| <code>GetName</code>
| <code>handle FindByModel(handle, string)</code>
| <code>string GetName()</code>
| Find entities by model name. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| 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>FindByName</code>
| <code>GetPosition</code>
| <code>handle FindByName(handle, string)</code>
| <code>int GetPosition()</code>
| Find entities by name. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Gets the weapon's current position.
|-
|-
| <code>FindByNameNearest</code>
| <code>GetPrimaryAmmoCount</code>
| <code>handle FindByNameNearest(string, Vector, float)</code>
| <code>int GetPrimaryAmmoCount()</code>
| Find entities by name nearest to a point.
| 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>FindByNameWithin</code>
| <code>GetPrimaryAmmoType</code>
| <code>handle FindByNameWithin(handle, string, Vector, float)</code>
| <code>int GetPrimaryAmmoType()</code>
| Find entities by name within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Returns the primary ammo type.
|-
| <code>GetPrintName</code>
| <code>string GetPrintName()</code>
| Gets the weapon's print name.
|-
| <code>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).
|-
| <code>GetSecondaryAmmoType</code>
| <code>int GetSecondaryAmmoType()</code>
| Returns the secondary ammo type.
|-
| <code>GetSlot</code>
| <code>int GetSlot()</code>
| Gets the weapon's current slot.
|-
| <code>GetSubType</code>
| <code>int GetSubType()</code>
| Get the weapon subtype.
|-
| <code>GetWeaponFlags</code>
| <code>int GetWeaponFlags()</code>
| Get the weapon flags.
|-
| <code>GetWeight</code>
| <code>int GetWeight()</code>
| Get the weapon weighting/importance.
|-
| <code>HasAnyAmmo</code>
| <code>bool HasAnyAmmo()</code>
| Do we have any ammo?
|-
| <code>HasPrimaryAmmo</code>
| <code>bool HasPrimaryAmmo()</code>
| Do we have any primary ammo?
|-
| <code>HasSecondaryAmmo</code>
| <code>bool HasSecondaryAmmo()</code>
| Do we have any secondary ammo?
|-
| <code>IsAllowedToSwitch</code>
| <code>bool IsAllowedToSwitch()</code>
| Are we allowed to switch to this weapon?
|-
| <code>IsMeleeWeapon</code>
| <code>bool IsMeleeWeapon()</code>
| 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>void PrimaryAttack()</code>
| Force a primary attack.
{{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>void SecondaryAttack()</code>
| Force a secondary attack.
{{warning|See above.}}
|-
| <code>SetClip1</code>
| <code>void SetClip1(int ''amount'')</code>
| Set current ammo in clip1.
|-
| <code>SetClip2</code>
| <code>void SetClip2(int ''amount'')</code>
| Set current ammo in clip2.
|-
| <code>SetCustomViewModel</code>
| <code>void SetCustomViewModel(string ''model_name'')</code>
| Sets a custom view model for this weapon by model name.
|-
| <code>SetCustomViewModelModelIndex</code>
| <code>void SetCustomViewModelModelIndex(int ''model_index'')</code>
| Sets a custom view model for this weapon by modelindex.
|-
| <code>SetSubType</code>
| <code>void SetSubType(int ''subtype'')</code>
| Set the weapon subtype.
|-
| <code>UsesClipsForAmmo1</code>
| <code>bool UsesClipsForAmmo1()</code>
| Do we use clips for ammo 1?
|-
|-
| <code>FindByTarget</code>
| <code>UsesClipsForAmmo2</code>
| <code>handle FindByTarget(handle, string)</code>
| <code>bool UsesClipsForAmmo2()</code>
| Find entities by targetname. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Do we use clips for ammo 2?
|-
|-
| <code>FindInSphere</code>
| <code>UsesPrimaryAmmo</code>
| <code>handle FindInSphere(handle, Vector, float)</code>
| <code>bool UsesPrimaryAmmo()</code>
| Find entities within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Do we use primary ammo?
|-
|-
| <code>First</code>
| <code>UsesSecondaryAmmo</code>
| <code>handle First()</code>
| <code>bool UsesSecondaryAmmo()</code>
| Begin an iteration over the list of entities
| Do we use secondary ammo?
|-
|-
| <code>Next</code>
| <code>VisibleInWeaponSelection</code>
| <code>handle Next(handle)</code>
| <code>bool VisibleInWeaponSelection()</code>
| At the given reference of a previously-found entity, returns the next one after it in the list.
| Is this weapon visible in weapon selection?
|}
|}


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


=== CNetPropManager ===
Animated characters who have vertex flex capability (e.g., facial expressions).
Game Instance: <code>NetProps</code>
 
Allows reading and updating the [[Networking_Entities#Network_Variables|network properties]] and datamaps of an entity.
 
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|List of netprops and datamaps can be found here: https://www.invalidvertex.com/tf2dump.php}}
{{warning|Each netprop has a set size in bits, exceeding the size may desync the clients from the server causing unpredictable behavior.}}


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width:100%"
! Function
! Function
! Signature
! Signature
! Description
! Description
|-
|-
| <code>GetPropArraySize</code>
| <code>PlayScene</code>
| <code>int GetPropArraySize(CBaseEntity ''entity'', string ''propertyName'')</code>
| <code>float PlayScene(string ''scene_file'', float ''delay'')</code>
| Returns the size of an netprop array, or -1.
| 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 ===
Extends [[#CBaseFlex|CBaseFlex ↑]]
 
Combat entities with similar movement capabilities to a player.
==== Methods ====
{| class="standard-table" style="width:100%"
! Function
! Signature
! Description
|-
|-
| <code>GetPropEntity</code>
| <code>GetLastKnownArea</code>
| <code>CBaseEntity GetPropEntity(CBaseEntity ''entity'', string ''propertyName'')</code>
| <code>handle GetLastKnownArea()</code>
| Reads an EHANDLE-valued netprop (21 bit integer). Returns the script handle of the entity.
| Return the last nav area occupied, NULL if unknown.
See [[#CTFNavArea|CTFNavArea ↓]].
|}
 
=== CBasePlayer ===
Extends [[#CBaseCombatCharacter|CBaseCombatCharacter ↑]]
 
Script handle class for player entities.
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
|-
| <code>GetPropEntityArray</code>
| <code>GetForceLocalDraw</code>
| <code>CBaseEntity GetPropEntityArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| <code>bool GetForceLocalDraw()</code>
| Reads an EHANDLE-valued netprop (21 bit integer) from an array. Returns the script handle of the entity.
| Whether the player is being forced by SetForceLocalDraw to be drawn.
|-
|-
| <code>GetPropFloat</code>
| <code>GetPlayerMaxs</code>
| <code>float GetPropFloat(CBaseEntity ''entity'', string ''propertyName'')</code>
| <code>Vector GetPlayerMaxs()</code>
| Reads a float-valued netprop.
| Get a vector containing max bounds of the player in local space. The player's model scale will affect the result.
|-
|-
| <code>GetPropFloatArray</code>
| <code>GetPlayerMins</code>
| <code>float GetPropFloatArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| <code>Vector GetPlayerMins()</code>
| Reads a float-valued netprop from an array.
| Get a vector containing min bounds of the player in local space. The player's model scale will affect the result.
|-
|-
| <code>GetPropInt</code>
| <code>GetScriptOverlayMaterial</code>
| <code>int GetPropInt(CBaseEntity ''entity'', string ''propertyName'')</code>
| <code>string GetScriptOverlayMaterial()</code>
| Reads an integer-valued netprop.
| Gets the current overlay material set by SetScriptOverlayMaterial.
|-
|-
| <code>GetPropIntArray</code>
| <code>IsNoclipping</code>
| <code>int GetPropIntArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| <code>bool IsNoclipping()</code>
| Reads an integer-valued netprop from an array.
| Returns true if the player is in noclip mode.
|-
|-
| <code>GetPropString</code>
| <code>SetForceLocalDraw</code>
| <code>string GetPropString(CBaseEntity ''entity'', string ''propertyName'')</code>
| <code>void SetForceLocalDraw(bool ''toggle'')</code>
| Reads an string-valued netprop.
| Forces the player to be drawn as if they were in thirdperson.
|-
|-
| <code>GetPropStringArray</code>
| <code>SetScriptOverlayMaterial</code>
| <code>string GetPropStringArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| <code>void SetScriptOverlayMaterial(string ''material'')</code>
| Reads an string-valued netprop from an array.
| Sets the overlay material that can't be overriden by other overlays. E.g. Jarate.
|-
|-
| <code>GetPropType</code>
| <code>SnapEyeAngles</code>
| <code>string GetPropType(CBaseEntity ''entity'', string ''propertyName'')</code>
| <code>void SnapEyeAngles(QAngle ''angles'')</code>
| Returns the name of the netprop type as a string.
| 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>GetPropVector</code>
| <code>ViewPunch</code>
| <code>Vector GetPropVector(CBaseEntity ''entity'', string ''propertyName'')</code>
| <code>void ViewPunch(QAngle ''angle_offset'')</code>
| Reads a 3D vector-valued netprop. {{todo | Does it work for other dimensions too?}}
| Ow! Punches the player's view.
|-
|-
| <code>GetPropVectorArray</code>
| <code>ViewPunchReset</code>
| <code>Vector GetPropVectorArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| <code>void ViewPunchReset(float ''tolerance'')</code>
| Reads a 3D vector-valued netprop from an array.  
| Reset's the player's view punch if the offset stays below the given tolerance.
|}
 
=== CBaseMultiplayerPlayer ===
Extends [[#CBasePlayer|CBasePlayer ↑]]
 
Script handle sub-class for player entities in multiplayer games. No additional methods.
 
<!-- No methods, so we do a line-break on our own to avoid having the bottom section seem "merged" on a quick glance. -->
<br>
 
=== CEconEntity ===
Extends [[#CBaseAnimating|CBaseAnimating ↑]]
 
Script handle class for economic exquisite equippables, meaning hats and weapons.
 
==== Methods ====
{| class="standard-table" style="width:100%"
! Function
! Signature
! Description
|-
|-
| <code>HasProp</code>
| <code>AddAttribute</code>
| <code>bool HasProp(CBaseEntity ''entity'', string ''propertyName'')</code>
| <code>void AddAttribute(string ''name'', float ''value'', float ''duration'')</code>
| Checks if a netprop exists.
| 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>SetPropEntity</code>
| <code>GetAttribute</code>
| <code>void SetPropEntity(CBaseEntity ''entity'', string ''propertyName'', CBaseEntity ''value'')</code>
| <code>float GetAttribute(string ''name'', float ''default_value'')</code>
| Sets an EHANDLE-valued netprop (21 bit integer) to reference the specified entity.
| 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>SetPropEntityArray</code>
| <code>RemoveAttribute</code>
| <code>void SetPropEntityArray(CBaseEntity ''entity'', string ''propertyName'', CBaseEntity ''value'', int ''arrayElement'')</code>
| <code>void RemoveAttribute(string ''name'')</code>
| Sets an EHANDLE-valued netprop (21 bit integer) from an array to reference the specified 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>SetPropFloat</code>
| <code>ReapplyProvision</code>
| <code>void SetPropFloat(CBaseEntity ''entity'', string ''propertyName'', float ''value'')</code>
| <code>void ReapplyProvision()</code>
| Sets a netprop to the specified float.
| Relinks attributes to provisioners, e.g. calling this on a weapon will add it's attributes to the player.
|-
| <code>SetPropFloatArray</code>
| <code>void SetPropFloatArray(CBaseEntity ''entity'', string ''propertyName'', float ''value'', int ''arrayElement'')</code>
| Sets a netprop from an array to the specified float.
|-
| <code>SetPropInt</code>
| <code>void SetPropInt(CBaseEntity ''entity'', string ''propertyName'', int ''value'')</code>
| Sets a netprop to the specified integer.
|-
| <code>SetPropIntArray</code>
| <code>void SetPropInt(CBaseEntity ''entity'', string ''propertyName'', int ''value'', int ''arrayElement'')</code>
| Sets a netprop from an array to the specified integer.
|-
| <code>SetPropString</code>
| <code>void SetPropString(CBaseEntity ''entity'', string ''propertyName'', string ''value'')</code>
| Sets a netprop to the specified string.
|-
| <code>SetPropStringArray</code>
| <code>void SetPropStringArray(CBaseEntity ''entity'', string ''propertyName'', string ''value'', int ''arrayElement'')</code>
| Sets a netprop from an array to the specified string.
|-
| <code>SetPropVector</code>
| <code>void SetPropVector(CBaseEntity ''entity'', string ''propertyName'', Vector ''value'')</code>
| Sets a netprop to the specified vector.
|-
| <code>SetPropVectorArray</code>
| <code>void SetPropVectorArray(CBaseEntity ''entity'', string ''propertyName'', Vector ''value'', int ''arrayElement'')</code>
| Sets a netprop from an array to the specified vector.
|}
|}


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


=== CScriptEntityOutputs ===
Script handle class for [[player]] entities of Team Fortress 2.
Game Instance: <code>EntityOutputs</code>
 
Allows reading and manipulation of entity output data.


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Function
! Signature
! Signature
! Description
! Description
|-
|-
| <code>AddOutput</code>
| <code>AddCond</code>
| <code>void AddOutput(CBaseEntity ''entity'', string ''outputName'', string ''targetName'', string ''inputName'', string ''parameter'', float ''delay'', int ''timesToFire'')</code>
| <code>void AddCond([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFCond|ETFCond]] ''cond'')</code>
| Adds a new output to the entity.
|
|-
|-
| <code>GetNumElements</code>
| <code>AddCondEx</code>
| <code>int GetNumElements(CBaseEntity ''entity'', string ''outputName'')</code>
| <code>void AddCondEx([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFCond|ETFCond]] ''cond'', float ''duration'', handle ''provider'')</code>
| Returns the number of array elements.
|
|-
|-
| <code>GetOutputTable</code>
| <code>AddCurrency</code>
| <code>void GetOutputTable(CBaseEntity ''entity'', string ''outputName'', table, int ''arrayElement'')</code>
| <code>void AddCurrency(int ''amount'')</code>
| Fills the passed table with output information.
| 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>HasAction</code>
| <code>AddCustomAttribute</code>
| <code>bool HasAction(CBaseEntity ''entity'', string ''outputName'')</code>
| <code>void AddCustomAttribute(string ''name'', float ''value'', float ''duration'')</code>
| Returns true if an action exists for the output.
| 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>HasOutput</code>
| <code>AddHudHideFlags</code>
| <code>bool HasOutput(CBaseEntity ''entity'', string ''outputName'')</code>
| <code>void AddHudHideFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FHideHUD|FHideHUD]] ''flags'')</code>
| Returns true if the output exists.
| Hides a hud element(-s).
|-
|-
| <code>RemoveOutput</code>
| <code>ApplyPunchImpulseX</code>
| <code>void RemoveOutput(CBaseEntity ''entity'', string ''outputName'', string ''targetName'', string ''inputName'', string ''parameter'')</code>
| <code>bool ApplyPunchImpulseX(float ''impulse'')</code>
| Removes an output from the entity.
| 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.
|}
 
 
=== CScriptKeyValues ===
Script handle representation of a model's [[$keyvalues]] block.
All sub-keys are instances of the same class.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function
! Signature
! Description
|-
|-
| <code>constructor</code>
| <code>BleedPlayer</code>
| <code>void BleedPlayer(float ''duration'')</code>
| Make a player bleed for a set duration of time.
|-
|-
| <code>FindKey</code>
| <code>BleedPlayerEx</code>
| <code>CScriptKeyValues FindKey(string ''key'')</code>
| <code>void BleedPlayerEx(float ''duration'', int ''damage'', bool ''endless'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFDmgCustom|ETFDmgCustom]] ''custom_damage_type'')</code>
| Find a sub key by the key name.
| Make a player bleed for a set duration of time, or forever, with specific damage per tick and damage_custom index.
|-
|-
| <code>GetFirstSubKey</code>
| <code>CancelTaunt</code>
| <code>CScriptKeyValues GetFirstSubKey()</code>
| <code>void CancelTaunt()</code>
| Return the first sub key object.
| Cancels any taunt in progress.
|-
|-
| <code>GetKeyBool</code>
| <code>CanAirDash</code>
| <code>bool GetKeyBool(string ''key'')</code>
| <code>bool CanAirDash()</code>
| Return the key value as a bool.
| Can the player air dash/double jump?
|-
|-
| <code>GetKeyFloat</code>
| <code>CanBeDebuffed</code>
| <code>float GetKeyFloat(string ''key'')</code>
| <code>bool CanBeDebuffed()</code>
| Return the key value as a float.
|
|-
|-
| <code>GetKeyInt</code>
| <code>CanBreatheUnderwater</code>
| <code>int GetKeyInt(string ''key'')</code>
| <code>bool CanBreatheUnderwater()</code>
| Return the key value as an integer.
|
|-
|-
| <code>GetKeyString</code>
| <code>CanDuck</code>
| <code>string GetKeyString(string ''key'')</code>
| <code>bool CanDuck()</code>
| Return the key value as a string.
| Can the player duck?
|-
|-
| <code>GetNextKey</code>
| <code>CanGetWet</code>
| <code>CScriptKeyValues GetNextKey()</code>
| <code>bool CanGetWet()</code>
| Return the next neighbor key object to the one the method is called on.
| Can the player get wet by jarate/milk?
|-
|-
| <code>IsKeyEmpty</code>
| <code>CanJump</code>
| <code>bool IsKeyEmpty(string ''key'')</code>
| <code>bool CanJump()</code>
| Returns true if the named key has no value.
| 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>IsValid</code>
| <code>ClearCustomModelRotation</code>
| <code>bool IsValid()</code>
| <code>void ClearCustomModelRotation()</code>
| Whether the handle belongs to a valid key.
|
|-
|-
| <code>ReleaseKeyValues</code>
| <code>ClearSpells</code>
| <code>void ReleaseKeyValues()</code>
| <code>void ClearSpells()</code>
| Releases the contents of the instance.
|
|}
 
 
=== CPlayerVoiceListener ===
{{todo|What instances use this class?}}
 
{| class = "standard-table" style = "width: 85%;"
! Function
! Signature
! Description
|-
|-
| <code>GetPlayerSpeechDuration</code>
| <code>ClearTauntAttack</code>
| <code>float GetPlayerSpeechDuration(int)</code>
| <code>void ClearTauntAttack()</code>
| Returns the number of seconds the player has been continuously speaking.
| Stops active taunt from damaging or cancels Rock-Paper-Scissors result.
|-
|-
| <code>IsPlayerSpeaking</code>
| <code>CanPlayerMove</code>
| <code>bool IsPlayerSpeaking(int)</code>
| <code>bool CanPlayerMove()</code>
| Returns whether the player specified is speaking.
| Can the player move?
|}
 
 
=== CEnvEntityMaker ===
Extends [[#CBaseEntity|CBaseEntity]]
 
Script handle class for {{ent|env_entity_maker}}.
 
{| class = "standard-table" style = "width: 85%;"
! Function
! Signature
! Description
|-
|-
| <code>SpawnEntity</code>
| <code>DoTauntAttack</code>
| <code>void SpawnEntity()</code>
| <code>void DoTauntAttack()</code>
| Create an entity at the location of the maker
| 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>SpawnEntityAtEntityOrigin</code>
| <code>DropFlag</code>
| <code>void SpawnEntityAtEntityOrigin(handle)</code>
| <code>void DropFlag(bool ''silent'')</code>
| Create an entity at the location of a specified entity instance
| Force player to drop the flag (intelligence).
|-
| <code>DropRune</code>
| <code>void DropRune(bool ''apply_force'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'')</code>
| 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>SpawnEntityAtLocation</code>
| <code>EndLongTaunt</code>
| <code>void SpawnEntityAtLocation(Vector, Vector)</code>
| <code>void EndLongTaunt()</code>
| Create an entity at a specified location and orientaton, orientation is Euler angle in degrees (pitch, yaw, roll)
| Stops a looping taunt (obeys minimum time rules and plays outro animation if available).
|-
|-
| <code>SpawnEntityAtNamedEntityOrigin</code>
| <code>EquipWearableViewModel</code>
| <code>void SpawnEntityAtNamedEntityOrigin(string)</code>
| <code>void EquipWearableViewModel(handle ''entity'')</code>
| Create an entity at the location of a named entity
| Equips a wearable on the viewmodel. Intended to be used with [[tf_wearable_vm]] entities.
|-
|-
|}
| <code>ExtinguishPlayerBurning</code>
 
| <code>void ExtinguishPlayerBurning()</code>
=== CFuncTrackTrain ===
|
Extends [[#CBaseEntity|CBaseEntity]]
 
Script handle class for {{ent|func_tracktrain}}.
 
{| class = "standard-table" style = "width: 85%;"
! Function
! Signature
! Description
|-
|-
| <code>GetFuturePosition</code>
| <code>FiringTalk</code>
| <code>Vector GetFuturePosition(float, float)</code>
| <code>void FiringTalk()</code>
| Get a position on the track x seconds in the future
| 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>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, as well as not slaying the player.
=== CPointScriptTemplate ===
{{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.}}
Extends [[#CBaseEntity|CBaseEntity]]
 
Script handle class for {{ent|point_script_template}}.
 
{| class = "standard-table" style = "width: 85%;"
! Function
! Signature
! Description
|-
|-
| <code>AddTemplate</code>
| <code>ForceRegenerateAndRespawn</code>
| <code>void AddTemplate(string, handle)</code>
| <code>void ForceRegenerateAndRespawn()</code>
| Add an entity to the template spawner
| 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>SetGroupSpawnTables</code>
| <code>ForceRespawn</code>
| <code>void SetGroupSpawnTables(handle, handle)</code>
| <code>void ForceRespawn()</code>
| Cache the group spawn tables
| 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.}}
 
 
=== CSceneEntity ===
Extends [[#CBaseEntity|CBaseEntity]]
 
Script handle class for {{ent|scripted_scene}}, which make use of [[VCD]] data.
 
{| class = "standard-table" style = "width: 85%;"
! Function
! Signature
! Description
|-
|-
| <code>AddBroadcastTeamTarget</code>
| <code>GetActiveWeapon</code>
| <code>void AddBroadcastTeamTarget(int)</code>
| <code>CTFWeapon GetActiveWeapon()</code>
| Adds a team (by index) to the broadcast list
| Get the player's current weapon.
|-
|-
| <code>EstimateLength</code>
| <code>GetBackstabs</code>
| <code>float EstimateLength()</code>
| <code>int GetBackstabs()</code>
| Returns length of this scene in seconds.
|
|-
|-
| <code>FindNamedEntity</code>
| <code>GetBonusPoints</code>
| <code>handle FindNamedEntity(string)</code>
| <code>int GetBonusPoints()</code>
| given an entity reference, such as !target, get actual entity from scene object
|
|-
|-
| <code>IsPaused</code>
| <code>GetBotType</code>
| <code>bool IsPaused()</code>
| <code>int GetBotType()</code>
| If this scene is currently paused.
|
|-
|-
| <code>IsPlayingBack</code>
| <code>GetBuildingsDestroyed</code>
| <code>bool IsPlayingBack()</code>
| <code>int GetBuildingsDestroyed()</code>
| If this scene is currently playing.
|
|-
|-
| <code>LoadSceneFromString</code>
| <code>GetCaptures</code>
| <code>bool LoadSceneFromString(string, string)</code>
| <code>int GetCaptures()</code>
| given a dummy scene name and a vcd string, load the scene
|
|-
|-
| <code>RemoveBroadcastTeamTarget</code>
| <code>GetClassEyeHeight</code>
| <code>void RemoveBroadcastTeamTarget(int)</code>
| <code>Vector GetClassEyeHeight()</code>
| Removes a team (by index) from the broadcast list
| Gets the eye height of the player.
|}
 
 
=== CSimpleCallChainer ===
Has the same members as [[#CCallChainer|CCallChainer]].
{{todo}}
 
{| class = "standard-table" style = "width: 85%;"
! Function
! Signature
! Description
|-
|-
| <code>Call</code>
| <code>GetCondDuration</code>
| <code>Call()</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>chain</code>
| <code>GetCustomAttribute</code>
| <code>chain()</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>constructor</code>
| <code>GetCurrency</code>
| <code>constructor()</code>
| <code>int GetCurrency()</code>
|  
| Get player's cash for game modes with upgrades, ie. MvM.
|-
|-
| <code>PostScriptExecute</code>
| <code>GetCurrentTauntMoveSpeed</code>
| <code>PostScriptExecute()</code>
| <code>float GetCurrentTauntMoveSpeed()</code>
|  
|
|-
|-
| <code>prefix</code>
| <code>GetDefenses</code>
| <code>prefix()</code>
| <code>int GetDefenses()</code>
|  
|
|-
|-
| <code>scope</code>
| <code>GetDisguiseAmmoCount</code>
| <code>scope()</code>
| <code>int GetDisguiseAmmoCount()</code>
|  
|
|}
 
=== CCallChainer ===
 
{| class = "standard-table" style = "width: 85%;"
! Function
! Signature
! Description
|-
|-
| <code>Call</code>
| <code>GetDisguiseTarget</code>
| <code>Call()</code>
| <code>CTFPlayer GetDisguiseTarget()</code>
|  
|
|-
|-
| <code>chains</code>
| <code>GetDisguiseTeam</code>
| <code>chains()</code>
| <code>int GetDisguiseTeam()</code>
|  
|
|-
|-
| <code>constructor</code>
| <code>GetDominations</code>
| <code>constructor()</code>
| <code>int GetDominations()</code>
|  
|
|-
|-
| <code>PostScriptExecute</code>
| <code>GetGrapplingHookTarget</code>
| <code>PostScriptExecute()</code>
| <code>handle GetGrapplingHookTarget()</code>
|  
| What entity is the player grappling?
|-
|-
| <code>prefix</code>
| <code>GetHeadshots</code>
| <code>prefix()</code>
| <code>int GetHeadshots()</code>
|  
|
|-
|-
| <code>scope</code>
| <code>GetHealPoints</code>
| <code>scope()</code>
| <code>int GetHealPoints()</code>
|  
|
|}
 
=== LateBinder ===
{{todo}}
 
{| class = "standard-table" style = "width: 85%;"
! Function
! Signature
! Description
|-
|-
| <code>Begin</code>
| <code>GetHealTarget</code>
| <code>Begin()</code>
| <code>handle GetHealTarget()</code>
|  
| Who is the medic healing?
|-
|-
| <code>End</code>
| <code>GetHudHideFlags</code>
| <code>End()</code>
| <code>int GetHudHideFlags()</code>
|  
| Gets current hidden hud elements.
See [[Team_Fortress_2/Scripting/Script_Functions/Constants#FHideHUD|Constants.FHideHUD]].
|-
|-
| <code>EstablishDelegation</code>
| <code>GetInvulns</code>
| <code>EstablishDelegation()</code>
| <code>int GetInvulns()</code>
|  
|
|-
|-
| <code>HookRootMetamethod</code>
| <code>GetKillAssists</code>
| <code>HookRootMetamethod()</code>
| <code>int GetKillAssists()</code>
|  
|
|-
|-
| <code>Log</code>
| <code>GetLastWeapon</code>
| <code>Log()</code>
| <code>CTFWeapon GetLastWeapon()</code>
|  
|
|-
|-
| <code>m_bindNamesStack</code>
| <code>GetNextChangeClassTime</code>
| <code>m_bindNamesStack()</code>
| <code>float GetNextChangeClassTime()</code>
|  
| Get next change class time.
|-
|-
| <code>m_fixupSet</code>
| <code>GetNextChangeTeamTime</code>
| <code>m_fixupSet()</code>
| <code>float GetNextChangeTeamTime()</code>
|  
| Get next change team time.
|-
|-
| <code>m_targetTable</code>
| <code>GetNextRegenTime</code>
| <code>m_targetTable()</code>
| <code>float GetNextRegenTime()</code>
|  
| Get next health regen time.
|-
|-
| <code>RemoveDelegation</code>
| <code>GetPlayerClass</code>
| <code>RemoveDelegation()</code>
| <code>int GetPlayerClass()</code>
|  
|
|-
|-
| <code>Resolve</code>
| <code>GetRageMeter</code>
| <code>Resolve()</code>
| <code>float GetRageMeter()</code>
|  
|
|-
|-
| <code>UnhookRootMetamethod</code>
| <code>GetResupplyPoints</code>
| <code>UnhookRootMetamethod()</code>
| <code>int GetResupplyPoints()</code>
|  
|
|}
 
=== regexp ===
The built-in [http://squirrel-lang.org/doc/sqstdlib3.html#d0e2591 Squirrel class] for regular expressions.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function
! Signature
! Description
|-
|-
| <code>constructor</code>
| <code>GetRevenge</code>
| <code>regexp()</code>
| <code>int GetRevenge()</code>
|  
|
|-
|-
| <code>capture</code>
| <code>GetScoutHypeMeter</code>
| <code>table capture(''str'', [''start''])</code>
| <code>float GetScoutHypeMeter()</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>GetSpyCloakMeter</code>
| <code> bool match(''str'')</code>
| <code>float GetSpyCloakMeter()</code>
| Returns a true if the regular expression matches the string str, otherwise returns false.
|
|-
|-
| <code>search</code>
| <code>GetTeleports</code>
| <code>table search(''str'', [''start''])</code>
| <code>int GetTeleports()</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>GetTauntAttackTime</code>
| <code>subexpcount()</code>
| <code>float GetTauntAttackTime()</code>
|  
| Timestamp until a taunt attack "lasts". 0 if unavailable.
|}
 
== Data Types ==
 
=== Vector ===
Squirrel equivalent of the C++ [[Vector]] class. A three-dimensional vector with overloaded arithmetic operations for both Vectors and scalar values. {{todo}}
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function
! Signature
! Description
|-
|-
| <code>constructor</code>
| <code>GetTauntRemoveTime</code>
| <code>Vector()</code>
| <code>float GetTauntRemoveTime()</code>
| Creates a new null vector.
| Timestamp until taunt is stopped.
|-
|-
| <code>constructor</code>
| <code>GetVehicleReverseTime</code>
| <code>Vector(float ''x'', float ''y'', float ''z'')</code>
| <code>float GetVehicleReverseTime()</code>
| Creates a new vector with the specified Cartesian coordiantes.
| Timestamp when kart was reversed.
|-
|-
| <code>Cross</code>
| <code>GetTimeSinceCalledForMedic</code>
| <code>float Cross(Vector ''factor'')</code>
| <code>float GetTimeSinceCalledForMedic()</code>
| The vector product of two vectors. Returns a vector orthogonal to the input vectors.
| When did the player last call medic.
|-
|-
| <code>Dot</code>
| <code>GrantOrRemoveAllUpgrades</code>
| <code>float Dot(Vector ''factor'')</code>
| <code>void GrantOrRemoveAllUpgrades(bool ''remove'', bool ''refund'')</code>
| The scalar product of two vectors.
|
|-
|-
| <code>Length</code>
| <code>HasItem</code>
| <code>float Length()</code>
| <code>bool HasItem()</code>
| Magnitude of the vector.
| Currently holding an item? Eg. capture flag.
{{tip|Fetch the <code>m_hItem</code> netprop to get the entity handle.}}
|-
|-
| <code>LengthSqr</code>
| <code>HandleTauntCommand</code>
| <code>float LengthSqr()</code>
| <code>void HandleTauntCommand(int ''taunt_slot'')</code>
| The magnitude of the vector squared. Faster than the above method.
| 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>Length2D</code>
| <code>IgnitePlayer</code>
| <code>float Length2D()</code>
| <code>void IgnitePlayer()</code>
| Returns the magnitude of the vector on the x-y plane. Meant to be used when working with the client's HUD.
| 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>Length2DSqr</code>
| <code>InAirDueToExplosion</code>
| <code>float Length2DSqr()</code>
| <code>bool InAirDueToExplosion()</code>
| Returns the square of the magnitude of the vector on the x-y plane. Faster than the above method.
|
|-
|-
| <code>Norm</code>
| <code>InAirDueToKnockback</code>
| <code>float Norm()</code>
| <code>bool InAirDueToKnockback()</code>
| Seems to also return the vector length.
|
|-
|-
| <code>Scale</code>
| <code>InCond</code>
| <code>Vector Scale(float ''factor'')</code>
| <code>bool InCond([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFCond|ETFCond]] ''cond'')</code>
| Scales the vector magnitude.
|
|-
|-
| <code>ToKVString</code>
| <code>IsAirDashing</code>
| <code>string ToKVString()</code>
| <code>bool IsAirDashing()</code>
| Returns a string without separations commas.
|
|-
| <code>IsAllowedToRemoveTaunt</code>
| <code>bool IsAllowedToRemoveTaunt()</code>
| Returns true if the taunt will be stopped.
|-
|-
| <code>tostring</code>
| <code>IsAllowedToTaunt</code>
| <code>string tostring()</code>
| <code>bool IsAllowedToTaunt()</code>
| Returns a human-readable string.
|
|-
|-
|}
| <code>IsBotOfType</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.
==== Members ====
{| class="standard-table" style="width: 100%;"
! Instance
! Type
! Description
|-
|-
| <code>x</code>
| <code>IsCallingForMedic</code>
| <code>float</code>
| <code>bool IsCallingForMedic()</code>
| Cartesian X axis.
| Is this player calling for medic?
|-
|-
| <code>y</code>
| <code>IsCarryingRune</code>
| <code>float</code>
| <code>bool IsCarryingRune()</code>
| Cartesian Y axis.
|
|-
|-
| <code>z</code>
| <code>IsControlStunned</code>
| <code>float</code>
| <code>bool IsControlStunned()</code>
| Cartesian Z axis.
|
|}
 
==== Operations ====
 
{| class="standard-table" style="width: 100%;"
! Operation
! Description
|-
|-
| <code>Vector + Vector</code>
| <code>IsCritBoosted</code>
| Returns the sum of two Vectors.
| <code>bool IsCritBoosted()</code>
|
|-
|-
| <code>Vector - Vector</code>
| <code>IsFakeClient</code>
| Returns the subtraction of two Vectors.
| <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>Vector * Vector</code>
| <code>IsFireproof</code>
| Returns the multiplication of two Vectors.
| <code>bool IsFireproof()</code>
|
|-
|-
| <code>Vector / Vector</code>
| <code>IsFullyInvisible</code>
| Returns the division of two Vectors.
| <code>bool IsFullyInvisible()</code>
|
|-
|-
|}
| <code>IsHypeBuffed</code>
 
| <code>bool IsHypeBuffed()</code>
==== 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. {{todo}}
 
{| class = "standard-table" style = "width: 85%;"
! Function
! Signature
! Description
|-
|-
| <code>constructor</code>
| <code>IsImmuneToPushback</code>
| <code>constructor()</code>
| <code>bool IsImmuneToPushback()</code>
|  
|
|-
|-
| <code>Forward</code>
| <code>IsInspecting</code>
| <code>Forward()</code>
| <code>bool IsInspecting()</code>
|  
|
|-
|-
| <code>Left</code>
| <code>IsInvulnerable</code>
| <code>Left()</code>
| <code>bool IsInvulnerable()</code>
|  
|
|-
|-
| <code>Pitch</code>
| <code>IsJumping</code>
| <code>Pitch()</code>
| <code>bool IsJumping()</code>
|  
|
|-
|-
| <code>Roll</code>
| <code>IsMiniBoss</code>
| <code>Roll()</code>
| <code>bool IsMiniBoss()</code>
|  
| Is this player an MvM mini-boss?
|-
|-
| <code>ToKVString</code>
| <code>IsParachuteEquipped</code>
| <code>ToKVString()</code>
| <code>bool IsParachuteEquipped()</code>
|  
|
|-
|-
| <code>ToQuat</code>
| <code>IsPlacingSapper</code>
| <code>ToQuat()</code>
| <code>bool IsPlacingSapper()</code>
|  
| Returns true if we placed a sapper in the last few moments.
|-
|-
| <code>Up</code>
| <code>IsRageDraining</code>
| <code>Up()</code>
| <code>bool IsRageDraining()</code>
|  
|
|-
|-
| <code>Yaw</code>
| <code>IsRegenerating</code>
| <code>Yaw()</code>
| <code>bool IsRegenerating()</code>
|  
|
|}
 
 
=== Vector2D, Vector4D ===
Two and four-dimensional equivalents to Vector.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function
! Signature
! Description
|-
|-
| <code>constructor</code>
| <code>IsSapping</code>
| <code>Vector''X''D(float ''x'', float ''y'', ...)</code>
| <code>bool IsSapping()</code>
| Creates a new vector with the specified Cartesian coordiantes.
| Returns true if we are currently sapping.
|-
|-
| <code>Dot</code>
| <code>IsSnared</code>
| <code>float Dot(Vector''X''D ''factor'')</code>
| <code>bool IsSnared()</code>
| The scalar product of two vectors.
|
|-
|-
| <code>Length</code>
| <code>IsStealthed</code>
| <code>float Length()</code>
| <code>bool IsStealthed()</code>
| Magnitude of the vector.
|
|-
|-
| <code>LengthSqr</code>
| <code>IsTaunting</code>
| <code>float LengthSqr()</code>
| <code>bool IsTaunting()</code>
| The magnitude of the vector squared. Faster than the above method.
|
|-
|-
| <code>Norm</code>
| <code>IsUsingActionSlot</code>
| <code>float Norm()</code>
| <code>bool IsUsingActionSlot()</code>
| Seems to also return the vector length.
|
|-
| <code>IsViewingCYOAPDA</code>
| <code>bool IsViewingCYOAPDA()</code>
|
|-
| <code>Regenerate</code>
| <code>void Regenerate(bool ''refill_health_ammo'')</code>
| Resupplies a player. If refill health/ammo is set, clears negative conds, gives back player health/ammo.
|-
|-
| <code>ToKVString</code>
| <code>RemoveAllItems</code>
| <code>string ToKVString()</code>
| <code>void RemoveAllItems(bool ''unused'')</code>
| Returns a string without separations commas.
| {{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
=== Quaternion ===
RemoveAllItems(GetListenServerHost())
 
</source>}}
{| class = "standard-table" style = "width: 85%;"
}}
! Function
}}
! Signature
! Description
|-
|-
| <code>constructor</code>
| <code>RemoveAllObjects</code>
| <code>constructor()</code>
| <code>void RemoveAllObjects(bool ''explode'')</code>
|  
| Remove all player objects. Eg. dispensers/sentries.
|-
|-
| <code>Dot</code>
| <code>RemoveCond</code>
| <code>Dot()</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>Invert</code>
| <code>RemoveCondEx</code>
| <code>Invert()</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>Norm</code>
| <code>RemoveCurrency</code>
| <code>Norm()</code>
| <code>void RemoveCurrency(int ''amount'')</code>
|  
| 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>SetPitchYawRoll</code>
| <code>RemoveCustomAttribute</code>
| <code>SetPitchYawRoll(num, num, num)</code>
| <code>void RemoveCustomAttribute(string ''name'')</code>
|  
| Remove a custom attribute to the player.
|-
|-
| <code>ToKVString</code>
| <code>RemoveDisguise</code>
| <code>ToKVString()</code>
| <code>void RemoveDisguise()</code>
|  
| Undisguise a spy.
|-
|-
| <code>ToQAngle</code>
| <code>RemoveHudHideFlags</code>
| <code>ToQAngle()</code>
| <code>void RemoveHudHideFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FHideHUD|FHideHUD]] ''flags'')</code>
|  
| Unhides a hud element(-s).
|}
 
=== Globals ===
{{todo|Split this section up (especially the built-in Squirrel functions)}}
 
{| class = "standard-table" style = "width: 85%;"
! Function
! Signature
! Description
|-
|-
| <code>__CollectEventCallbacks</code>
| <code>RemoveInvisibility</code>
| <code>__CollectEventCallbacks()</code>
| <code>void RemoveInvisibility()</code>
|  
| Un-invisible a spy.
|-
|-
| <code>__CollectGameEventCallbacks</code>
| <code>RemoveTeleportEffect</code>
| <code>__CollectGameEventCallbacks()</code>
| <code>void RemoveTeleportEffect()</code>
|  
|
|-
|-
| <code>__DumpScope</code>
| <code>ResetScores</code>
| <code>__DumpScope()</code>
| <code>void ResetScores()</code>
|  
|
|-
|-
| <code>__ReplaceClosures</code>
| <code>RollRareSpell</code>
| <code>__ReplaceClosures()</code>
| <code>void RollRareSpell()</code>
|  
|
|-
|-
| <code>__RunEventCallbacks</code>
| <code>SetCondDuration</code>
| <code>__RunEventCallbacks()</code>
| <code>void SetCondDuration([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFCond|ETFCond]] ''cond'', float ''duration'')</code>
|  
|
|-
|-
| <code>__RunGameEventCallbacks</code>
| <code>SetCurrency</code>
| <code>__RunGameEventCallbacks()</code>
| <code>void SetCurrency(int ''amount'')</code>
|  
| Set player's cash for game modes with upgrades, ie. MvM. Does not have any bounds checking.
|-
|-
| <code>__VScriptServerDebugHook</code>
| <code>SetCurrentTauntMoveSpeed</code>
| <code>__VScriptServerDebugHook()</code>
| <code>void SetCurrentTauntMoveSpeed(float ''speed'')</code>
|  
|
|-
|-
| <code>abs</code>
| <code>SetCustomModel</code>
| <code>abs(num)</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>acos</code>
| <code>SetCustomModelOffset</code>
| <code>acos(num)</code>
| <code>void SetCustomModelOffset(Vector ''offset'')</code>
|  
|
|-
|-
| <code>AddThinkToEnt</code>
| <code>SetCustomModelRotates</code>
| <code>void AddThinkToEnt(handle, string)</code>
| <code>void SetCustomModelRotates(bool ''toggle'')</code>
| Adds a late bound think function to the C++ think tables for the obj
|
|-
|-
| <code>AddToScriptHelp</code>
| <code>SetCustomModelRotation</code>
| <code>AddToScriptHelp()</code>
| <code>void SetCustomModelRotation(QAngle ''angles'')</code>
|  
|
|-
|-
| <code>AllowThirdPersonCamera</code>
| <code>SetCustomModelVisibleToSelf</code>
| <code>bool AllowThirdPersonCamera()</code>
| <code>void SetCustomModelVisibleToSelf(bool ''toggle'')</code>
|  
|
|-
|-
| <code>ArePlayersInHell</code>
| <code>SetCustomModelWithClassAnimations</code>
| <code>bool ArePlayersInHell()</code>
| <code>void SetCustomModelWithClassAnimations(string ''model_name'')</code>
|  
| Sets a custom player model with full animations.
|-
|-
| <code>array</code>
| <code>SetDisguiseAmmoCount</code>
| <code>array(num)</code>
| <code>void SetDisguiseAmmoCount(int ''count'')</code>
|  
|
|-
|-
| <code>asin</code>
| <code>SetForcedTauntCam</code>
| <code>asin(num)</code>
| <code>void SetForcedTauntCam(int ''toggle'')</code>
|  
|
|-
|-
| <code>assert</code>
| <code>SetGrapplingHookTarget</code>
| <code>assert()</code>
| <code>void SetGrapplingHookTarget(handle ''entity'', bool ''bleed'')</code>
|  
| Set the player's target grapple entity.
|-
|-
| <code>Assert</code>
| <code>SetHudHideFlags</code>
| <code>Assert()</code>
| <code>void SetHudHideFlags([[Team_Fortress_2/Scripting/Script_Functions/Constants#FHideHUD|FHideHUD]] ''flags'')</code>
|  
| Force hud hide flags to a value.
|-
|-
| <code>atan</code>
| <code>SetIsMiniBoss</code>
| <code>atan(num)</code>
| <code>void SetIsMiniBoss(bool ''toggle'')</code>
|  
| Make this player an MvM mini-boss.
|-
|-
| <code>atan2</code>
| <code>SetNextChangeClassTime</code>
| <code>atan2(num, num)</code>
| <code>void SetNextChangeClassTime(float ''time'')</code>
|  
| Set next change class time.
|-
|-
| <code>BeginScriptDebug</code>
| <code>SetNextChangeTeamTime</code>
| <code>BeginScriptDebug()</code>
| <code>void SetNextChangeTeamTime(float ''time'')</code>
|  
| Set next change team time.
|-
|-
| <code>callee</code>
| <code>SetNextRegenTime</code>
| <code>callee()</code>
| <code>void SetNextRegenTime(float ''time'')</code>
|  
| Set next available resupply time.
|-
|-
| <code>ceil</code>
| <code>SetPlayerClass</code>
| <code>ceil(num)</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.
{{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.}}
{{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>ClearGameEventCallbacks</code>
| <code>SetRageMeter</code>
| <code>ClearGameEventCallbacks()</code>
| <code>void SetRageMeter(float ''percent'')</code>
|  
| Sets rage meter from 0 - 100.
|-
|-
| <code>ClientPrint</code>
| <code>SetRPSResult</code>
| <code>void ClientPrint(handle, int, string)</code>
| <code>void SetRPSResult(int ''result'')</code>
| Print a client message
| Rig the result of Rock-Paper-Scissors (0 - rock, 1 - paper, 2 - scissors).
|-
|-
| <code>collectgarbage</code>
| <code>SetScoutHypeMeter</code>
| <code>collectgarbage()</code>
| <code>void SetScoutHypeMeter(float ''percent'')</code>
|  
| Sets hype meter from 0 - 100.
|-
|-
| <code>compilestring</code>
| <code>SetSpyCloakMeter</code>
| <code>compilestring(string, string)</code>
| <code>void SetSpyCloakMeter(float)</code>
|  
| Sets cloakmeter from 0 - 100.
|-
|-
| <code>cos</code>
| <code>SetVehicleReverseTime</code>
| <code>cos(num)</code>
| <code>void SetVehicleReverseTime(float ''time'')</code>
|  
| Set the timestamp when kart was reversed.
|-
|-
| <code>CreateProp</code>
| <code>SetUseBossHealthBar</code>
| <code>handle CreateProp(string, Vector, string, int)</code>
| <code>void SetUseBossHealthBar(bool ''toggle'')</code>
| Create a physics prop
|
|-
|-
| <code>CreateSceneEntity</code>
| <code>StopTaunt</code>
| <code>handle CreateSceneEntity(string)</code>
| <code>void StopTaunt(bool ''remove_prop'')</code>
| Create a scene entity to play the specified scene.
| Stops current taunt. If ''remove_prop'' is true, the taunt prop will be immediately deleted instead of potentially delaying.
|-
|-
| <code>DebugDrawBox</code>
| <code>StunPlayer</code>
| <code>void DebugDrawBox(Vector, Vector, int, int, int, int, float)</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>
| Draw a debug overlay box
| 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>DebugDrawBoxAngles</code>
| <code>Taunt</code>
| <code>void DebugDrawBoxAngles(Vector, Vector, Vector, QAngle, Vector, float, float)</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>
| Draw a debug oriented box (cent, min, max, angles(p,y,r), vRgb, a, duration)
| 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>DebugDrawBoxDirection</code>
| <code>TryToPickupBuilding</code>
| <code>void DebugDrawBoxDirection(Vector, Vector, Vector, Vector, Vector, float, float)</code>
| <code>bool TryToPickupBuilding()</code>
| Draw a debug forward box (cent, min, max, forward, vRgb, a, duration)
| Make the player attempt to pick up a building in front of them.
|-
|-
| <code>DebugDrawCircle</code>
| <code>UpdateSkin</code>
| <code>void DebugDrawCircle(Vector, Vector, float, float, bool, float)</code>
| <code>void UpdateSkin(int ''skin'')</code>
| Draw a debug circle (center, rad, vRgb, a, ztest, duration)
|
|-
|-
| <code>DebugDrawClear</code>
| <code>WasInCond</code>
| <code>void DebugDrawClear()</code>
| <code>bool WasInCond([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFCond|ETFCond]] ''cond'')</code>
| Try to clear all the debug overlay info
|
|-
|-
| <code>DebugDrawLine</code>
| <code>Weapon_CanUse</code>
| <code>void DebugDrawLine(Vector, Vector, int, int, int, bool, float)</code>
| <code>bool Weapon_CanUse(CTFWeapon ''weapon'')</code>
| Draw a debug overlay line
|
|-
|-
| <code>DebugDrawLine_vCol</code>
| <code>Weapon_Drop</code>
| <code>void DebugDrawLine_vCol(Vector, Vector, Vector, bool, float)</code>
| <code>void Weapon_Drop(CTFWeapon ''weapon'')</code>
| Draw a debug line using color vec (start, end, vRgb, a, ztest, duration)
| Does nothing!
|-
|-
| <code>DebugDrawScreenTextLine</code>
| <code>Weapon_DropEx</code>
| <code>void DebugDrawScreenTextLine(float, float, int, string, int, int, int, int, float)</code>
| <code>void Weapon_DropEx(CTFWeapon ''weapon'', Vector ''target'', Vector ''velocity'')</code>
| Draw text with a line offset
| Does nothing!
|-
|-
| <code>DebugDrawText</code>
| <code>Weapon_Equip</code>
| <code>void DebugDrawText(Vector, string, bool, float)</code>
| <code>void Weapon_Equip(CTFWeapon ''weapon'')</code>
| Draw text in 3d (origin, text, bViewCheck, duration)
| Equips a weapon in the player. This places it inside the <code>m_hMyWeapons</code> array.
|-
|-
| <code>developer</code>
| <code>Weapon_SetLast</code>
| <code>developer()</code>
| <code>void Weapon_SetLast(CTFWeapon ''weapon'')</code>
|  
|
|-
|-
| <code>DispatchParticleEffect</code>
| <code>Weapon_ShootPosition</code>
| <code>void DispatchParticleEffect(string, Vector, Vector)</code>
| <code>Vector Weapon_ShootPosition()</code>
| Dispatches a one-off particle system
| 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>Document</code>
| <code>Weapon_Switch</code>
| <code>Document()</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 ===
Extends [[#CTFPlayer|CTFPlayer ↑]] and [[#NextBotCombatCharacter|NextBotCombatCharacter ↓]]
 
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 ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
|-
| <code>DoEntFire</code>
| <code>AddBotAttribute</code>
| <code>DoEntFire(string, string, string, num, Vector, Vector)</code>
| <code>void AddBotAttribute([[Team_Fortress_2/Scripting/Script_Functions/Constants#FTFBotAttributeType|FTFBotAttributeType]] ''attribute'')</code>
|  
| Sets attribute flags on this TFBot.
|-
|-
| <code>DoIncludeScript</code>
| <code>AddBotTag</code>
| <code>bool DoIncludeScript(string, handle)</code>
| <code>void AddBotTag(string ''tag'')</code>
| Execute a script (internal)
| Adds a bot tag.
|-
|-
| <code>DoUniqueString</code>
| <code>AddWeaponRestriction</code>
| <code>DoUniqueString(string)</code>
| <code>void AddWeaponRestriction([[Team_Fortress_2/Scripting/Script_Functions/Constants#TFBotWeaponRestrictionType|TFBotWeaponRestrictionType]] ''flags'')</code>
|  
| Adds weapon restriction flags.
|-
|-
| <code>dummy</code>
| <code>ClearAllBotAttributes</code>
| <code>dummy()</code>
| <code>void ClearAllBotAttributes()</code>
|  
| Clears all attribute flags on this TFBot.
|-
|-
| <code>DumpObject</code>
| <code>ClearAllBotTags</code>
| <code>DumpObject()</code>
| <code>void ClearAllBotTags()</code>
|  
| Clears bot tags.
|-
|-
| <code>EmitAmbientSoundOn</code>
| <code>ClearAllWeaponRestrictions</code>
| <code>void EmitAmbientSoundOn(string, float, int, int, handle)</code>
| <code>void ClearAllWeaponRestrictions()</code>
| Play named ambient sound on an entity.
| Removes all weapon restriction flags.
|-
|-
| <code>EmitSoundOn</code>
| <code>ClearAttentionFocus</code>
| <code>void EmitSoundOn(string, handle)</code>
| <code>void ClearAttentionFocus()</code>
| Play named sound on Entity
| Clear current focus.
|-
|-
| <code>EmitSoundOnClient</code>
| <code>ClearBehaviorFlag</code>
| <code>void EmitSoundOnClient(string, handle)</code>
| <code>void ClearBehaviorFlag([[Team_Fortress_2/Scripting/Script_Functions/Constants#TFBOT_BEHAVIOR|TFBOT_BEHAVIOR]] ''flags'')</code>
| Play named sound only on the client for the passed in player
| Clear the given behavior flag(s) for this bot.
|-
|-
| <code>enabledebuginfo</code>
| <code>DelayedThreatNotice</code>
| <code>enabledebuginfo()</code>
| <code>void DelayedThreatNotice(handle ''threat'', float ''delay'')</code>
|  
| Notice the threat after a delay in seconds.
|-
|-
| <code>EndScriptDebug</code>
| <code>DisbandCurrentSquad</code>
| <code>EndScriptDebug()</code>
| <code>void DisbandCurrentSquad()</code>
|  
| Forces the current squad to be entirely disbanded by everyone.
|-
|-
| <code>EntFire</code>
| <code>FindVantagePoint</code>
| <code>function EntFire(target, action, value, delay, activator)</code>
| <code>CTFNavArea FindVantagePoint(float ''max_distance'')</code>
| Generate and entity i/o event
| Get the nav area of the closest vantage point (within distance).
|-
|-
| <code>EntFireByHandle</code>
| <code>GenerateAndWearItem</code>
| <code>void EntFireByHandle(handle, string, string, float, handle, handle)</code>
| <code>void GenerateAndWearItem(string ''item_name'')</code>
| Generate and entity i/o event. First parameter is an entity instance.
| Give me an item!
|-
|-
| <code>EntIndexToHScript</code>
| <code>GetActionPoint</code>
| <code>handle EntIndexToHScript(int)</code>
| <code>handle GetActionPoint()</code>
| Turn an entity index integer to an HScript representing that entity's script instance.
| Get the given action point for this bot.
|-
|-
| <code>error</code>
| <code>GetAllBotTags</code>
| <code>error()</code>
| <code>void GetAllBotTags(table ''result'')</code>
|  
| Get all bot tags. The key is the index, and the value is the tag.
|-
|-
| <code>exp</code>
| <code>GetHomeArea</code>
| <code>exp(num)</code>
| <code>CTFNavArea GetHomeArea()</code>
|  
| Sets the home nav area of the bot.
|-
|-
| <code>fabs</code>
| <code>GetDifficulty</code>
| <code>fabs(num)</code>
| <code>int GetDifficulty()</code>
|  
| Returns the bot's difficulty level. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotDifficultyType|Constants.ETFBotDifficultyType]].
|-
|-
| <code>FileToString</code>
| <code>GetMaxVisionRangeOverride</code>
| <code>string FileToString(string)</code>
| <code>float GetMaxVisionRangeOverride()</code>
| Reads a string from a file to send to script
| 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>FindCircularReference</code>
| <code>GetMission</code>
| <code>FindCircularReference()</code>
| <code>int GetMission()</code>
|  
| Get this bot's current mission. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotMissionType|ETFBotMissionType]].
|-
|-
| <code>FindCircularReferences</code>
| <code>GetMissionTarget</code>
| <code>FindCircularReferences()</code>
| <code>handle GetMissionTarget()</code>
|  
| Get this bot's current mission target.
|-
|-
| <code>FireGameEvent</code>
| <code>GetNearestKnownSappableTarget</code>
| <code>bool FireGameEvent(string, handle)</code>
| <code>handle GetNearestKnownSappableTarget()</code>
| Fire a game event to a listening callback function in script. Parameters are passed in a squirrel table.
| Gets the nearest known sappable target.
|-
|-
| <code>FireScriptEvent</code>
| <code>GetPrevMission</code>
| <code>FireScriptEvent()</code>
| <code>int GetPrevMission()</code>
|  
| Get this bot's previous mission. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotMissionType|ETFBotMissionType]].
|-
|-
| <code>FlagsMayBeCapped</code>
| <code>GetSpawnArea</code>
| <code>bool FlagsMayBeCapped()</code>
| <code>CTFNavArea GetSpawnArea()</code>
| May a flag be captured?
| Return the nav area of where we spawned.
|-
| <code>GetSquadFormationError</code>
| <code>float GetSquadFormationError()</code>
| Gets our formation error coefficient.
|-
|-
| <code>floor</code>
| <code>HasBotAttribute</code>
| <code>floor(num)</code>
| <code>bool HasBotAttribute([[Team_Fortress_2/Scripting/Script_Functions/Constants#FTFBotAttributeType|FTFBotAttributeType]] ''attribute'')</code>
|  
| Checks if this TFBot has the given attributes.
|-
|-
| <code>format</code>
| <code>HasBotTag</code>
| <code>format(string)</code>
| <code>bool HasBotTag(string ''tag'')</code>
|  
| Checks if this TFBot has the given bot tag.
|-
|-
| <code>FrameTime</code>
| <code>HasMission</code>
| <code>float FrameTime()</code>
| <code>bool HasMission([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotMissionType|ETFBotMissionType]] ''mission'')</code>
| Get the time spent on the server in the last frame
| Return true if the given mission is this bot's current mission.
|-
|-
| <code>GameModeUsesCurrency</code>
| <code>HasWeaponRestriction</code>
| <code>bool GameModeUsesCurrency()</code>
| <code>bool HasWeaponRestriction([[Team_Fortress_2/Scripting/Script_Functions/Constants#TFBotWeaponRestrictionType|TFBotWeaponRestrictionType]] ''flags'')</code>
| Does the current gamemode have currency?
| Checks if this TFBot has the given weapon restriction flags.
|-
|-
| <code>GameModeUsesMiniBosses</code>
| <code>IsAmmoFull</code>
| <code>bool GameModeUsesMiniBosses()</code>
| <code>bool IsAmmoFull()</code>
| Does the current gamemode have minibosses?
|
|-
|-
| <code>GameModeUsesUpgrades</code>
| <code>IsAmmoLow</code>
| <code>bool GameModeUsesUpgrades()</code>
| <code>bool IsAmmoLow()</code>
| Does the current gamemode have upgrades?
|
|-
|-
| <code>GetClassLimit</code>
| <code>IsAttentionFocused</code>
| <code>int GetClassLimit(int)</code>
| <code>bool IsAttentionFocused()</code>
| Get class limit for class. Indices:
| Is our attention focused right now?
|-
|-
| <code>getconsttable</code>
| <code>IsAttentionFocusedOn</code>
| <code>getconsttable()</code>
| <code>bool IsAttentionFocusedOn(handle ''entity'')</code>
|  
| Is our attention focused on this entity.
|-
|-
| <code>GetDeveloperLevel</code>
| <code>IsBehaviorFlagSet</code>
| <code>int GetDeveloperLevel()</code>
| <code>bool IsBehaviorFlagSet([[Team_Fortress_2/Scripting/Script_Functions/Constants#TFBOT_BEHAVIOR|TFBOT_BEHAVIOR]] ''flags'')</code>
| Gets the level of 'developer'
| Return true if the given behavior flag(s) are set for this bot.
|-
|-
| <code>GetFrameCount</code>
| <code>IsDifficulty</code>
| <code>int GetFrameCount()</code>
| <code>bool IsDifficulty([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotDifficultyType|ETFBotDifficultyType]] ''difficulty'')</code>
| Returns the engines current frame count
| Returns true/false if the bot's difficulty level matches.
|-
|-
| <code>GetFriction</code>
| <code>IsInASquad</code>
| <code>float GetFriction(handle)</code>
| <code>bool IsInASquad()</code>
| Returns the Friction on a player entity, meaningless if not a player
| Checks if we are in a squad.
|-
|-
| <code>GetFunctionSignature</code>
| <code>IsOnAnyMission</code>
| <code>GetFunctionSignature()</code>
| <code>bool IsOnAnyMission()</code>
|  
| Return true if this bot has a current mission.
|-
|-
| <code>GetGravityMultiplier</code>
| <code>IsWeaponRestricted</code>
| <code>float GetGravityMultiplier()</code>
| <code>bool IsWeaponRestricted(handle ''weapon'')</code>
|  
| Checks if the given weapon is restricted for use on the bot.
|-
|-
| <code>GetListenServerHost</code>
| <code>LeaveSquad</code>
| <code>handle GetListenServerHost()</code>
| <code>void LeaveSquad()</code>
| Get the local player on a listen server.
| Makes us leave the current squad (if any).
|-
|-
| <code>GetMannVsMachineAlarmStatus</code>
| <code>PressAltFireButton</code>
| <code>bool GetMannVsMachineAlarmStatus()</code>
| <code>void PressAltFireButton(float ''duration'' = -1)</code>
|  
|  
|-
|-
| <code>GetMapName</code>
| <code>PressFireButton</code>
| <code>string GetMapName()</code>
| <code>void PressFireButton(float ''duration'' = -1)</code>
| Get the name of the map.
|
|-
| <code>PressSpecialFireButton</code>
| <code>void PressSpecialFireButton(float ''duration'' = -1)</code>
|
|-
|-
| <code>GetModelIndex</code>
| <code>RemoveBotAttribute</code>
| <code>int GetModelIndex(string)</code>
| <code>void RemoveBotAttribute([[Team_Fortress_2/Scripting/Script_Functions/Constants#FTFBotAttributeType|FTFBotAttributeType]] ''attribute'')</code>
| Returns the index of the named model.
| Removes attribute flags on this TFBot.
|-
|-
| <code>GetOvertimeAllowedForCTF</code>
| <code>RemoveBotTag</code>
| <code>bool GetOvertimeAllowedForCTF()</code>
| <code>void RemoveBotTag(string ''tag'')</code>
|  
| Removes a bot tag.
|-
|-
| <code>GetPhysAngularVelocity</code>
| <code>RemoveWeaponRestriction</code>
| <code>Vector GetPhysAngularVelocity(handle)</code>
| <code>void RemoveWeaponRestriction([[Team_Fortress_2/Scripting/Script_Functions/Constants#TFBotWeaponRestrictionType|TFBotWeaponRestrictionType]] ''flags'')</code>
| Get Angular Velocity for VPHYS or normal object
| Removes weapon restriction flags.
|-
|-
| <code>GetPhysVelocity</code>
| <code>SetActionPoint</code>
| <code>Vector GetPhysVelocity(handle)</code>
| <code>void SetActionPoint(handle ''entity'')</code>
| Get Velocity for VPHYS or normal object
| Set the given action point for this bot.
|-
|-
| <code>GetPlayerFromUserID</code>
| <code>SetAttentionFocus</code>
| <code>handle GetPlayerFromUserID(int)</code>
| <code>void SetAttentionFocus(handle ''entity'')</code>
| Given a user id, return the entity, or null
| Sets our current attention focus to this entity.
|-
|-
| <code>getroottable</code>
| <code>SetAutoJump</code>
| <code>getroottable()</code>
| <code>void SetAutoJump(float ''min_time'', float ''max_time'')</code>
|  
| Sets if the bot should automatically jump, and how often.
|-
|-
| <code>GetRoundState</code>
| <code>SetBehaviorFlag</code>
| <code>int GetRoundState()</code>
| <code>void SetBehaviorFlag([[Team_Fortress_2/Scripting/Script_Functions/Constants#TFBOT_BEHAVIOR|TFBOT_BEHAVIOR]] ''flags'')</code>
| Get current round state. Indices:
| Set the given behavior flag(s) for this bot.
|-
|-
| <code>GetSoundDuration</code>
| <code>SetDifficulty</code>
| <code>float GetSoundDuration(string, string)</code>
| <code>void SetDifficulty([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotDifficultyType|ETFBotDifficultyType]] ''difficulty'')</code>
| Returns float duration of the sound. Takes soundname and optional actormodelname.
| Sets the bots difficulty level.
|-
|-
| <code>getstackinfos</code>
| <code>SetHomeArea</code>
| <code>getstackinfos(num)</code>
| <code>void SetHomeArea(CTFNavArea ''area'')</code>
|  
| Set the home nav area of the bot, may be null.
|-
|-
| <code>GetStopWatchState</code>
| <code>SetMaxVisionRangeOverride</code>
| <code>int GetStopWatchState()</code>
| <code>void SetMaxVisionRangeOverride(float ''range'')</code>
| Get the current stopwatch state. Indices:
| Sets max vision range override for the bot.
|-
|-
| <code>GetWinningTeam</code>
| <code>SetMission</code>
| <code>int GetWinningTeam()</code>
| <code>void SetMission([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFBotMissionType|ETFBotMissionType]] ''mission'', bool ''reset_behavior'')</code>
| Who won!
| Set this bot's current mission to the given mission.
|-
|-
| <code>HaveStopWatchWinner</code>
| <code>SetMissionTarget</code>
| <code>bool HaveStopWatchWinner()</code>
| <code>void SetMissionTarget(handle ''entity'')</code>
|  
| Set this bot's mission target to the given entity.
|-
|-
| <code>IncludeScript</code>
| <code>SetPrevMission</code>
| <code>IncludeScript()</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>InMatchStartCountdown</code>
| <code>SetScaleOverride</code>
| <code>bool InMatchStartCountdown()</code>
| <code>void SetScaleOverride(float ''scale'')</code>
| Are we in the pre-match state?
| Sets the scale override for the bot.
|-
|-
| <code>InOvertime</code>
| <code>SetShouldQuickBuild</code>
| <code>bool InOvertime()</code>
| <code>void SetShouldQuickBuild(bool ''toggle'')</code>
| Currently in overtime?
| Sets if the bot should build instantly.
|-
|-
| <code>IsAttackDefenseMode</code>
| <code>SetSquadFormationError</code>
| <code>bool IsAttackDefenseMode()</code>
| <code>void SetSquadFormationError(float ''coefficient'')</code>
|  
| Sets our formation error coefficient.
|-
|-
| <code>IsBirthday</code>
| <code>ShouldAutoJump</code>
| <code>bool IsBirthday()</code>
| <code>bool ShouldAutoJump()</code>
| Are we in birthday mode?
| Returns if the bot should automatically jump.
|-
|-
| <code>IsCompetitiveMode</code>
| <code>ShouldQuickBuild</code>
| <code>bool IsCompetitiveMode()</code>
| <code>bool ShouldQuickBuild()</code>
| Playing competitive?
| Returns if the bot should build instantly.
|-
|-
| <code>IsDedicatedServer</code>
| <code>UpdateDelayedThreatNotices</code>
| <code>bool IsDedicatedServer()</code>
| <code>void UpdateDelayedThreatNotices()</code>
| Returns true if this server is a dedicated server.
|
|}
 
=== 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>IsDefaultGameMode</code>
| <code>SetResolvePlayerCollisions</code>
| <code>bool IsDefaultGameMode()</code>
| <code>void SetResolvePlayerCollisions(bool ''toggle'')</code>
| The absence of arena, mvm, tournament mode, etc
| 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 ===
Game Instance: <code>Convars</code>
 
An interface to manipulate the [[ConVar|convars]] on the server.
 
{{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.
-->
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
|-
| <code>IsHolidayActive</code>
| <code>GetBool</code>
| <code>bool IsHolidayActive(int)</code>
| <code>bool GetBool(string ''name'')</code>
| Is the given holiday active? Indices:
| Returns the convar as a bool. May return null if no such convar.
|-
|-
| <code>IsHolidayMap</code>
| <code>GetClientConvarValue</code>
| <code>bool IsHolidayMap(int)</code>
| <code>string GetClientConvarValue(string ''name'', int ''entindex'')</code>
| Playing a holiday map? Indices:
| 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>IsInArenaMode</code>
| <code>GetInt</code>
| <code>bool IsInArenaMode()</code>
| <code>int GetInt(string ''name'')</code>
| Playing arena mode?
| 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>IsInKothMode</code>
| <code>GetStr</code>
| <code>bool IsInKothMode()</code>
| <code>string GetStr(string ''name'')</code>
| Playing king of the hill mode?
| 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>IsInMedievalMode</code>
| <code>GetFloat</code>
| <code>bool IsInMedievalMode()</code>
| <code>float GetFloat(string ''name'')</code>
| Playing medieval mode?
| Returns the convar as a float. May return null if no such convar.
{{warning|See above.}}
|-
|-
| <code>IsInWaitingForPlayers</code>
| <code>IsConVarOnAllowList</code>
| <code>bool IsInWaitingForPlayers()</code>
| <code>bool IsConVarOnAllowList(string ''name'')</code>
| Are we waiting for some stragglers?
| 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!
|-
|-
| <code>IsMannVsMachineMode</code>
| <code>SetValue</code>
| <code>bool IsMannVsMachineMode()</code>
| <code>void SetValue(string ''name'', any ''value'')</code>
| Playing MvM? Beep boop
| 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.}}
| <code>IsMannVsMachineRespecEnabled</code>
|}
| <code>bool IsMannVsMachineRespecEnabled()</code>
 
| Are players allowed to refund their upgrades?
=== CEntities ===
|-
Game Instance: <code>Entities</code>
| <code>IsMatchTypeCasual</code>
 
| <code>bool IsMatchTypeCasual()</code>
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.
| Playing casual?
 
|-
The following are two equivalent examples and iterate over all weapons on the map:
| <code>IsMatchTypeCompetitive</code>
 
| <code>bool IsMatchTypeCompetitive()</code>
{| width=100%
| Playing competitive?
|- style="vertical-align:top;"
|-
|
| <code>IsModelPrecached</code>
<source lang=js>
| <code>bool IsModelPrecached(string)</code>
local ent = null
| Checks if the modelname is precached.
while ( ent = Entities.FindByClassname(ent, "tf_weapon_*") )
|-
{
| <code>IsPasstimeMode</code>
  // ...
| <code>bool IsPasstimeMode()</code>
}
| No ball games.
</source>
|
<source lang=js>
for (local ent; ent = Entities.FindByName(ent, "tf_weapon_*"); )
{
  // ...
}
</source>
|}
 
{{note |
* 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.
* Semicolons are optional, except in the header of the <code>for</code> statement.
* The string parameters of the <code>FindBy...</code> functions support the wildcard star <code>*</code>. In the above example, <code>FindByClassname</code> only returns either a handle of an entity whose classname begins with "<code>tf_weapon_</code>" or it returns <code>null</code>.
}}
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
|-
| <code>IsPlayerABot</code>
| <code>CreateByClassname</code>
| <code>bool IsPlayerABot(handle)</code>
| <code>handle CreateByClassname(string ''classname'')</code>
| Is this player/entity a bot
| Creates an entity by classname.
{{tip|Example usage: <source lang=js>local prop = Entities.CreateByClassname("prop_dynamic")</source>}}
|-
|-
| <code>IsPowerupMode</code>
| <code>DispatchSpawn</code>
| <code>bool IsPowerupMode()</code>
| <code>void DispatchSpawn(handle ''entity'')</code>
| Playing powerup mode? Not compatible with MvM
| 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>IsPVEModeActive</code>
| <code>FindByClassname</code>
| <code>bool IsPVEModeActive()</code>
| <code>handle FindByClassname(handle ''previous'', string ''classname'')</code>
|  
| 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.
{{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>IsQuickBuildTime</code>
| <code>FindByClassnameNearest</code>
| <code>bool IsQuickBuildTime()</code>
| <code>handle FindByClassnameNearest(string ''classname'', Vector ''center'', float ''radius'')</code>
| If an engie places a building, will it immediately upgrade? Eg. MvM pre-round etc.
| Find entities by classname nearest to a point within a radius.
|-
|-
| <code>IsSoundPrecached</code>
| <code>FindByClassnameWithin</code>
| <code>bool IsSoundPrecached(string)</code>
| <code>handle FindByClassnameWithin(handle ''previous'', string ''classname'', Vector ''center'', float ''radius'')</code>
| Takes a sound name
| 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>IsTruceActive</code>
| <code>FindByModel</code>
| <code>bool IsTruceActive()</code>
| <code>handle FindByModel(handle ''previous'', string ''model_name'')</code>
|  
| 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>IsUsingGrapplingHook</code>
| <code>FindByName</code>
| <code>bool IsUsingGrapplingHook()</code>
| <code>handle FindByName(handle ''previous'', string ''targetname'')</code>
|  
| 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>IsUsingSpells</code>
| <code>FindByNameNearest</code>
| <code>bool IsUsingSpells()</code>
| <code>handle FindByNameNearest(string ''targetname'', Vector ''center'', float ''radius'')</code>
|  
| Find entities by targetname nearest to a point within a radius.
|-
|-
| <code>IsWeakref</code>
| <code>FindByNameWithin</code>
| <code>IsWeakref()</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.
|-
|-
| <code>LocalTime</code>
| <code>FindByTarget</code>
| <code>void LocalTime(handle)</code>
| <code>handle FindByTarget(handle ''previous'', string ''target'')</code>
| Fills out a table with the local time (second, minute, hour, day, month, year, dayofweek, dayofyear, daylightsavings)
| 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>log</code>
| <code>FindInSphere</code>
| <code>log(num)</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.
|-
|-
| <code>log10</code>
| <code>First</code>
| <code>log10(num)</code>
| <code>handle First()</code>
|  
| Begin an iteration over the list of entities. The first entity is always [[worldspawn]].
|-
|-
| <code>lstrip</code>
| <code>Next</code>
| <code>lstrip(string)</code>
| <code>handle Next(handle ''previous'')</code>
|  
| At the given reference of a previously-found entity, returns the next one after it in the list.
|-
|}
| <code>MakeNamespace</code>
 
| <code>MakeNamespace()</code>
=== CTFNavArea ===
|  
 
Script handle class for areas part of the [[Nav Mesh|navigation mesh]].
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>AddIncomingConnection</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.
|-
|-
| <code>MapHasMatchSummaryStage</code>
| <code>ClearAttributeTF</code>
| <code>bool MapHasMatchSummaryStage()</code>
| <code>void ClearAttributeTF([[Team_Fortress_2/Scripting/Script_Functions/Constants#FTFNavAttributeType|FTFNavAttributeType]] ''bits'')</code>
|  
| Clear TF-specific area attribute bits.
|-
|-
| <code>MatchmakingShouldUseStopwatchMode</code>
| <code>ComputeClosestPointInPortal</code>
| <code>bool MatchmakingShouldUseStopwatchMode()</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.
|-
|-
| <code>Msg</code>
| <code>ComputeDirection</code>
| <code>Msg()</code>
| <code>int ComputeDirection(Vector ''point'')</code>
|  
| Return direction from this area to the given point.
|-
|-
| <code>newthread</code>
| <code>ConnectTo</code>
| <code>newthread(Vector)</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.
|-
|-
| <code>PickupObject</code>
| <code>Contains</code>
| <code>void PickupObject(handle, handle)</code>
| <code>bool Contains(CTFNavArea ''area'')</code>
| Have a player pickup a nearby named entity
| Return true if other area is on or above this area, but no others.
|-
|-
| <code>PlayerInstanceFromIndex</code>
| <code>ContainsOrigin</code>
| <code>handle PlayerInstanceFromIndex(int)</code>
| <code>bool ContainsOrigin(Vector ''point'')</code>
| Get a script instance of a player by index.
| Return true if given point is on or above this area, but no others.
|-
|-
| <code>PlayerReadyStatus_ArePlayersOnTeamReady</code>
| <code>DebugDrawFilled</code>
| <code>bool PlayerReadyStatus_ArePlayersOnTeamReady(int)</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.
|-
|-
| <code>PlayerReadyStatus_HaveMinPlayersToEnable</code>
| <code>Disconnect</code>
| <code>bool PlayerReadyStatus_HaveMinPlayersToEnable()</code>
| <code>void Disconnect(CTFNavArea ''area'')</code>
|  
| Disconnect this area from given area.
|-
|-
| <code>PlayerReadyStatus_ResetState</code>
| <code>FindRandomSpot</code>
| <code>void PlayerReadyStatus_ResetState()</code>
| <code>Vector FindRandomSpot()</code>
|  
| Get random origin within extent of area.
|-
|-
| <code>PlayersAreOnMatchSummaryStage</code>
| <code>GetAdjacentArea</code>
| <code>bool PlayersAreOnMatchSummaryStage()</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.
{{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>PointsMayBeCaptured</code>
| <code>GetAdjacentAreas</code>
| <code>bool PointsMayBeCaptured()</code>
| <code>void GetAdjacentAreas([[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'', table ''result'')</code>
| Are points able to be captured?
| Fills a passed in table with all adjacent areas in the given direction.
|-
|-
| <code>pow</code>
| <code>GetAdjacentCount</code>
| <code>pow(num, num)</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.
|-
|-
| <code>PrecacheEntityFromTable</code>
| <code>GetAttributes</code>
| <code>bool PrecacheEntityFromTable(handle)</code>
| <code>int GetAttributes()</code>
| Precache an entity from KeyValues in table
| Get area attribute bits.
See [[Team_Fortress_2/Scripting/Script_Functions/Constants#FNavAttributeType|FNavAttributeType]].
|-
|-
| <code>PrecacheModel</code>
| <code>GetAvoidanceObstacleHeight</code>
| <code>void PrecacheModel(string)</code>
| <code>float GetAvoidanceObstacleHeight()</code>
| Precache a model.
| Returns the maximum height of the obstruction above the ground.
|-
|-
| <code>PrecacheSound</code>
| <code>GetCenter</code>
| <code>void PrecacheSound(string)</code>
| <code>Vector GetCenter()</code>
| Precache a sound.
| Get center origin of area.
|-
|-
| <code>print</code>
| <code>GetCorner</code>
| <code>print()</code>
| <code>Vector GetCorner([[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'')</code>
|  
| Get corner origin of area.
|-
|-
| <code>PrintHelp</code>
| <code>GetDistanceSquaredToPoint</code>
| <code>PrintHelp()</code>
| <code>float GetDistanceSquaredToPoint(Vector ''pos'')</code>
|  
| Return shortest distance between point and this area.
|-
|-
| <code>printl</code>
| <code>GetDoor</code>
| <code>printl()</code>
| <code>CBaseAnimating GetDoor()</code>
|  
| Returns the door entity above the area.
|-
|-
| <code>rand</code>
| <code>GetElevator</code>
| <code>rand()</code>
| <code>CBaseAnimating GetElevator()</code>
|  
| Returns the elevator if in an elevator's path.
|-
|-
| <code>RandomFloat</code>
| <code>GetElevatorAreas</code>
| <code>float RandomFloat(float, float)</code>
| <code>void GetElevatorAreas(table ''result'')</code>
| Generate a random floating point number within a range, inclusive
| Fills table with a collection of areas reachable via elevator from this area.
|-
|-
| <code>RandomInt</code>
| <code>GetID</code>
| <code>int RandomInt(int, int)</code>
| <code>int GetID()</code>
| Generate a random integer within a range, inclusive
| Get area ID.
|-
|-
| <code>realPrint</code>
| <code>GetIncomingConnections</code>
| <code>realPrint()</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).
|-
|-
| <code>RegisterFunctionDocumentation</code>
| <code>GetParent</code>
| <code>RegisterFunctionDocumentation()</code>
| <code>CTFNavArea GetParent()</code>
|  
| Returns the area just prior to this one in the search path.
|-
|-
| <code>RegisterScriptGameEventListener</code>
| <code>GetParentHow</code>
| <code>void RegisterScriptGameEventListener(string)</code>
| <code>int GetParentHow()</code>
| Register as a listener for a game event from script.
| Returns how we get from parent to us.
|-
|-
| <code>resurrectunreachable</code>
| <code>GetPlaceName</code>
| <code>resurrectunreachable()</code>
| <code>string GetPlaceName()</code>
|  
| Get place name if it exists, null otherwise.
|-
|-
| <code>RetrieveNativeSignature</code>
| <code>GetPlayerCount</code>
| <code>RetrieveNativeSignature()</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).
|-
|-
| <code>RotateOrientation</code>
| <code>GetRandomAdjacentArea</code>
| <code>QAngle RotateOrientation(QAngle, QAngle)</code>
| <code>CTFNavArea GetRandomAdjacentArea([[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'')</code>
| Rotate a QAngle by another QAngle.
| Return a random adjacent area in the given direction.
|-
|-
| <code>RotatePosition</code>
| <code>GetSizeX</code>
| <code>Vector RotatePosition(Vector, QAngle, Vector)</code>
| <code>float GetSizeX()</code>
| Rotate a Vector around a point.
| Return the area size along the X axis.
|-
|-
| <code>rstrip</code>
| <code>GetSizeY</code>
| <code>rstrip(string)</code>
| <code>float GetSizeY()</code>
|  
| Return the area size along the Y axis.
|-
|-
| <code>Say</code>
| <code>GetTravelDistanceToBombTarget</code>
| <code>void Say(handle, string, bool)</code>
| <code>float GetTravelDistanceToBombTarget()</code>
| Have Entity say string, and teamOnly or not
| Gets the travel distance to the MvM bomb target.
|-
|-
| <code>ScreenFade</code>
| <code>GetZ</code>
| <code>void ScreenFade(handle, int, int, int, int, float, float, int)</code>
| <code>float GetZ(Vector ''pos'')</code>
| Start a screenfade with the following parameters. player, red, green, blue, alpha, flFadeTime, flFadeHold, flags
| Return Z of area at (x,y) of 'pos'.
|-
|-
| <code>ScreenShake</code>
| <code>HasAttributeTF</code>
| <code>void ScreenShake(Vector, float, float, float, float, int, bool)</code>
| <code>bool HasAttributeTF([[Team_Fortress_2/Scripting/Script_Functions/Constants#FTFNavAttributeType|FTFNavAttributeType]] ''bits'')</code>
| Start a screenshake with the following parameters. vecCenter, flAmplitude, flFrequency, flDuration, flRadius, eCommand( SHAKE_START = 0, SHAKE_STOP = 1 ), bAirShake
| Has TF-specific area attribute bits of the given ones. The name is slightly misleading, think of this one as "HasAttribute'''s'''TF".
|-
|-
| <code>ScriptDebugAddTextFilter</code>
| <code>HasAttributes</code>
| <code>ScriptDebugAddTextFilter()</code>
| <code>bool HasAttributes([[Team_Fortress_2/Scripting/Script_Functions/Constants#FNavAttributeType|FNavAttributeType]] ''bits'')</code>
|  
| Has area attribute bits of the given ones?.
|-
|-
| <code>ScriptDebugAddTrace</code>
| <code>HasAvoidanceObstacle</code>
| <code>ScriptDebugAddTrace()</code>
| <code>bool HasAvoidanceObstacle(float ''max_height'')</code>
|  
| Returns true if there's a large, immobile object obstructing this area.
|-
|-
| <code>ScriptDebugAddWatch</code>
| <code>IsBlocked</code>
| <code>ScriptDebugAddWatch()</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.
|-
|-
| <code>ScriptDebugAddWatches</code>
| <code>IsBottleneck</code>
| <code>ScriptDebugAddWatches()</code>
| <code>bool IsBottleneck()</code>
|  
| Returns true if area is a bottleneck. (tiny narrow areas with only one path).
|-
|-
| <code>ScriptDebugAddWatchPattern</code>
| <code>IsCompletelyVisibleToTeam</code>
| <code>ScriptDebugAddWatchPattern()</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.
|-
|-
| <code>ScriptDebugClearTraces</code>
| <code>IsConnected</code>
| <code>ScriptDebugClearTraces()</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).
|-
|-
| <code>ScriptDebugClearWatches</code>
| <code>IsCoplanar</code>
| <code>ScriptDebugClearWatches()</code>
| <code>bool IsCoplanar(handle ''area'')</code>
|  
| Return true if this area and given. area are approximately co-planar.
|-
|-
| <code>ScriptDebugDefaultWatchColor</code>
| <code>IsDamaging</code>
| <code>ScriptDebugDefaultWatchColor()</code>
| <code>bool IsDamaging()</code>
|  
| Return true if this area is marked to have continuous damage.
|-
|-
| <code>ScriptDebugDraw</code>
| <code>IsDegenerate</code>
| <code>ScriptDebugDraw()</code>
| <code>bool IsDegenerate()</code>
|  
| Return true if this area is badly formed.
|-
|-
| <code>ScriptDebugDrawWatches</code>
| <code>IsEdge</code>
| <code>ScriptDebugDrawWatches()</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.
|-
|-
| <code>ScriptDebugDumpKeys</code>
| <code>IsFlat</code>
| <code>ScriptDebugDumpKeys()</code>
| <code>bool IsFlat()</code>
|  
| Return true if this area is approximately flat.
|-
|-
| <code>ScriptDebugHook</code>
| <code>IsOverlapping</code>
| <code>ScriptDebugHook()</code>
| <code>bool IsOverlapping(handle ''area'')</code>
|  
| Return true if 'area' overlaps our 2D extents.
|-
|-
| <code>ScriptDebugIterateKeys</code>
| <code>IsOverlappingOrigin</code>
| <code>ScriptDebugIterateKeys()</code>
| <code>bool IsOverlappingOrigin(Vector ''pos'', float ''tolerance'')</code>
|  
| Return true if 'pos' is within 2D extents of area.
|-
|-
| <code>ScriptDebugIterateKeysRecursive</code>
| <code>IsPotentiallyVisibleToTeam</code>
| <code>ScriptDebugIterateKeysRecursive()</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.
|-
|-
| <code>ScriptDebugRemoveTextFilter</code>
| <code>IsReachableByTeam</code>
| <code>ScriptDebugRemoveTextFilter()</code>
| <code>bool IsReachableByTeam([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'')</code>
|  
| Is this area reachable by the given team?
|-
|-
| <code>ScriptDebugRemoveTrace</code>
| <code>IsRoughlySquare</code>
| <code>ScriptDebugRemoveTrace()</code>
| <code>bool IsRoughlySquare()</code>
|  
| Return true if this area is approximately square.
|-
|-
| <code>ScriptDebugRemoveWatch</code>
| <code>IsTFMarked</code>
| <code>ScriptDebugRemoveWatch()</code>
| <code>bool IsTFMarked()</code>
|  
| Is this nav area marked with the current marking scope?
|-
|-
| <code>ScriptDebugRemoveWatches</code>
| <code>IsUnderwater</code>
| <code>ScriptDebugRemoveWatches()</code>
| <code>bool IsUnderwater()</code>
|  
| Return true if area is underwater.
|-
|-
| <code>ScriptDebugRemoveWatchPattern</code>
| <code>IsValidForWanderingPopulation</code>
| <code>ScriptDebugRemoveWatchPattern()</code>
| <code>bool IsValidForWanderingPopulation()</code>
|  
| Returns true if area is valid for wandering population.
|-
|-
| <code>ScriptDebugText</code>
| <code>IsVisible</code>
| <code>ScriptDebugText()</code>
| <code>bool IsVisible(Vector ''point'')</code>
|  
| Return true if area is visible from the given eyepoint.
|-
|-
| <code>ScriptDebugTextDraw</code>
| <code>MarkAsBlocked</code>
| <code>ScriptDebugTextDraw()</code>
| <code>void MarkAsBlocked([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'')</code>
|  
| Mark this area as blocked for team.
|-
|-
| <code>ScriptDebugTextPrint</code>
| <code>MarkAsDamaging</code>
| <code>ScriptDebugTextPrint()</code>
| <code>void MarkAsDamaging(float ''duration'')</code>
|  
| Mark this area is damaging for the next 'duration' seconds.
|-
|-
| <code>ScriptDebugTextTrace</code>
| <code>MarkObstacleToAvoid</code>
| <code>ScriptDebugTextTrace()</code>
| <code>void MarkObstacleToAvoid(float ''height'')</code>
|  
| Marks the obstructed status of the nav area.
|-
|-
| <code>ScriptDebugTraceAll</code>
| <code>RemoveAttributes</code>
| <code>ScriptDebugTraceAll()</code>
| <code>void RemoveAttributes([[Team_Fortress_2/Scripting/Script_Functions/Constants#FNavAttributeType|FNavAttributeType]] ''bits'')</code>
|
| Removes area attribute bits.
|-
| <code>ScriptDebugWatches</code>
| <code>ScriptDebugWatches()</code>
|  
|-
|-
| <code>SendToConsole</code>
| <code>RemoveOrthogonalConnections</code>
| <code>void SendToConsole(string)</code>
| <code>void RemoveOrthogonalConnections([[Team_Fortress_2/Scripting/Script_Functions/Constants#ENavDirType|ENavDirType]] ''dir'')</code>
| Send a string to the console as a command
| Removes all connections in directions to left and right of specified direction.
|-
|-
| <code>SendToConsoleServer</code>
| <code>SetAttributeTF</code>
| <code>void SendToConsoleServer(string)</code>
| <code>void SetAttributeTF([[Team_Fortress_2/Scripting/Script_Functions/Constants#FTFNavAttributeType|FTFNavAttributeType]] ''bits'')</code>
| Copy of SendToServerConsole with another name for compat.
| Set TF-specific area attributes.
|-
|-
| <code>SendToServerConsole</code>
| <code>SetAttributes</code>
| <code>void SendToServerConsole(string)</code>
| <code>void SetAttributes([[Team_Fortress_2/Scripting/Script_Functions/Constants#FNavAttributeType|FNavAttributeType]] ''bits'')</code>
| Send a string that gets executed on the server as a ServerCommand
| Set area attribute bits.
|-
|-
| <code>setconsttable</code>
| <code>SetPlaceName</code>
| <code>setconsttable()</code>
| <code>void SetPlaceName(string ''name'')</code>
|  
| Set place name. If you pass null, the place name will be set to nothing.
|-
|-
| <code>setdebughook</code>
| <code>TFMark</code>
| <code>setdebughook()</code>
| <code>void TFMark()</code>
|  
| Mark this nav area with the current marking scope.
|-
|-
| <code>seterrorhandler</code>
| <code>UnblockArea</code>
| <code>seterrorhandler()</code>
| <code>void UnblockArea()</code>
|  
| Unblocks this area.
|}
 
=== CNavMesh ===
Game Instance: <code>NavMesh</code>
 
An interface to collect nav areas from, especially for pathfinding needs.
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
|-
| <code>SetFakeClientConVarValue</code>
| <code>FindNavAreaAlongRay</code>
| <code>void SetFakeClientConVarValue(handle, string, string)</code>
| <code>CTFNavArea FindNavAreaAlongRay(Vector ''start_pos'', Vector ''end_pos'', handle ''ignore_area'')</code>
| Sets a USERINFO client ConVar for a fakeclient
| Get nav area from ray.
|-
|-
| <code>SetGravityMultiplier</code>
| <code>GetAllAreas</code>
| <code>void SetGravityMultiplier(float)</code>
| <code>void GetAllAreas(table ''result'')</code>
|  
| Fills a passed in table of all nav areas.
|-
|-
| <code>SetMannVsMachineAlarmStatus</code>
| <code>GetAreasWithAttributes</code>
| <code>void SetMannVsMachineAlarmStatus(bool)</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.
|-
|-
| <code>SetOvertimeAllowedForCTF</code>
| <code>GetNavArea</code>
| <code>void SetOvertimeAllowedForCTF(bool)</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.
|-
|-
| <code>SetPlayersInHell</code>
| <code>GetNavAreaByID</code>
| <code>void SetPlayersInHell(bool)</code>
| <code>CTFNavArea GetNavAreaByID(int ''area_id'')</code>
|  
| Get nav area by ID.
|-
|-
| <code>setroottable</code>
| <code>GetNavAreaCount</code>
| <code>setroottable()</code>
| <code>int GetNavAreaCount()</code>
|  
| Return total number of nav areas.
|-
|-
| <code>SetUsingSpells</code>
| <code>GetNavAreasFromBuildPath</code>
| <code>void SetUsingSpells(bool)</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 '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>ShowMessage</code>
| <code>GetNavAreasInRadius</code>
| <code>void ShowMessage(string)</code>
| <code>void GetNavAreasInRadius(Vector ''origin'', float ''radius'', table ''result'')</code>
| Print a hud message on all clients
| Fills a passed in table of nav areas within radius.
|-
|-
| <code>sin</code>
| <code>GetNavAreasOverlappingEntityExtent</code>
| <code>sin(num)</code>
| <code>void GetNavAreasOverlappingEntityExtent(handle ''entity'', table ''result'')</code>
|  
| Fills passed in table with areas overlapping entity's extent.
|-
|-
| <code>SpawnEntityFromTable</code>
| <code>GetNearestNavArea</code>
| <code>handle SpawnEntityFromTable(string, handle)</code>
| <code>CTFNavArea GetNearestNavArea(Vector ''origin'', float ''max_distance'', bool ''check_los'', bool ''check_ground'')</code>
| Spawn entity from KeyValues in table - 'name' is entity name, rest are KeyValues for spawn.
| Given a position in the world, return the nav area that is closest to or below that height.
|-
|-
| <code>SpawnEntityGroupFromTable</code>
| <code>GetObstructingEntities</code>
| <code>bool SpawnEntityGroupFromTable(handle)</code>
| <code>void GetObstructingEntities(table ''result'')</code>
| Hierarchically spawn an entity group from a set of spawn tables.
| Fills a passed in table of all obstructing entities.
|-
|-
| <code>split</code>
| <code>NavAreaBuildPath</code>
| <code>split(string, string)</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.
|-
|-
| <code>sqrt</code>
| <code>NavAreaTravelDistance</code>
| <code>sqrt(num)</code>
| <code>float NavAreaTravelDistance(CTFNavArea ''start_area'', CTFNavArea ''end_area'', float ''max_path_length'')</code>
|  
| Compute distance between two areas. Return -1.0 if can't reach 'end_area' from 'start_area'.
|-
|-
| <code>srand</code>
| <code>RegisterAvoidanceObstacle</code>
| <code>srand(num)</code>
| <code>void RegisterAvoidanceObstacle(handle ''entity'')</code>
|  
| Registers avoidance obstacle.
|-
|-
| <code>StopAmbientSoundOn</code>
| <code>UnregisterAvoidanceObstacle</code>
| <code>void StopAmbientSoundOn(string, handle)</code>
| <code>void UnregisterAvoidanceObstacle(handle ''entity'')</code>
| Stop named ambient sound on an entity.
| Unregisters avoidance obstacle.
|}
 
=== CNetPropManager ===
Game Instance: <code>NetProps</code>
 
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.}}
 
{{tip|Resources for finding netprops and datamaps of entities:
* Interactive viewer of netprops: https://jackz.me/netprops/tf2
* 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
}}
 
{{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.}}
{{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 ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>GetPropArraySize</code>
| <code>int GetPropArraySize(handle ''entity'', string ''property_name'')</code>
| Returns the size of an netprop array, or -1.
|-
| <code>GetPropEntity</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.
|-
| <code>GetPropEntityArray</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.
|-
| <code>GetPropBool</code>
| <code>bool GetPropBool(handle ''entity'', string ''property_name'')</code>
| Reads a boolean-valued netprop.
|-
|-
| <code>StopSoundOn</code>
| <code>GetPropBoolArray</code>
| <code>void StopSoundOn(string, handle)</code>
| <code>bool GetPropBoolArray(handle ''entity'', string ''property_name'', int ''array_element'')</code>
| Stop named sound on Entity
| Reads a boolean-valued netprop from an array.
|-
|-
| <code>StringToFile</code>
| <code>GetPropFloat</code>
| <code>bool StringToFile(string, string)</code>
| <code>float GetPropFloat(handle ''entity'', string ''property_name'')</code>
| Store a string to a file for later reading
| Reads a float-valued netprop.
|-
|-
| <code>strip</code>
| <code>GetPropFloatArray</code>
| <code>strip(string)</code>
| <code>float GetPropFloatArray(handle ''entity'', string ''property_name'', int ''array_element'')</code>
|  
| Reads a float-valued netprop from an array.
|-
|-
| <code>suspend</code>
| <code>GetPropInfo</code>
| <code>suspend()</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.
|-
|-
| <code>tan</code>
| <code>GetPropInt</code>
| <code>tan(num)</code>
| <code>int GetPropInt(handle ''entity'', string ''property_name'')</code>
|  
| Reads an integer-valued netprop.
|-
|-
| <code>Time</code>
| <code>GetPropIntArray</code>
| <code>float Time()</code>
| <code>int GetPropIntArray(handle ''entity'', string ''property_name'', int ''array_element'')</code>
| Get the current server time
| Reads an integer-valued netprop from an array.
|-
|-
| <code>TraceLine</code>
| <code>GetPropString</code>
| <code>float TraceLine(Vector, Vector, handle)</code>
| <code>string GetPropString(handle ''entity'', string ''property_name'')</code>
| given 2 points & ent to ignore, return fraction along line that hits world or models
| Reads an string-valued netprop.
|-
|-
| <code>TraceLineEx</code>
| <code>GetPropStringArray</code>
| <code>bool TraceLineEx(handle)</code>
| <code>string GetPropStringArray(handle ''entity'', string ''property_name'', int ''array_element'')</code>
| Pass table - Inputs: start, end, mask, ignore  -- outputs: pos, fraction, hit, enthit, startsolid
| Reads an string-valued netprop from an array.
|-
|-
| <code>TraceLinePlayersIncluded</code>
| <code>GetPropType</code>
| <code>float TraceLinePlayersIncluded(Vector, Vector, handle)</code>
| <code>string GetPropType(handle ''entity'', string ''property_name'')</code>
| given 2 points & ent to ignore, return fraction along line that hits world, models, players or npcs
| Returns the name of the netprop type as a string.
|-
|-
| <code>type</code>
| <code>GetPropVector</code>
| <code>type()</code>
| <code>Vector GetPropVector(handle ''entity'', string ''property_name'')</code>
|  
| Reads a 3D vector-valued netprop.
|-
|-
| <code>UniqueString</code>
| <code>GetPropVectorArray</code>
| <code>function UniqueString(string)</code>
| <code>Vector GetPropVectorArray(handle ''entity'', string ''property_name'', int ''array_element'')</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.
| Reads a 3D vector-valued netprop from an array.
|-
|-
| <code>UsePlayerReadyStatusMode</code>
| <code>GetTable</code>
| <code>bool UsePlayerReadyStatusMode()</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 prop_type to 0 for SendTable or 1 for DataMap).
|-
|-
| <code>VSquirrel_OnCreateScope</code>
| <code>HasProp</code>
| <code>VSquirrel_OnCreateScope()</code>
| <code>bool HasProp(handle ''entity'', string ''property_name'')</code>
|  
| Checks if a netprop exists.
|-
|-
| <code>VSquirrel_OnReleaseScope</code>
| <code>SetPropBool</code>
| <code>VSquirrel_OnReleaseScope()</code>
| <code>void SetPropBool(handle ''entity'', string ''property_name'', bool ''value'')</code>
|  
| Sets a netprop to the specified boolean.
|-
| <code>SetPropBoolArray</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.
|-
| <code>SetPropEntity</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.
|-
| <code>SetPropEntityArray</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.
|-
| <code>SetPropFloat</code>
| <code>void SetPropFloat(handle ''entity'', string ''property_name'', float ''value'')</code>
| Sets a netprop to the specified float.
|-
| <code>SetPropFloatArray</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.
|-
| <code>SetPropInt</code>
| <code>void SetPropInt(handle ''entity'', string ''property_name'', int ''value'')</code>
| 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>void SetPropIntArray(handle ''entity'', string ''property_name'', int ''value'', int ''array_element'')</code>
| Sets a netprop from an array to the specified integer.
|-
| <code>SetPropString</code>
| <code>void SetPropString(handle ''entity'', string ''property_name'', string ''value'')</code>
| Sets a netprop to the specified string.
|-
| <code>SetPropStringArray</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.
|-
| <code>SetPropVector</code>
| <code>void SetPropVector(handle ''entity'', string ''property_name'', Vector ''value'')</code>
| Sets a netprop to the specified vector.
|-
| <code>SetPropVectorArray</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.
|}
 
=== CScriptEntityOutputs ===
Game Instance: <code>EntityOutputs</code>
 
Allows reading and manipulation of entity output data.
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>AddOutput</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.
|-
| <code>GetNumElements</code>
| <code>int GetNumElements(handle ''entity'', string ''output_name'')</code>
| Returns the number of array elements.
|-
| <code>GetOutputTable</code>
| <code>void GetOutputTable(handle ''entity'', string ''output_name'', table, int ''array_element'')</code>
| Fills the passed table with output information.
|-
| <code>HasAction</code>
| <code>bool HasAction(handle ''entity'', string ''output_name'')</code>
| Returns true if an action exists for the output.
|-
| <code>HasOutput</code>
| <code>bool HasOutput(handle ''entity'', string ''output_name'')</code>
| Returns true if the output exists.
|-
| <code>RemoveOutput</code>
| <code>void RemoveOutput(handle ''entity'', string ''output_name'', string ''targetname'', string ''input_name'', string ''parameter'')</code>
| 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 ===
Script handle representation of a model's [[$keyvalues]] block.
All sub-keys are instances of the same class.
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>FindKey</code>
| <code>CScriptKeyValues FindKey(string ''key'')</code>
| Find a sub key by the key name.
|-
| <code>GetFirstSubKey</code>
| <code>CScriptKeyValues GetFirstSubKey()</code>
| Return the first sub key object.
|-
| <code>GetKeyBool</code>
| <code>bool GetKeyBool(string ''key'')</code>
| Return the key value as a bool.
|-
| <code>GetKeyFloat</code>
| <code>float GetKeyFloat(string ''key'')</code>
| Return the key value as a float.
|-
| <code>GetKeyInt</code>
| <code>int GetKeyInt(string ''key'')</code>
| Return the key value as an integer.
|-
| <code>GetKeyString</code>
| <code>string GetKeyString(string ''key'')</code>
| Return the key value as a string.
|-
| <code>GetNextKey</code>
| <code>CScriptKeyValues GetNextKey()</code>
| Return the next neighbor key object to the one the method is called on.
|-
| <code>IsKeyEmpty</code>
| <code>bool IsKeyEmpty(string ''key'')</code>
| Returns true if the named key has no value.
|-
| <code>IsValid</code>
| <code>bool IsValid()</code>
| Whether the handle belongs to a valid key.
|-
| <code>ReleaseKeyValues</code>
| <code>void ReleaseKeyValues()</code>
| Releases the contents of the instance.
|}
 
 
=== CPlayerVoiceListener ===
Game Instance: <code>PlayerVoiceListener</code>
 
Tracks if any player is using voice and for how long.
 
==== Methods ====
{| class="standard-table" style="width:100%"
! Function
! Signature
! Description
|-
| <code>GetPlayerSpeechDuration</code>
| <code>float GetPlayerSpeechDuration(int ''player_index'')</code>
| Returns the number of seconds the player has been continuously speaking.
|-
| <code>IsPlayerSpeaking</code>
| <code>bool IsPlayerSpeaking(int ''player_index'')</code>
| Returns whether the player specified is speaking.
|}
 
=== CEnvEntityMaker ===
Extends [[#CBaseEntity|CBaseEntity ↑]]
 
Script handle class for [[env_entity_maker]].
 
==== Methods ====
{| class="standard-table" style="width:100%"
! Function
! Signature
! Description
|-
| <code>SpawnEntity</code>
| <code>void SpawnEntity()</code>
| Create an entity at the location of the maker.
|-
| <code>SpawnEntityAtEntityOrigin</code>
| <code>void SpawnEntityAtEntityOrigin(handle ''entity'')</code>
| Create an entity at the location of a specified entity instance.
|-
| <code>SpawnEntityAtLocation</code>
| <code>void SpawnEntityAtLocation(Vector ''origin'', Vector ''orientation'')</code>
| Create an entity at a specified location and orientation, orientation is Euler angle in degrees (pitch, yaw, roll).
|-
| <code>SpawnEntityAtNamedEntityOrigin</code>
| <code>void SpawnEntityAtNamedEntityOrigin(string ''targetname'')</code>
| 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|CBaseEntity ↑]]
 
Script handle class for {{ent|point_template}}.
 
==== Hooks ====
;<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.
{{ExpandBox|<source lang=js>
function PreSpawnInstance(entity_class, entity_name)
{
local keyvalues =
{
rendercolor = "0 255 0",
targetname = "my_spawned_entity"
}
 
return keyvalues
}
</source>}}
 
;<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.
{{note|PostSpawn() will not be called unless the PreSpawnInstance() function is also defined in the script.}}
{{ExpandBox|<source lang=js>
function PostSpawn( entities )
{
foreach(targetname, handle in entities)
{
printl(targetname + ": " + handle)
}
}
</source>}}
 
===== 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.
{{ExpandBox|<source lang=js>
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)
</source>}}
 
Spawn templated entities from any script.
{{ExpandBox|<source lang=js>
local ent = SpawnMyEntity({
rendercolor = Vector(RandomInt(0, 255), RandomInt(0, 255), RandomInt(0, 255))
})
 
printl( ent )
</source>}}
 
=== CFuncTrackTrain ===
Extends [[#CBaseEntity|CBaseEntity ↑]]
 
Script handle class for {{ent|func_tracktrain}}.
 
==== Methods ====
{| class="standard-table" style="width:100%"
! Function
! Signature
! Description
|-
| <code>GetFuturePosition</code>
| <code>Vector GetFuturePosition(float ''x'', float ''speed'')</code>
| Get a position on the track X seconds in the future.
|-
|}
 
 
=== CPointScriptTemplate ===
Extends [[#CBaseEntity|CBaseEntity ↑]]
 
Script handle class for {{ent|point_script_template}}.
 
==== Methods ====
{| class="standard-table" style="width:100%"
! Function
! Signature
! Description
|-
| <code>AddTemplate</code>
| <code>void AddTemplate(string ''classname'', table ''keyvalues'')</code>
| 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>void SetGroupSpawnTables(table ''group'', table ''spawn'')</code>
| 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 ===
Extends [[#CBaseEntity|CBaseEntity ↑]]
 
Script handle class for {{ent|scripted_scene}}, which make use of [[VCD]] data.
 
==== Methods ====
{| class="standard-table" style="width:100%"
! Function
! Signature
! Description
|-
| <code>AddBroadcastTeamTarget</code>
| <code>void AddBroadcastTeamTarget(int ''index'')</code>
| Adds a team (by index) to the broadcast list.
|-
| <code>EstimateLength</code>
| <code>float EstimateLength()</code>
| Returns length of this scene in seconds.
|-
| <code>FindNamedEntity</code>
| <code>handle FindNamedEntity(string ''reference'')</code>
| Given an entity reference, such as !target, get actual entity from scene object.
|-
| <code>IsPaused</code>
| <code>bool IsPaused()</code>
| If this scene is currently paused.
|-
| <code>IsPlayingBack</code>
| <code>bool IsPlayingBack()</code>
| If this scene is currently playing.
|-
| <code>LoadSceneFromString</code>
| <code>bool LoadSceneFromString(string ''scene_name'', string ''scene'')</code>
| Given a dummy scene name and a vcd string, load the scene.
|-
| <code>RemoveBroadcastTeamTarget</code>
| <code>void RemoveBroadcastTeamTarget(int ''index'')</code>
| 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 <code>chains</code> table with the prefix removed. All collected unprefixed functions can then be called in a chain using the class's <code>Call()</code> method, given the method's ''event'' argument matches the functions' name.
 
Whenever a '''CCallChainer''' object is created, a function named <code>Dispatch</code> followed by its given prefix will also be created, which  the class binds the environment of its <code>Call()</code> method to.
 
==== Methods ====
{| class="standard-table" style="width:100%"
! Function
! Signature
! Description
|-
| <code>constructor</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.
|-
| <code>PostScriptExecute</code>
| <code>void PostScriptExecute()</code>
| Search for all non-native functions with matching prefixes, then push them into the <code>chains</code> table.
|-
| <code>Call</code>
| <code>bool Call(string ''event'', any ...)</code>
| Find an unprefixed function name in the <code>chains</code> table and call it with the given arguments.
|}
 
==== Members ====
{| class="standard-table" style="width:100%"
! Instance
! Type
! Description
|-
| <code>chains</code>
| <code>table</code>
| Contains names of unprefixed functions, each with an array of functions to call.
|-
| <code>prefix</code>
| <code>string</code>
| Prefix that functions should have to be added into the <code>chains</code> table. Set by the constructor.
|-
| <code>scope</code>
| <code>table</code>
| If set, seek functions in this scope instead. Set by the constructor.
|}
 
=== 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.
 
This class is also used internally by these [[#CBaseEntity|CBaseEntity ↑]] hooks: <code>Precache()</code> and <code>OnPostSpawn()</code>.
 
==== Methods ====
{| class="standard-table" style="width:100%"
! Function
! Signature
! Description
|-
| <code>constructor</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.
|-
| <code>PostScriptExecute</code>
| <code>void PostScriptExecute()</code>
| Begin searching for all non-native functions with matching prefixes, then push them into the <code>chain</code> array.
|-
| <code>Call</code>
| <code>bool Call(any ...)</code>
| Call all functions inside the <code>chain</code> array with the given arguments.
|}
 
==== Members ====
{| class="standard-table" style="width:100%"
! Instance
! Type
! Description
|-
| <code>chain</code>
| <code>array</code>
| All functions to be called by the <code>Call()</code> method.
|-
| <code>exactMatch</code>
| <code>bool</code>
| If set, names of non-native functions and <code>prefix</code> must be an exact match.  Set by the constructor.
|-
| <code>prefix</code>
| <code>string</code>
| Prefix that functions should have to be added into the <code>chain</code> array. Set by the constructor.
|-
| <code>scope</code>
| <code>table</code>
| If set, seek functions in this scope instead. Set by the constructor.
|}
 
=== NextBotCombatCharacter ===
Extends [[#CBaseCombatCharacter|CBaseCombatCharacter ↑]]
 
Script handle class for non-playable combat characters operating under the [[NextBot]] system.
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>ClearImmobileStatus</code>
| <code>void ClearImmobileStatus()</code>
| Clear immobile status.
|-
| <code>FlagForUpdate</code>
| <code>void FlagForUpdate(bool ''toggle'')</code>
| 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>INextBotComponent GetBodyInterface()</code>
| Get this bot's body interface.
{{note|Not actually exposed, no functions exist.}}
|-
| <code>GetBotId</code>
| <code>int GetBotId()</code>
| Get this bot's id.
|-
| <code>GetImmobileDuration</code>
| <code>float GetImmobileDuration()</code>
| How long have we been immobile.
|-
| <code>GetImmobileSpeedThreshold</code>
| <code>float GetImmobileSpeedThreshold()</code>
| Return units/second below which this actor is considered immobile.
|-
| <code>GetIntentionInterface</code>
| <code>INextBotComponent GetIntentionInterface()</code>
| Get this bot's intention interface.
{{note|Not actually exposed, no functions exist.}}
|-
| <code>GetLocomotionInterface</code>
| <code>ILocomotion GetLocomotionInterface()</code>
| Get this bot's locomotion interface.
|-
| <code>GetTickLastUpdate</code>
| <code>int GetTickLastUpdate()</code>
| Get last update tick.
|-
| <code>GetVisionInterface</code>
| <code>INextBotComponent GetVisionInterface()</code>
| Get this bot's vision interface.
{{note|Not actually exposed, no functions exist.}}
|-
| <code>IsEnemy</code>
| <code>bool IsEnemy(handle ''entity'')</code>
| Return true if given entity is our enemy.
|-
| <code>IsFlaggedForUpdate</code>
| <code>bool IsFlaggedForUpdate()</code>
| Is this bot flagged for update.
|-
| <code>IsFriend</code>
| <code>bool IsFriend(handle ''entity'')</code>
| Return true if given entity is our friend.
|-
| <code>IsImmobile</code>
| <code>bool IsImmobile()</code>
| Return true if we haven't moved in awhile.
|}
 
=== INextBotComponent ===
Base script handle class for any interfaces belonging to an individual [[#NextBotCombatCharacter|NextBotCombatCharacter ↑]] entity.
 
==== Methods ====
{| class="standard-table" style="width:100%"
! Function
! Signature
! Description
|-
| <code>ComputeUpdateInterval</code>
| <code>bool ComputeUpdateInterval()</code>
| Recomputes the component update interval.
|-
| <code>GetUpdateInterval</code>
| <code>float GetUpdateInterval()</code>
| Returns the component update interval.
|-
| <code>Reset</code>
| <code>void Reset()</code>
| Resets the internal update state
|}
 
=== ILocomotion ===
Extends [[#INextBotComponent|INextBotComponent ↑]]
 
The interface for interacting with a specific NextBot's movement brain.
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>Approach</code>
| <code>void Approach(Vector ''goal'', float ''goal_weight'')</code>
| 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>void ClearStuckStatus(string ''reason'')</code>
| Reset stuck status to un-stuck. Reason message is shown when debugging nextbots.
|-
| <code>ClimbUpToLedge</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.
|-
| <code>ComputeUpdateInterval</code>
| <code>bool ComputeUpdateInterval()</code>
| Returns false if no time has elapsed.
|-
| <code>DriveTo</code>
| <code>void DriveTo(Vector ''pos'')</code>
| Move the bot to the precise given position immediately, updating internal state.
|-
| <code>FaceTowards</code>
| <code>void FaceTowards(Vector ''target'')</code>
| 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>float FractionPotentialGap(Vector ''from'', Vector ''to'')</code>
| If the locomotor cannot jump over the gap, returns the fraction of the jumpable ray.
|-
| <code>FractionPotentiallyTraversable</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 ''immediately'' is true, breakables are considered non-traverseable.
|-
| <code>GetDeathDropHeight</code>
| <code>float GetDeathDropHeight()</code>
| Distance at which we will die if we fall.
|-
| <code>GetDesiredSpeed</code>
| <code>float GetDesiredSpeed()</code>
| Get desired speed for locomotor movement.
|-
| <code>GetFeet</code>
| <code>Vector GetFeet()</code>
| Return position of feet - the driving point where the bot contacts the ground.
|-
| <code>GetGround</code>
| <code>handle GetGround()</code>
| Return the current ground entity or NULL if not on the ground.
|-
| <code>GetGroundMotionVector</code>
| <code>Vector GetGroundMotionVector()</code>
| Return unit vector in XY plane describing our direction of motion - even if we are currently not moving.
|-
| <code>GetGroundNormal</code>
| <code>Vector GetGroundNormal()</code>
| Surface normal of the ground we are in contact with.
|-
| <code>GetGroundSpeed</code>
| <code>float GetGroundSpeed()</code>
| Return current world space speed in XY plane.
|-
| <code>GetMaxAcceleration</code>
| <code>float GetMaxAcceleration()</code>
| Return maximum acceleration of locomotor.
|-
| <code>GetMaxDeceleration</code>
| <code>float GetMaxDeceleration()</code>
| Return maximum deceleration of locomotor.
|-
| <code>GetMaxJumpHeight</code>
| <code>float GetMaxJumpHeight()</code>
| 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>Vector GetMotionVector()</code>
| Return unit vector describing our direction of motion - even if we are currently not moving.
|-
| <code>GetRunSpeed</code>
| <code>float GetRunSpeed()</code>
| Get maximum running speed.
|-
| <code>GetSpeed</code>
| <code>float GetSpeed()</code>
| Return current world space speed (magnitude of velocity).
|-
| <code>GetSpeedLimit</code>
| <code>float GetSpeedLimit()</code>
| Get maximum speed bot can reach, regardless of desired speed.
|-
| <code>GetStepHeight</code>
| <code>float GetStepHeight()</code>
| 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>float GetStuckDuration()</code>
| Return how long we've been stuck.
|-
| <code>GetTraversableSlopeLimit</code>
| <code>float GetTraversableSlopeLimit()</code>
| Return Z component of unit normal of steepest traversable slope.
|-
| <code>GetUpdateInterval</code>
| <code>float GetUpdateInterval()</code>
| Returns time between updates.
|-
| <code>GetVelocity</code>
| <code>Vector GetVelocity()</code>
| Return current world space velocity.
|-
| <code>GetWalkSpeed</code>
| <code>float GetWalkSpeed()</code>
| Get maximum walking speed.
|-
| <code>HasPotentialGap</code>
| <code>float HasPotentialGap(Vector ''from'', Vector ''to'')</code>
| 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>bool IsAbleToClimb()</code>
| Return true if this bot can climb arbitrary geometry it encounters.
|-
| <code>IsAbleToJumpAcrossGaps</code>
| <code>bool IsAbleToJumpAcrossGaps()</code>
| Return true if this bot can jump across gaps in its path.
|-
| <code>IsAreaTraversable</code>
| <code>bool IsAreaTraversable(handle ''area'')</code>
| Return true if given area can be used for navigation.
|-
| <code>IsAttemptingToMove</code>
| <code>bool IsAttemptingToMove()</code>
| Return true if we have tried to Approach() or DriveTo() very recently.
|-
| <code>IsClimbingOrJumping</code>
| <code>bool IsClimbingOrJumping()</code>
| Is jumping in any form.
|-
| <code>IsClimbingUpToLedge</code>
| <code>bool IsClimbingUpToLedge()</code>
| Is climbing up to a high ledge.
|-
| <code>IsEntityTraversable</code>
| <code>bool IsEntityTraversable(handle ''entity'', bool ''immediately'')</code>
| Return true if the entity handle is traversable. If ''immediately'' is true, breakables are considered non-traverseable.
|-
| <code>IsGap</code>
| <code>bool IsGap(Vector ''pos'', Vector ''forward'')</code>
| Return true if there is a gap at this position.
{{note|''forward'' is unused.}}.
|-
| <code>IsJumpingAcrossGap</code>
| <code>bool IsJumpingAcrossGap()</code>
| Is jumping across a gap to the far side.
|-
| <code>IsOnGround</code>
| <code>bool IsOnGround()</code>
| Return true if standing on something.
|-
| <code>IsPotentiallyTraversable</code>
| <code>float IsPotentiallyTraversable(Vector ''from'', Vector ''to'', bool ''immediately'')</code>
| 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>bool IsRunning()</code>
| Is running?
|-
| <code>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.
|-
| <code>IsStuck</code>
| <code>bool IsStuck()</code>
| 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.
|-
| <code>Jump</code>
| <code>void Jump()</code>
| Initiate a simple undirected jump in the air.
|-
| <code>JumpAcrossGap</code>
| <code>void JumpAcrossGap(Vector ''goal_pos'', Vector ''goal_forward'')</code>
| Initiate a jump across an empty volume of space to far side.
{{note|''goal_forward'' is unused.}}
|-
| <code>OnLandOnGround</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.
|-
| <code>OnLeaveGround</code>
| <code>void OnLeaveGround(handle ''ground'')</code>
| Manually run the OnLeaveGround callback. Typically invoked when bot leaves ground for any reason.
|-
| <code>Reset</code>
| <code>void Reset()</code>
| Resets motion, stuck state etc.
|-
| <code>Run</code>
| <code>void Run()</code>
| Set desired movement speed to running.
|-
| <code>SetDesiredSpeed</code>
| <code>void SetDesiredSpeed(float ''speed'')</code>
| Set desired speed for locomotor movement.
|-
| <code>SetSpeedLimit</code>
| <code>void SetSpeedLimit(float ''limit'')</code>
| Set maximum speed bot can reach, regardless of desired speed.
|-
| <code>Stop</code>
| <code>void Stop()</code>
| Set desired movement speed to stopped.
|-
| <code>Walk</code>
| <code>void Walk()</code>
| Set desired movement speed to walking
|}
 
=== LateBinder ===
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>Begin</code>
|
|
|-
| <code>End</code>
|
|
|-
| <code>EstablishDelegation</code>
|
|
|-
| <code>HookRootMetamethod</code>
|
|
|-
| <code>UnhookRootMetamethod</code>
|
|
|-
| <code>RemoveDelegation</code>
|
|
|-
| <code>Resolve</code>
|
|
|}
 
==== Members ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Instance
! Type
! Description
|-
| <code>m_bindNamesStack</code>
| <code>array</code>
|
|-
| <code>m_fixupSet</code>
| <code>array</code>
|
|-
| <code>m_log</code>
| <code>bool</code>
|
|-
| <code>m_logIndent</code>
| <code>int</code>
|
|-
| <code>m_targetTable</code>
| <code>table?(null)</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.0, float ''y'' = 0.0, float ''z'' = 0.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>
| Magnitude of the vector.
|-
| <code>LengthSqr</code>
| <code>float LengthSqr()</code>
| 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>float Length2D()</code>
| Returns the magnitude of the vector on the x-y plane.
|-
| <code>Length2DSqr</code>
| <code>float Length2DSqr()</code>
| Returns the square of the magnitude of the vector on the x-y plane.
|-
| <code>Norm</code>
| <code>float Norm()</code>
| Normalizes the vector in place and returns it's length.
|-
| <code>Scale</code>
| <code>Vector Scale(float ''factor'')</code>
| Scales the vector magnitude.
|-
| <code>ToKVString</code>
| <code>string ToKVString()</code>
| Returns a string without separations commas.
|-
| <code>tostring</code>
| <code>string tostring()</code>
| Returns a human-readable string.
|-
|}
 
==== Members ====
{| class="standard-table" style="width:100%"
! Instance
! Type
! Description
|-
| <code>x</code>
| <code>float</code>
| Cartesian X axis.
|-
| <code>y</code>
| <code>float</code>
| Cartesian Y axis.
|-
| <code>z</code>
| <code>float</code>
| Cartesian Z axis.
|}
 
==== Operations ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Operation
! Return Type
! Description
|-
| <code>Vector + Vector</code>
|rowspan="2"| <code>Vector</code>
|rowspan="2"| Returns the sum of both classes's members.
|-
| <code>QAngle + Vector</code>
|-
| <code>Vector - Vector</code>
|rowspan="2"| <code>Vector</code>
|rowspan="2"| Returns the subtraction of both classes's members.
|-
| <code>QAngle - Vector</code>
|-
| <code>Vector * integer</code>
|rowspan="2"| <code>Vector</code>
|rowspan="2"| Returns the multiplication of a Vector against a scalar.
|-
| <code>Vector * float</code>
|}
 
=== 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 ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>constructor</code>
| <code>QAngle(float ''pitch'' = 0.0, float ''yaw'' = 0.0, float ''roll'' = 0.0)</code>
| Creates a new QAngle.
|-
| <code>Forward </code>
| <code>Vector Forward()</code>
| Returns the Forward Vector of the angles.
|-
| <code>Left</code>
| <code>Vector Left()</code>
| {{note|Returns the ''right'' Vector of the angles.}}
|-
| <code>Pitch</code>
| <code>float Pitch()</code>
| Returns the pitch angle in degrees.
|-
| <code>Roll</code>
| <code>float Roll()</code>
| Returns the roll angle in degrees.
|-
| <code>ToKVString</code>
| <code>string ToKVString()</code>
| Returns a string with the values separated by one space.
|-
| <code>ToQuat</code>
| <code>Quaternion ToQuat()</code>
| Returns a quaternion representaion of the orientation.
|-
| <code>Up</code>
| <code>Vector Up()</code>
| Returns the Up Vector of the angles.
|-
| <code>Yaw</code>
| <code>float Yaw()</code>
| Returns the yaw angle in degrees.
|}
 
==== Members ====
{| class="standard-table" style="width:100%"
! Instance
! Type
! Description
|-
| <code>x</code>
| <code>float</code>
| Pitch in degrees.
|-
| <code>y</code>
| <code>float</code>
| Yaw in degrees.
|-
| <code>z</code>
| <code>float</code>
| Roll in degrees.
|}
 
==== Operations ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Operation
! Return Type
! Description
|-
| <code>QAngle + QAngle</code>
|rowspan="2"| <code>QAngle</code>
|rowspan="2"| Sum of both classes's members (XYZ).
|-
| <code>Vector + QAngle</code>
|-
| <code>QAngle - QAngle</code>
|rowspan="2"| <code>QAngle</code>
|rowspan="2"| Subtraction of both classes's members (XYZ).
|-
| <code>Vector - QAngle</code>
|-
| <code>QAngle * int</code>
|rowspan="2"| <code>QAngle</code>
|rowspan="2"| QAngle multiplied by a number.
|-
| <code>QAngle * float</code>
|}
 
 
=== Vector2D, Vector4D ===
Two and four-dimensional equivalents to Vector with less amount of methods.
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>constructor</code>
| <code>Vector2D(float ''x'' = 0.0, float ''y'' = 0.0)</code>
| 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>float Dot(Vector''X''D ''factor'')</code>
| The scalar product of two vectors.
|-
| <code>Length</code>
| <code>float Length()</code>
| Magnitude of the vector.
|-
| <code>LengthSqr</code>
| <code>float LengthSqr()</code>
| 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>float Norm()</code>
| Normalizes the vector in place and returns it's length.
|-
| <code>ToKVString</code>
| <code>string ToKVString()</code>
| Returns a string without separations commas.
|}
 
 
=== Quaternion ===
[http://en.wikipedia.org/wiki/Quaternion Quaternion] represents rotations in three-dimensional space.
 
==== Methods ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>constructor</code>
| <code>Quaternion()</code>
| Creates a new identity quaternion. (0, 0, 0, 1)
|-
| <code>constructor</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>.
|-
| <code>Dot</code>
| <code>float Dot(Quaternion ''factor'')</code>
| The 4D scalar product of two quaternions. represents the angle between the quaternions in the range [1, 0].
|-
| <code>Invert</code>
| <code>Quaternion Invert()</code>
| Returns a quaternion with the complimentary rotation.
|-
| <code>Norm</code>
| <code>float Norm()</code>
| Normalizes the quaternion.
|-
| <code>SetPitchYawRoll</code>
| <code>void SetPitchYawRoll(float ''pitch'', float ''yaw'', float ''roll'')</code>
| Recomputes the quaternion from the supplied Euler angles.
|-
| <code>ToKVString</code>
| <code>string ToKVString()</code>
| Returns a string with the values separated by one space.
|-
| <code>ToQAngle</code>
| <code>QAngle ToQAngle()</code>
| Returns the angles resulting from the rotation.
|}
 
==== Members ====
{| class="standard-table" style="width:100%"
! Instance
! Type
! Description
|-
| <code>x</code>
| <code>float</code>
| Vector component along the '''i''' axis.
|-
| <code>y</code>
| <code>float</code>
| Vector component along the '''j''' axis.
|-
| <code>z</code>
| <code>float</code>
| Vector component along the '''k''' axis.
|-
| <code>w</code>
| <code>float</code>
| Scalar part.
|}
 
==== Operations ====
{{todo|Descriptions of the operations are lacking details.}}
 
{| class="standard-table" style="width:100%"
! Operation
! Return Type
! Description
|-
| <code>Quaternion + Quaternion</code>
| <code>Quaternion</code>
| Sum of the two Quaternions.
|-
| <code>Quaternion - Quaternion</code>
| <code>Quaternion</code>
| Subtraction of the two Quaternions.
|-
| <code>Quaternion * integer</code>
|rowspan="2"| <code>Quaternion</code>
|rowspan="2"| Quaternion multiplied by a number.
|-
| <code>Quaternion * float</code>
|}
 
== Globals ==
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>AddThinkToEnt</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. 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 [[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.}}}}
{{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>void AddToScriptHelp(table ''help'')</code>
|
|-
| <code>Assert</code>
| <code>void Assert(bool ''value'', string ''optional_message'' = null)</code>
| Test value and if not true, throws exception, optionally with message.
|-
| <code>ClearGameEventCallbacks</code>
| <code>void ClearGameEventCallbacks()</code>
| 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>CreateProp</code>
| <code>CBaseAnimating CreateProp(string ''classname'', Vector ''origin'', string ''model_name'', int ''activity'')</code>
| Create a prop.
|-
| <code>CreateSceneEntity</code>
| <code>CBaseAnimating CreateSceneEntity(string ''scene'')</code>
| Create a scene entity to play the specified scene.
|-
| <code>developer</code>
| <code>int developer()</code>
| The current level of the <code>developer</code> console variable.
|-
| <code>DispatchParticleEffect</code>
| <code>void DispatchParticleEffect(string ''name'', Vector ''origin'', Vector ''direction'')</code>
| 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>void Document(unknown ''symbol_or_table'', unknown ''item_if_symbol'' = null, string ''description_if_symbol'' = null)</code>
|
|-
| <code>DoEntFire</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''. Negative delays are clamped to 0.
{{note|Does not work if the ''target'' string is <code>point_servercommand</code>.}}
|-
| <code>DoIncludeScript</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. 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>bool IncludeScript(string ''file'', table ''scope'' = null)</code>
| Wrapper for DoIncludeScript.
|-
| <code>EmitAmbientSoundOn</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.
{{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>void StopAmbientSoundOn(string ''sound_name'', handle ''entity'')</code>
| Stop named sound on an entity using configurations similar to [[ambient_generic]].
|-
| <code>[[Team Fortress 2/Scripting/Script Functions/EmitSoundEx|EmitSoundEx]]</code>
| <code>void EmitSoundEx(table ''params'')</code>
| 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.
|-
| <code>EmitSoundOn</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>).
{{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>StopSoundOn</code>
| <code>void StopSoundOn(string ''sound_script'', handle ''entity'')</code>
| Stop named sound on an entity.
|-
| <code>EmitSoundOnClient</code>
| <code>void EmitSoundOnClient(string ''sound_script'', handle ''player'')</code>
| Play named sound only on the client for the specified player. The sound must be precached first for it to play (<code>PrecacheScriptSound</code>).
{{note|This only supports soundscripts.}}
|-
| <code>EntFire</code>
| <code>void EntFire(string ''target'', string ''action'', string ''value'' = null, float ''delay'' = 0, handle ''activator'' = null)</code>
| Wrapper for DoEntFire() that sets<code>''activator''</code> to null, but has no<code>''caller''</code>param. Negative delays are clamped to 0.
{{note|Does not work if the ''target'' string is <code>point_servercommand</code>.}}
|-
| <code>EntFireByHandle</code>
| <code>void EntFireByHandle(handle ''entity'', string ''action'', string ''value'', float ''delay'', handle ''activator'', handle ''caller'')</code>
| Generate an entity I/O event. First parameter is an entity instance. Negative delays are clamped to 0.
{{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.}}
{{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]].
{{note|This also affects <code>SetText</code> input on [[game_text]], but accounting for it is not as vital.}}
}}
|-
| <code>EntIndexToHScript</code>
| <code>handle EntIndexToHScript(int ''entindex'')</code>
| Turn an entity index integer to an HScript representing that entity's script instance.
|-
| <code>FileToString</code>
| <code>string FileToString(string ''file'')</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.
{{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>FindCircularReference</code>
| <code>FindCircularReference()</code>
|
|-
| <code>FindCircularReferences</code>
| <code>FindCircularReferences()</code>
|
|-
| <code>FireGameEvent</code>
| <code>bool FireGameEvent(string ''name'', table ''params'')</code>
| 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>FireScriptHook</code>
| <code>bool FireScriptHook(string ''name'', table ''params'')</code>
| Fire a script hook to a listening callback function in script. Parameters are passed in a squirrel table.
|-
| <code>FireScriptEvent</code>
| <code>void FireScriptEvent(string ''event'', table ''params'')</code>
| Wrapper for <code>__RunEventCallbacks()</code>.
|-
| <code>FrameTime</code>
| <code>float FrameTime()</code>
| Get the time spent on the server in the last frame. Usually this will be 0.015 (the default tickrate).
|-
| <code>GetDeveloperLevel</code>
| <code>int GetDeveloperLevel()</code>
| Gets the level of 'developer'
|-
| <code>GetFrameCount</code>
| <code>int GetFrameCount()</code>
| 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>GetFriction</code>
| <code>float GetFriction(CTFPlayer ''player'')</code>
| Returns the Friction on a player entity, meaningless if not a player.
|-
| <code>GetFunctionSignature</code>
| <code>string GetFunctionSignature(function ''func'', string ''prefix'')</code>
|
|-
| <code>GetListenServerHost</code>
| <code>CTFPlayer GetListenServerHost()</code>
| Get the local player on a listen server. Returns null on dedicated servers.
{{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>GetMapName</code>
| <code>string GetMapName()</code>
| 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>.
|-
| <code>GetModelIndex</code>
| <code>int GetModelIndex(string ''model_name'')</code>
| Returns the index of the named model.
|-
| {{obs}} <code>GetPhysAngularVelocity</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.
|-
| {{obs}} <code>GetPhysVelocity</code>
| <code>Vector GetPhysVelocity(handle ''entity'')</code>
| Returns the velocity of the entity. Deprecated, use the <code>GetPhysVelocity</code> method on the entity instead.
|-
| <code>GetPlayerFromUserID</code>
| <code>CTFPlayer GetPlayerFromUserID(int ''userid'')</code>
| Given a user id, return the entity, or null.
{{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>GetSoundDuration</code>
| <code>float GetSoundDuration(string ''sound_name'', string ''actor_model_name'')</code>
| 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.}}
|-
| <code>IsDedicatedServer</code>
| <code>bool IsDedicatedServer()</code>
| Returns true if this server is a dedicated server.
|-
| <code>IsModelPrecached</code>
| <code>bool IsModelPrecached(string ''model_name'')</code>
| Checks if the ''model_name'' is precached.
|-
| <code>IsSoundPrecached</code>
| <code>bool IsSoundPrecached(string ''sound_name'')</code>
| Checks if the ''sound_name'' is precached.
|-
| <code>IsPlayerABot</code>
| <code>bool IsPlayerABot(CTFPlayer ''player'')</code>
| 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>IsWeakref</code>
| <code>bool IsWeakref()</code>
|
|-
| <code>LocalTime</code>
| <code>void LocalTime(table ''result'')</code>
| 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.
{{warning|The month will be 1-12 rather than 0-11.}}
|-
| <code>MakeNamespace</code>
| <code>MakeNamespace()</code>
|
|-
| <code>MaxClients</code>
| <code>float MaxClients()</code>
| 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>PickupObject</code>
| <code>void PickupObject(CTFPlayer ''player'', handle ''entity'')</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.
{{note|Does nothing in {{tf2|2}} as the code is not implemented.}}
|-
| <code>PlayerInstanceFromIndex</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>PrecacheEntityFromTable</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>PrecacheModel</code>
| <code>int PrecacheModel(string ''model_name'')</code>
| 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>PrecacheScriptSound</code>
| <code>bool PrecacheScriptSound(string ''sound_name'')</code>
| Precache a soundscript. Returns false if soundscript is missing, or if a null or empty sound name is passed in.
|-
| <code>PrecacheSound</code>
| <code>bool PrecacheSound(string ''sound_name'')</code>
| Precache a raw sound. Returns false if a null or empty sound name is passed in.
|-
| <code>PrintHelp</code>
| <code>void PrintHelp()</code>
| Equivalent to running <code>script_help</code> command.
|-
| <code>RandomFloat</code>
| <code>float RandomFloat(float ''min'', float ''max'')</code>
| Generate a random floating-point number within a range, inclusive.
|-
| <code>RandomInt</code>
| <code>int RandomInt(int ''min'', int ''max'')</code>
| Generate a random integer within a range, inclusive.
|-
| <code>RegisterFunctionDocumentation</code>
| <code>void RegisterFunctionDocumentation(function ''func'', string ''name'', string ''signature'', string ''description'')</code>
|
|-
| <code>RegisterScriptGameEventListener</code>
| <code>void RegisterScriptGameEventListener(string ''event_name'')</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.
{{note|This cannot be used to register non-existent game events.}}
|-
| <code>RegisterScriptHookListener</code>
| <code>void RegisterScriptHookListener(string ''name'')</code>
| Register as a listener for a script hook from script.
|-
| <code>RetrieveNativeSignature</code>
| <code>string RetrieveNativeSignature(function ''func'')</code>
|
|-
| <code>RotateOrientation</code>
| <code>QAngle RotateOrientation(QAngle ''initial'', QAngle ''rotation'')</code>
| Rotate a QAngle by another QAngle.
|-
| <code>RotatePosition</code>
| <code>Vector RotatePosition(Vector ''origin'', QAngle ''rotation'', Vector ''input'')</code>
| 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>ScreenFade</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>
| Start a customisable screenfade. If no player is specified, the fade will apply to all players.
|-
| <code>ScreenShake</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>
| 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>ScriptHooksEnabled</code>
| <code>bool ScriptHooksEnabled()</code>
| Returns whether script hooks are currently enabled.
|-
| <code>SendGlobalGameEvent</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.}}
{{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!).
Example:
{{ExpandBox|<source lang=js>
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)
</source>
}}}}
|-
| <code>SendToConsole</code>
| <code>void SendToConsole(string ''command'')</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>void SendToServerConsole(string ''command'')</code>
| 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>SendToConsoleServer</code>
| <code>void SendToConsoleServer(string ''command'')</code>
| Copy of SendToServerConsole with another name for compat.
|-
| <code>SetFakeClientConVarValue</code>
| <code>void SetFakeClientConVarValue(CTFBot ''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>SetSkyboxTexture</code>
| <code>void SetSkyboxTexture(string ''texture'')</code>
| 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>SpawnEntityFromTable</code>
| <code>handle SpawnEntityFromTable(string ''name'', table ''keyvalues'')</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.}}
{{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>.}}
{{tip|If spawning multiple entities at once, use <code>SpawnEntityGroupFromTable</code> as it will be more efficient.}}
Example:
{{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>SpawnEntityGroupFromTable</code>
| <code>bool SpawnEntityGroupFromTable(table ''groups'')</code>
| 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. <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>StringToFile</code>
| <code>void StringToFile(string ''file'', string ''string'')</code>
| 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>Time</code>
| <code>float Time()</code>
| 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>TraceLine</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>TraceLinePlayersIncluded</code>
| <code>float TraceLinePlayersIncluded(Vector ''start'', Vector ''end'', handle ''ignore'')</code>
| Different version of <code>TraceLine</code> that also hits players and NPCs.
|-
| <code>[[Team Fortress 2/Scripting/Script Functions/TraceLineEx|TraceLineEx]]</code>
| <code>bool TraceLineEx(table ''params'')</code>
| 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>[[Team Fortress 2/Scripting/Script Functions/TraceHull|TraceHull]]</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>UniqueString</code>
| <code>string UniqueString(string ''suffix'' = null)</code>
| 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>DoUniqueString</code>
| <code>string DoUniqueString(string ''suffix'')</code>
| Internal function called by <code>UniqueString</code>.
|-
| <code>VSquirrel_OnCreateScope</code>
| <code>table VSquirrel_OnCreateScope(any ''value'', table ''scope'')</code>
| Creates a new scope with the name of value in the submitted table (includes unique params).
|-
| <code>VSquirrel_OnReleaseScope</code>
| <code>void VSquirrel_OnReleaseScope(table ''created_scope'')</code>
| Removes a scope created via VSquirrel_OnCreateScope.
|-
| <code>__CollectEventCallbacks</code>
| <code>void __CollectEventCallbacks(scope, prefix, global_table_name, reg_func)</code>
| Overloaded function. Its only used for this: <code>__CollectEventCallbacks(scope, "OnGameEvent_", "GameEventCallbacks", ::RegisterScriptGameEventListener)</code>.
|-
| <code>__CollectGameEventCallbacks</code>
| <code>void __CollectGameEventCallbacks(table ''scope'')</code>
| Wrapper that registers callbacks for both [[#Hooks|OnGameEvent_''x'' ↑]] and <code>OnScriptEvent_</code> functions. Done using the <code>__CollectEventCallbacks</code> function.
|-
| <code>__ReplaceClosures</code>
| <code>void __ReplaceClosures(script, scope)</code>
|
|-
| <code>__RunEventCallbacks</code>
| <code>void __RunEventCallbacks(event, params, prefix, global_table_name, bool warn_if_missing)</code>
| Call all functions in the callback array for the given game event.
|-
| <code>__RunGameEventCallbacks</code>
| <code>void __RunGameEventCallbacks(event, params)</code>
| Wrapper for <code>__RunEventCallbacks()</code>.
|-
| <code>__RunScriptHookCallbacks</code>
| <code>void __RunScriptHookCallbacks(event, param)</code>
|
|}
 
=== Team Fortress 2 ===
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>AllowThirdPersonCamera</code>
| <code>bool AllowThirdPersonCamera()</code>
|
|-
| <code>ArePlayersInHell</code>
| <code>bool ArePlayersInHell()</code>
|
|-
| <code>FlagsMayBeCapped</code>
| <code>bool FlagsMayBeCapped()</code>
| May a flag be captured?
|-
| <code>ForceEnableUpgrades</code>
| <code>void ForceEnableUpgrades(int ''state'')</code>
| Whether to force on MvM-styled upgrades on/off. 0 -> default, 1 -> force off, 2 -> force on.
|-
| <code>ForceEscortPushLogic</code>
| <code>void ForceEscortPushLogic(int ''state'')</code>
| Forces payload pushing logic. 0 -> default, 1 -> force off, 2 -> force on.
|-
| <code>GameModeUsesCurrency</code>
| <code>bool GameModeUsesCurrency()</code>
| Does the current gamemode have currency?
|-
| <code>GameModeUsesMiniBosses</code>
| <code>bool GameModeUsesMiniBosses()</code>
| Does the current gamemode have minibosses?
|-
| <code>GameModeUsesUpgrades</code>
| <code>bool GameModeUsesUpgrades()</code>
| Does the current gamemode have upgrades?
|-
| <code>GetClassLimit</code>
| <code>int GetClassLimit([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFClass|ETFClass]] ''class'')</code>
| Get class limit for class.
|-
| <code>GetGravityMultiplier</code>
| <code>float GetGravityMultiplier()</code>
|
|-
| <code>GetMannVsMachineAlarmStatus</code>
| <code>bool GetMannVsMachineAlarmStatus()</code>
|
|-
| <code>GetOvertimeAllowedForCTF</code>
| <code>bool GetOvertimeAllowedForCTF()</code>
|
|-
| <code>GetRoundState</code>
| <code>int GetRoundState()</code>
| Get current round state. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#ERoundState|Constants.ERoundState]].
|-
| <code>GetStopWatchState</code>
| <code>int GetStopWatchState()</code>
| Get the current stopwatch state. See [[Team_Fortress_2/Scripting/Script_Functions/Constants#EStopwatchState|Constants.EStopwatchState]].
|-
| <code>GetWinningTeam</code>
| <code>int GetWinningTeam()</code>
| Who won!
|-
| <code>HaveStopWatchWinner</code>
| <code>bool HaveStopWatchWinner()</code>
|
|-
| <code>InMatchStartCountdown</code>
| <code>bool InMatchStartCountdown()</code>
| Are we in the pre-match/setup state?
|-
| <code>InOvertime</code>
| <code>bool InOvertime()</code>
| Currently in overtime?
|-
| <code>IsAttackDefenseMode</code>
| <code>bool IsAttackDefenseMode()</code>
|
|-
| <code>IsBirthday</code>
| <code>bool IsBirthday()</code>
| Are we in birthday mode?
|-
| <code>IsCompetitiveMode</code>
| <code>bool IsCompetitiveMode()</code>
| Playing competitive?
|-
| <code>IsDefaultGameMode</code>
| <code>bool IsDefaultGameMode()</code>
| The absence of arena, mvm, tournament mode, etc.
|-
| <code>IsHolidayActive</code>
| <code>bool IsHolidayActive([[Team_Fortress_2/Scripting/Script_Functions/Constants#EHoliday|EHoliday]] ''holiday'')</code>
| Is the given holiday active?
|-
| <code>IsHolidayMap</code>
| <code>bool IsHolidayMap([[Team_Fortress_2/Scripting/Script_Functions/Constants#EHoliday|EHoliday]] ''holiday'')</code>
| Playing a holiday map?
|-
| <code>IsInArenaMode</code>
| <code>bool IsInArenaMode()</code>
| Playing arena mode?
|-
| <code>IsInKothMode</code>
| <code>bool IsInKothMode()</code>
| Playing king of the hill mode?
|-
| <code>IsInMedievalMode</code>
| <code>bool IsInMedievalMode()</code>
| Playing medieval mode?
|-
| <code>IsInWaitingForPlayers</code>
| <code>bool IsInWaitingForPlayers()</code>
| Are we waiting for some stragglers?
|-
| <code>IsMannVsMachineMode</code>
| <code>bool IsMannVsMachineMode()</code>
| Playing MvM? Beep boop.
|-
| <code>IsMannVsMachineRespecEnabled</code>
| <code>bool IsMannVsMachineRespecEnabled()</code>
| Are players allowed to refund their upgrades?
|-
| <code>IsMatchTypeCasual</code>
| <code>bool IsMatchTypeCasual()</code>
| Playing casual?
|-
| <code>IsMatchTypeCompetitive</code>
| <code>bool IsMatchTypeCompetitive()</code>
| Playing competitive?
|-
| <code>IsPasstimeMode</code>
| <code>bool IsPasstimeMode()</code>
| No ball games.
|-
| <code>IsPowerupMode</code>
| <code>bool IsPowerupMode()</code>
| Playing powerup mode? Not compatible with MvM.
|-
| <code>IsPVEModeActive</code>
| <code>bool IsPVEModeActive()</code>
|
|-
| <code>IsQuickBuildTime</code>
| <code>bool IsQuickBuildTime()</code>
| If an engie places a building, will it immediately upgrade? Eg. MvM pre-round etc.
|-
| <code>IsTruceActive</code>
| <code>bool IsTruceActive()</code>
|
|-
| <code>IsUsingGrapplingHook</code>
| <code>bool IsUsingGrapplingHook()</code>
|
|-
| <code>IsUsingSpells</code>
| <code>bool IsUsingSpells()</code>
|
|-
| <code>MapHasMatchSummaryStage</code>
| <code>bool MapHasMatchSummaryStage()</code>
|
|-
| <code>MatchmakingShouldUseStopwatchMode</code>
| <code>bool MatchmakingShouldUseStopwatchMode()</code>
|
|-
| <code>PlayerReadyStatus_ArePlayersOnTeamReady</code>
| <code>bool PlayerReadyStatus_ArePlayersOnTeamReady([[Team_Fortress_2/Scripting/Script_Functions/Constants#ETFTeam|ETFTeam]] ''team'')</code>
|
|-
| <code>PlayerReadyStatus_HaveMinPlayersToEnable</code>
| <code>bool PlayerReadyStatus_HaveMinPlayersToEnable()</code>
|
|-
| <code>PlayerReadyStatus_ResetState</code>
| <code>void PlayerReadyStatus_ResetState()</code>
|
|-
| <code>PlayersAreOnMatchSummaryStage</code>
| <code>bool PlayersAreOnMatchSummaryStage()</code>
|
|-
| <code>PointsMayBeCaptured</code>
| <code>bool PointsMayBeCaptured()</code>
| Are points able to be captured?
|-
| <code>SetGravityMultiplier</code>
| <code>void SetGravityMultiplier(float ''multiplier'')</code>
|
|-
| <code>SetMannVsMachineAlarmStatus</code>
| <code>void SetMannVsMachineAlarmStatus(bool ''status'')</code>
|
|-
| <code>SetOvertimeAllowedForCTF</code>
| <code>void SetOvertimeAllowedForCTF(bool ''state'')</code>
|
|-
| <code>SetPlayersInHell</code>
| <code>void SetPlayersInHell(bool ''state'')</code>
|
|-
| <code>SetUsingSpells</code>
| <code>void SetUsingSpells(bool ''state'')</code>
|
|-
| <code>UsePlayerReadyStatusMode</code>
| <code>bool UsePlayerReadyStatusMode()</code>
|
|}
 
=== Printing and Drawing ===
Functions for printing out messages or drawing elements in the world, mostly for debugging reasons.
{{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.}}
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>ClientPrint</code>
| <code>void ClientPrint(CTFPlayer ''player'', [[Team_Fortress_2/Scripting/Script_Functions/Constants#EHudNotify|EHudNotify]] ''destination'', string ''message'')</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 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>DebugDrawBox</code>
| <code>void DebugDrawBox(Vector ''origin'', Vector ''min'', Vector ''max'', int ''r'', int ''g'', int ''b'', int ''alpha'', float ''duration'')</code>
| Draw a debug overlay box.
|-
| <code>DebugDrawBoxAngles</code>
| <code>void DebugDrawBoxAngles(Vector ''origin'', Vector ''min'', Vector ''max'', QAngle ''direction'', Vector ''rgb'', int ''alpha'', float ''duration'')</code>
| Draw a debug oriented box.
|-
| <code>DebugDrawBoxDirection</code>
| <code>void DebugDrawBoxDirection(Vector ''center'', Vector ''min'', Vector ''max'', Vector ''forward'', Vector ''rgb'', float ''alpha'', float ''duration'')</code>
| Draw a debug forward box.
|-
| <code>DebugDrawCircle</code>
| <code>void DebugDrawCircle(Vector ''center'', Vector ''rgb'', float ''alpha'', float ''radius'', bool ''ztest'', float ''duration'')</code>
| Draw a debug circle.
|-
| <code>DebugDrawClear</code>
| <code>void DebugDrawClear()</code>
| Try to clear all the debug overlay info.
|-
| <code>DebugDrawLine</code>
| <code>void DebugDrawLine(Vector ''start'', Vector ''end'', int ''red'', int ''green'', int ''blue', bool ''z_test'', float ''time'')</code>
| Draw a debug overlay line.
|-
| <code>DebugDrawLine_vCol</code>
| <code>void DebugDrawLine_vCol(Vector ''start'', Vector ''end'', Vector ''rgb'', bool ''ztest'', float ''duration'')</code>
| Draw a debug line using color vec.
|-
| <code>DebugDrawScreenTextLine</code>
| <code>void DebugDrawScreenTextLine(float ''x'', float ''y'', int ''line_offset'', string ''text'', int ''r'', int ''g'', int ''b'', int ''a'', float ''duration'')</code>
| Draw text with a line offset.
|-
| <code>DebugDrawText</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>__DumpScope</code>
| <code>void __DumpScope(int ''indentation'', table ''scope'')</code>
| 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>DumpObject</code>
| <code>void DumpObject(handle ''object'')</code>
| Dumps information about a class or instance.
|-
| <code>Msg</code>
| <code>void Msg(string ''message'')</code>
| Prints message to console without any line feed after.
|-
| <code>printf</code>
| <code>void printf(string ''format'', args...)</code>
| Prints message to console with C style formatting. The line feed is not included.
|-
| <code>printl</code>
| <code>void printl(string ''message'')</code>
| Prints message to console with a line feed after.
|-
| <code>realPrint</code>
| <code>void realPrint(string ''message'')</code>
| Identical to print. print seems to be a wrapper for this.
|-
| <code>Say</code>
| <code>void Say(CTFPlayer ''player'', string ''message'', bool ''team_only'') </code>
| Calling this will have the specified player send the message to chat, either to team_only (true) or to everyone.
|-
| <code>ShowMessage</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.
|}
 
=== Squirrel Standard Library ===
 
{{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].
 
==== Global ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>assert</code>
| <code>assert(bool ''exp'')</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>).
|-
| <code>callee</code>
| <code>function callee()</code>
| Returns the currently running closure.
|-
| <code>castf2i</code>
| <code>int castf2i(float ''value'')</code>
| 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>casti2f</code>
| <code>float casti2f(int ''value'')</code>
| 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>collectgarbage</code>
| <code>int collectgarbage()</code>
| Runs the garbage collector and returns the number of reference cycles found(and deleted) This function only works on garbage collector builds.
|-
| <code>compilestring</code>
| <code>any compilestring(string ''string'', string ''buffer_name'' = null)</code>
| Compiles a string containing a squirrel script into a function and returns it.
|-
| <code>dummy</code>
| <code>dummy()</code>
|
|-
| <code>enabledebuginfo</code>
| <code>void enabledebuginfo(any ''enable'')</code>
| Enable/disable the debug line information generation at compile time. enable != null enables . enable == null disables.
|-
| <code>error</code>
| <code>void error(string ''x'')</code>
| Prints x in the standard error output .
|-
| <code>getconsttable</code>
| <code>table getconsttable()</code>
| Returns the const table of the VM.
|-
| <code>getroottable</code>
| <code>table getroottable()</code>
| Returns the root table of the VM.
|-
| <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.
{{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>print</code>
| <code>void print(string ''message'')</code>
| Prints the given parameter but with no newline unlike <code>printl()</code>.
|-
| <code>resurrectunreachable</code>
| <code>array resurrectunreachable()</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.
|-
| <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>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
|}
 
==== Math ====
 
{{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%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>abs</code>
| <code>int abs(float ''x'')</code>
| Returns <nowiki>|x|</nowiki> as integer unlike <code>fabs()</code>.
|-
| <code>acos</code>
| <code>float acos(float ''x'')</code>
| Returns cos<sup>-1</sup>(x), -1 ≤ x ≤ 1.
|-
| <code>asin</code>
| <code>float asin(float ''x'')</code>
| 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>ceil</code>
| <code>int ceil(float ''x'')</code>
| Returns the smallest integer that is ≥ x.
|-
| <code>cos</code>
| <code>float cos(float ''x'')</code>
| Returns cos(x).
|-
| <code>exp</code>
| <code>float exp(float ''x'')</code>
| Returns exp(x) = e<sup>x</sup>.
|-
| <code>fabs</code>
| <code>float fabs(float ''x'')</code>
| Returns <nowiki>|x|</nowiki> as float unlike <code>abs()</code>.
|-
| <code>floor</code>
| <code>int floor(float ''x'')</code>
| Returns the largest integer that is ≤ x.
|-
| <code>log</code>
| <code>float log(float ''x'')</code>
| Returns log<sub>e</sub>(x) = ln(x).
|-
| <code>log10</code>
| <code>float log10(float ''x'')</code>
| Returns log<sub>10</sub>(x).
|-
| <code>pow</code>
| <code>float pow(float ''x'', float ''y'')</code>
| Returns x<sup>y</sup>.
|-
| <code>rand</code>
| <code>int rand()</code>
| 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>sin</code>
| <code>float sin(float ''x'')</code>
| Returns sin(x).
|-
| <code>sqrt</code>
| <code>float sqrt(float ''x'')</code>
| Returns the square root of x.
|-
| <code>srand</code>
| <code>void srand(int ''seed'')</code>
| Sets the starting point for generating a series of pseudorandom integers.
|-
| <code>tan</code>
| <code>float tan(float ''x'')</code>
| Returns tan(x)
|}
 
==== Integer ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>tofloat</code>
| <code>float tofloat()</code>
| Converts the integer to float and returns it.
|-
| <code>tostring</code>
| <code>string tostring()</code>
| Converts the integer to string and returns it.
|-
| <code>tochar</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>tointeger</code>
| <code>int tointeger()</code>
| Converts the float to integer and returns it.
|-
| <code>tostring</code>
| <code>string tostring()</code>
| Converts the integer to string and returns it.
|-
| <code>tochar</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>tofloat</code>
| <code>float tofloat()</code>
| Returns <code>1.0</code> for true <code>0.0</code> for false.
|-
| <code>tointeger</code>
| <code>int tointeger()</code>
| Returns <code>1</code> for true <code>0</code> for false.
|-
| <code>tostring</code>
| <code>string tostring()</code>
| 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. <code>str.slice(0, 5)</code>.
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>find</code>
| <code>int find(string ''search_string'', int ''start_index'' = 0)</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>len</code>
| <code>int len()</code>
| Returns the length of the string, ie. the number of characters it comprises.
|-
| <code>slice</code>
| <code>string slice(int ''start_index'', int ''end_index'' = null)</code>
| 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>tofloat</code>
| <code>float tofloat()</code>
| Returns float value represented by the string. Must only contain numeric characters and/or plus and minus symbols. An exception is thrown otherwise.
|-
| <code>tointeger</code>
| <code>int tointeger(int ''base'' = 10)</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.
|-
| <code>tolower</code>
| <code>string tolower()</code>
| Returns a new string with all upper-case characters converted to lower-case.
|-
| <code>toupper</code>
| <code>string toupper()</code>
| 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>endswith</code>
| <code>bool endswith(string ''str'', string ''cmp'')</code>
| Returns true if the end of the string matches the comparison string.
|-
| <code>escape</code>
| <code>string escape(string ''str'')</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>format</code>
| <code>string format(string ''format'', args...)</code>
| Returns a [[w:printf format string|formatted string]]. Same rules as the standard C functions (except * is not supported).
|-
| <code>lstrip</code>
| <code>string lstrip(string ''str'')</code>
| Removes whitespace at the beginning of the given string.
|-
| <code>rstrip</code>
| <code>string rstrip(string ''str'')</code>
| Removes whitespace at the end of the given string.
|-
| <code>split</code>
| <code>array split(string ''str'', string ''separator'', bool ''skip_empty'' = false)</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. 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>startswith</code>
| <code>bool startswith(string ''str'', string ''cmp'')</code>
| Returns true if the beginning of the string matches the comparison string.
|-
| <code>strip</code>
| <code>string strip(string ''str'')</code>
| Removes whitespace at the beginning and end of the given string
|}
 
==== Array ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>array</code>
| <code>array(int ''length'', any ''fill'' = null)</code>
| 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>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>
| 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>pop</code>
| <code>any pop()</code>
| Returns and removes the value at the end of the array.
|-
| <code>push</code>
| <code>void push(any ''item'')</code>
| Adds an item to the end of an array.
|-
| <code>reduce</code>
| <code>any reduce(function<pre_value, current_value> ''func'', any ''init'' = null)</code>
| 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>remove</code>
| <code>any remove(int ''index'')</code>
| Returns and removes an array item at a specified index.
|-
| <code>resize</code>
| <code>void resize(int ''new_size'', any ''fill'' = null)</code>
| Increases or decreases the size of an array. In case of increasing fills the new spots with ''fill'' parameter.
|-
| <code>reverse</code>
| <code>void reverse()</code>
| Reverses the order of the elements in an array.
|-
| <code>slice</code>
| <code>array slice(int ''start_index'', int ''end_index'' = null)</code>
| 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>sort</code>
| <code>void sort(function<a, b> ''compare'' = null)</code>
| 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>top</code>
| <code>any top()</code>
| Returns the value at the end of an array.
|-
| <code>tostring</code>
| <code>string tostring()</code>
| Returns the string "(array : ''pointer'')"
|}
 
==== Table ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function
! Signature
! Description
|-
| <code>clear</code>
| <code>void clear()</code>
| Removes all of the items from a table.
|-
| <code>filter</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>getdelegate</code>
| <code>table getdelegate()</code>
| Returns a table's delegate.
|-
| <code>keys</code>
| <code>array keys()</code>
| Returns an array containing all the keys of the table slots.
|-
| <code>len</code>
| <code>int len()</code>
| Returns the length of the table, ie. the number of entries it has.
|-
| <code>rawdelete</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>rawget</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 table/class/handle without employing delegation.
|-
| <code>rawset</code>
| <code>table rawset(any ''key'', any ''value'')</code>
| Sets the value of the specified key without employing delegation. Returns table itself.
|-
| <code>setdelegate</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>values</code>
| <code>array values()</code>
| Returns an array containing all the values of the table slots.
|-
| <code>tostring</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>acall</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>bindenv</code>
| <code>function bindenv(table ''environment'')</code>
| Clones the target function and binds it to a specified context object.
|-
| <code>call</code>
| <code>any call(table ''environment'', any ''args''...)</code>
| Calls the function with a non-default context object.
|-
| <code>getinfos</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>getroot</code>
| <code>table getroot()</code>
| Returns the root table of the closure.
|-
| <code>pacall</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>pcall</code>
| <code>any pcall(table ''environment'', any ''args''...)</code>
| Calls the function with a non-default context object, bypassing Squirrel error callbacks.
|-
| <code>setroot</code>
| <code>void setroot(table ''root'')</code>
| Sets the root table of a closure.
|-
| <code>tostring</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>rawin</code>
| <code>bool rawin(any ''key'')</code>
| Checks for the presence of the specified key in the class without employing delegation.
|-
| <code>rawnewmember</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>rawset</code>
| <code>class rawset(any ''key'', any ''value'')</code>
| Sets the value of the specified key without employing delegation. Returns the class itself.
|-
| <code>setattributes</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>tostring</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>getclass</code>
| <code>class getclass()</code>
| Returns the class that created the instance.
|-
| <code>rawget</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>
|
|}
|}
=== Squirrel Standard Library ===
{{todo}}


== See also ==
== See also ==
Line 2,592: Line 6,408:
* [[VScript Fundamentals]]
* [[VScript Fundamentals]]
* {{sq}} [[Squirrel]]
* {{sq}} [[Squirrel]]
* {{tf2}} [[TF2 Vscript Examples|VScript Examples]]
* {{tf2}} [[TF2 VScript Examples|VScript Examples]]
* {{csgo}} [[CSGO Vscript Examples|VScript Examples (CSGO)]]
* {{src13}} [[Source SDK Base 2013/Scripting/VScript Examples|List of Source SDK Base 2013 VScript Examples]]
* {{l4d2}} [[List of L4D2 Script Functions]]
* {{csgo}} [[List of CS:GO Script Functions]]
* {{l4d2}} [[Left 4 Dead 2/Script Functions|List of L4D2 Script Functions]]
* {{portal2}} [[List of Portal 2 Script Functions]]
* {{portal2}} [[List of Portal 2 Script Functions]]
 
* {{asrd}} [[List of Reactive Drop Script Functions|List of AS:RD Script Functions]]
[[Category:Team Fortress 2]]
* [[List of Script Libraries]]
[[Category:VScript functions]]
[[Category:Scripting]]
[[Category:Scripting]]

Latest revision as of 16:25, 7 September 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: 32767

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