Left 4 Dead 2/Scripting/Script Functions: Difference between revisions

From Valve Developer Community
Jump to navigation Jump to search
m (typo)
m (→‎Methods: __KeyValueFromFloat warning should be enough)
 
(115 intermediate revisions by 19 users not shown)
Line 1: Line 1:
{{lang|List of L4D2 Script Functions}}
{{LanguageBar}}
{{toc-right}}{{sq}} This list contains engine-related Squirrel variables, functions, and constants available for {{l4d2}} [[L4D2_Vscripts| Left 4 Dead 2 VScripts]].
{{toc-right}}
Some can be printed in-game with the <code>script_help</code> command when the game is run in developer mode with the <code>-dev</code> or <code>-allowdebug</code> parameters. Others have been found from data mining, for example with <code>script g_ModeScript.DeepPrintTable(getroottable())</code>, and from the [[L4D2_EMS|Expanded Mutation System documentation]].


For functions and parameters related to the<code>DirectorOptions</code>table, see the [[L4D2 Director Scripts]] page.
{{sq}} This list contains engine-related Squirrel variables, functions, and constants available for {{l4d2}} [[L4D2_Vscripts| Left 4 Dead 2 VScripts]].
Some can be printed in-game with the {{Code|script_help}} command when the game is run in developer mode with the {{Code|-dev}} or {{Code|-allowdebug}} parameters. Others have been found from data mining, for example with {{Code|script g_ModeScript.DeepPrintTable(getroottable())}}, and from the [[L4D2_EMS|Expanded Mutation System documentation]].


== Variables ==
For functions and parameters related to the{{Code|DirectorOptions}}table, see the [[L4D2 Director Scripts]] page.


== Instances ==
{| class="standard-table"  
{| class="standard-table"  
!Instance
! Name !! Type !! Description
!Type
|-
!Description
| <kbd>Convars</kbd> || <kbd>{{↓|Convars}}</kbd>
| Provides an interface to read and change the values of console variables.
|-
| <kbd>Director</kbd> || <kbd>{{↓|CDirector}}</kbd>
| Provides a limited interface to the Director.
|-
|-
|<code>Convars</code>
| <kbd>Entities</kbd> || <kbd>{{↓|CEntities}}</kbd>
|<code>[[#Convars|Convars]]</code>
| Allows searching of currently-spawned entities.
|Provides an interface to read and change the values of console variables.
|-
|-
|<code>Director</code>
| <kbd>EntityOutputs</kbd> || <kbd>{{↓|CScriptEntityOutputs}}</kbd>
|<code>[[#CDirector|CDirector]]</code>
| Allows reading and changing of entities' output data.
|Provides a limited interface to the Director.
|-
| <kbd>NavMesh</kbd> || <kbd>{{↓|CNavMesh}}</kbd>
| An interface to the Navigation Mesh.
|-
| <kbd>NetProps</kbd> || <kbd>{{↓|CNetPropManager}}</kbd>
| Allows reading and updating the network properties of an entity.
|-
| <kbd>ResponseCriteria</kbd> || <kbd>{{↓|CScriptResponseCriteria}}</kbd>
| Allows reading the response criteria of an entity.
|}
 
== Script Scopes ==
{| class="standard-table"
! Name !! Type !! Description
|-
|-
|<code>DirectorScript</code>
| <kbd>DirectorScript</kbd> || table
|table
| Script scope for [[L4D2_Director_Scripts|Director scripts]]. Contains the active [[L4D2_Director_Scripts#DirectorOptions|DirectorOptions]] table.
| Script scope for [[L4D2_Director_Scripts|Director scripts]]. Contains the active [[L4D2_Director_Scripts#DirectorOptions|DirectorOptions]] table.
|-
|-
|<code>Documentation</code>
| <kbd>g_ClearoutTable</kbd> || table (<kbd>null</kbd>)
|table
| NONE
| Contains the printed strings from the <code>script_help</code> command.
|-
|-
|<code>Entities</code>
| <kbd>g_MapScript</kbd> || table
|<code>[[#CEntities|CEntities]]</code>
| Script scope of map-specific vscripts, which also contains utilty functions.
|Provides access to currently spawned entities.
|-
|-
|<code>EntityOutputs</code>
| <kbd>g_ModeScript</kbd> || table
|<code>[[#CScriptEntityOutputs|CScriptEntityOutputs]]</code>
| Script scope of mode-specific vscripts like mutations. This scope also has the {{Code|g_MapScript}} scope as its environment.
|Allows manipulation of entity output data.
|-
|-
|<code>g_ClearoutTable</code>
| <kbd>g_RoundState</kbd> || table
|table (<code>null</code>)
| Scope of the start box used in the Holdout or Dash mutation.
|  
|-
|-
|<code>g_MapScript</code>
| <kbd>[[#Response Rules|g_rr ↓]]</kbd> || table
|table
| An interface to the Response System.
| Script scope for map specific vscripts. It also contains a lot of utility functions.
|}
 
== Variables ==
{| class="standard-table"
! Name !! Type !! Description
|-
|-
|<code>g_ModeScript</code>
| <kbd>Documentation</kbd> || table
|table
| Contains the printed strings from the <kbd>script_help</kbd> command.
| Script scope for mode specific vscripts. Only fully available in Scripted Mode.
|-
|-
|<code>g_RoundState</code>
| <kbd>GameEventCallbacks</kbd> || table
|table
| Table of registered game event callbacks.
|  
|-
|-
|<code>g_rr</code>
| <kbd>print_indent</kbd> || integer
|table
| Spaces to indent prints by except ones from {{Code|realPrint}}. Defaults to 0.
|  
|-
|-
|<code>NavMesh</code>
| <kbd>_PublishedHelp</kbd> || table
|<code>[[#CNavMesh|CNavMesh]]</code>
| NONE
|Provides a method to unblock the rescue vehicle.
|-
|-
|<code>NetProps</code>
| <kbd>ScriptEventCallbacks</kbd> || table
|<code>[[#CNetPropManager|CNetPropManager]]</code>
| Table of registered script event callbacks.
|Allows reading and updating the network properties of an entity.
|-
|-
|<code>print_indent</code>
|}
|integer
 
|
=== Script Debug ===
{| class = "standard-table"
! Name !! Type !! Value
|-
|-
|<code>_PublishedHelp</code>
| <kbd>ScriptDebugDefaultWatchColor</kbd> || array
|table
| [0, 192, 0]
|  
|-
|-
|<code>ResponseCriteria</code>
| <kbd>ScriptDebugDrawTextEnabled</kbd> || bool
|<code>[[#CScriptResponseCriteria|CScriptResponseCriteria]]</code>
| true
|Allows reading the response criteria of an entity.
|-
|-
|<code>ScriptDebugTraceAllOn</code>
| <kbd>ScriptDebugDrawWatchesEnabled</kbd> || bool
|bool
| true
|  
|-
|-
|<code>ScriptDebugTraces</code>
| <kbd>ScriptDebugInDebugDraw</kbd> || bool
|table
| false
|  
|-
|-
|<code>ScriptDebugText</code>
| <kbd>ScriptDebugText</kbd> || array
|array
| NONE
|  
|-
|-
|<code>ScriptDebugTextFilters</code>
| <kbd>ScriptDebugTextIndent</kbd> || integer
|table
| 0
|  
|-
|-
|<code>ScriptDebugTextIndent</code>
| <kbd>ScriptDebugTextFilters</kbd> || table
|integer
| NONE
|  
|-
|-
|<code>ScriptDebugWatches</code>
| <kbd>ScriptDebugTraces</kbd> || table
|array
| NONE
|  
|-
|-
|<code>ScriptEventCallbacks</code>
| <kbd>ScriptDebugTraceAllOn</kbd> || bool
|table
| false
|  
|-
|-
| <kbd>ScriptDebugWatches</kbd> || array
| NONE
|}
|}


== Constants ==
== Constants ==
A [https://en.wikipedia.org/wiki/Constant_(computer_programming) constant] is a variable whose value cannot be altered during program runtime, usually to avoid [https://en.wikipedia.org/wiki/Magic_number_(programming) magic numbers] by giving them self-documenting names.
{| class="standard-table"
{| class="standard-table"
!Instance
! Instance !! Type !! Value
!Type
!Value
|-
|-
|<code>_charsize_</code>
| <kbd>_charsize_</kbd> || integer
|integer
| 1
|1
|-
|-
|<code>_floatsize_</code>
| <kbd>_floatsize_</kbd> || integer
|integer
| 4
|4
|-
|-
|<code>_intsize_</code>
| <kbd>_intsize_</kbd> || integer
|integer
| 4
|4
|-
|-
|<code>_version_</code>
| <kbd>_version_</kbd> || string
|string
| "Squirrel 3.0.4 stable"
| "Squirrel 3.0.4 Stable"
|-
|-
|<code>_versionnumber_</code>
| <kbd>_versionnumber_</kbd> || integer
|integer
| 304
| 304
|-
|-
|<code>RAND_MAX</code>
| <kbd>RAND_MAX</kbd> || integer
|integer
| 32767
|32767
|-
|-
|<code>SPAWN_FLAGS</code>
| <kbd>SPAWN_FLAGS</kbd> || table
|table
|<syntaxhighlight lang=js>
|<syntaxhighlight lang=js>
SPAWN = 1
SPAWN = 1
Line 143: Line 142:
TARGETSPAWN = 4</syntaxhighlight>
TARGETSPAWN = 4</syntaxhighlight>
|-
|-
|<code>PI</code>
| <kbd>PI</kbd> || float
|float
| 3.14159
|
|}
|}


<!-- These line breaks were always here, and are to put the section at the bottom of the TOC table -->
<!-- These line breaks were always here, and are to put the section at the bottom of the TOC table -->
<!-- 27 line breaks here, currently -->
<!-- 12 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><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br>


== Classes ==
== Classes ==
=== CBaseEntity ===
{{↑|toc}}
Extended by:
{{↓|CBaseAnimating}}
{{↓|CBaseTrigger}}
{{↓|CEnvEntityMaker}}
{{↓|CInfoItemPosition}}
{{↓|CPointTemplate}}
{{↓|CPointScriptTemplate}}
{{↓|CPointScriptUseTarget}}
{{note|Entity vscript classes are created when script handle for an entity of such type is created for the first time (i.e. class CInfoItemPosition won't exist or have help strings shown by <code>script_help</code> until script handle for some <kbd>info_item_position</kbd> entity was made, for example by SpawnEntityFromTable, Entities.FindByClassname, etc.)}}


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


All script handles in-game are accessible from the<code>[[#CEntities|Entities]]</code>instance. [[Entity Scripts]] can use<code>self</code>to access their own script handle.
An entity's own handle are accessed with:
* <kbd>[[#CEntities|Entities ]]</kbd> instance.
* [[Entity Scripts]] only - The <kbd>self</kbd> keyword.


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>__KeyValueFromInt</code>
| <kbd>__KeyValueFromInt</kbd><br><kbd>__KeyValueFromString</kbd><br><kbd>__KeyValueFromVector</kbd> || <kbd>bool __KeyValueFromInt(string ''key'', int ''value'')</kbd><br><kbd>bool __KeyValueFromString(string ''key'', string ''value'')</kbd><br><kbd>bool __KeyValueFromVector(string ''key'', Vector ''value'')</kbd>
| <code>bool __KeyValueFromInt(string ''key'', int ''value'')</code>
| Sets an entity [[keyvalue]] from a specific data type. Returns true if successfully set, false if it the key does not exist.
| Sets an entity [[keyvalue]] from an integer. This simply changes the value without executing any code that may be needed for the entity to process the keyvalue, so there may be unintended side effects.
 
|-
This simply changes the value without executing any other code that may be needed for the entity to fully process the keyvalue, such as code for updating the entity's internal network state. This can create unexpected side effects on already-spawned entities such as visual changes being delayed for clients.
| <code>__KeyValueFromFloat</code>
{{tip|Use [[#CNetPropManager|Netprops ↓]] and update the keyvalue's corresponding prop instead, as this correctly updates the networking state and results in an immediate update.}}
| <code>bool __KeyValueFromFloat(string ''key'', float ''value'')</code>
{{warning|__KeyValueFromFloat doesn't exist}}
| Sets an entity keyvalue from a float. This simply changes the value without executing any code that may be needed for the entity to process the keyvalue, so there may be unintended side effects.
|-
| <code>__KeyValueFromString</code>
| <code>bool __KeyValueFromString(string ''key'', string ''value'')</code>
| Sets an entity Keyvalue from a string. This simply changes the value without executing any code that may be needed for the entity to process the Keyvalue, so there may be unintended side effects.
|-
| <code>__KeyValueFromVector</code>
| <code>bool __KeyValueFromVector(string ''key'', Vector ''value'')</code>
| Sets an entity Keyvalue from a [[#Vector|Vector]]. This simply changes the value without executing any code that may be needed for the entity to process the Keyvalue, so there may be unintended side effects.
|-
|-
| <code>ApplyAbsVelocityImpulse</code>
| <kbd>ApplyAbsVelocityImpulse</kbd> || <kbd>void ApplyAbsVelocityImpulse(Vector ''impulse'')</kbd>
| <code>void ApplyAbsVelocityImpulse(Vector ''impulse'')</code>
| Apply a Velocity Impulse as a world space impulse vector.
| Apply a Velocity Impulse as a world space impulse vector.
|-
|-
| <code>ApplyLocalAngularVelocityImpulse</code>
| <kbd>ApplyLocalAngularVelocityImpulse</kbd> || <kbd>void ApplyLocalAngularVelocityImpulse(Vector ''impulse'')</kbd>
| <code>void ApplyLocalAngularVelocityImpulse(Vector ''impulse'')</code>
| 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.
| 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>ConnectOutput</code>
| <kbd>ConnectOutput</kbd> || <kbd>void ConnectOutput(string ''output'', string ''function'')</kbd>
| <code>void ConnectOutput(string ''output'', string ''function'')</code>
| Adds an I/O connection that will call the named function when the specified output fires.
| Adds an I/O connection that will call the named function when the specified output fires.
|-
|-
| <code>DisconnectOutput</code>
| <kbd>DisconnectOutput</kbd> || <kbd>void DisconnectOutput(string ''output'', string ''function'')</kbd>
| <code>void DisconnectOutput(string ''output'', string ''function'')</code>
| Removes a connected script function from an I/O event.
| Removes a connected script function from an I/O event.
|-
|-
| <code>FirstMoveChild</code>
| <kbd>FirstMoveChild</kbd> || <kbd>handle FirstMoveChild()</kbd>
| <code>handle FirstMoveChild()</code>
| Returns the first entity parented to this one. Needs to be used in combination with NextMovePeer to iterate over all children.
| Returns the first entity parented to this one.
{{tip|Example usage: <source lang=js>for (local child = entity.FirstMoveChild(); child != null; child = child.NextMovePeer())</source>}}
|-
|-
| <code>GetAngles</code>
| <kbd>GetAngles</kbd> || <kbd>QAngle GetAngles()</kbd>
| <code>QAngle GetAngles()</code>
| Returns the orientation of the entity in the world.
| Returns the orientation of the entity in the world.
|-
|-
| <code>GetBaseVelocity</code>
| <kbd>GetBaseVelocity</kbd> || <kbd>Vector GetBaseVelocity()</kbd>
| <code>Vector GetBaseVelocity()</code>
| 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. <!-- Thanks! -->
| 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. <!-- Thanks! -->
|-
|-
| <code>GetCenter</code>
| <kbd>GetCenter</kbd> || <kbd>Vector GetCenter()</kbd>
| <code>Vector GetCenter()</code>
| Get world space center of object - absolute coords.
| Get world space center of object - absolute coords.
|-
|-
| <code>GetClassname</code>
| <kbd>GetClassname</kbd> || <kbd>string GetClassname()</kbd>
| <code>string GetClassname()</code>
| Returns the entity class. This includes<kbd>player</kbd>and<kbd>infected</kbd>.
| Returns the entity class. This includes<code>player</code>and<code>infected</code>.
|-
|-
| <code>GetContext</code>
| <kbd>GetContext</kbd> || <kbd>''variable'' GetContext(string ''name'')</kbd>
| <code>''variable'' GetContext(string ''name'')</code>
| Looks up a response context and returns it if available. May return string, float, or null (if the context isn't found).<br>{{bug*|Always returns null for contexts with numeric value}}{{bug*|Can return value for expired contexts}} <!-- I hate this shitty function -->
| Looks up a response context and returns it if available. May return string, float, or null (if the context isn't found).
|-
|-
| <code>GetEntityHandle</code>
| <kbd>GetEntityHandle</kbd> || <kbd>''unknown'' GetEntityHandle()</kbd>
| <code>''unknown'' GetEntityHandle()</code>
| Get a C++ [[CHandle|EHANDLE]] reference of the entity. This is an opaque type not directly usable by Squirrel, not a normal script handle. Only necessary for [[#CPointScriptUseTarget|CPointScriptUseTarget functions. ]]
| Get a C++ [[CHandle|EHANDLE]] reference of the entity. This is an opaque type not directly usable by Squirrel, not a normal script handle. Only necessary for [[List of L4D2 Script Functions#CPointScriptUseTarget|CPointScriptUseTarget functions.]]
|-
|-
| <code>GetEntityIndex</code>
| <kbd>GetEntityIndex</kbd> || <kbd>int GetEntityIndex()</kbd>
| <code>int GetEntityIndex()</code>
| Returns the entity index. This is the same type of index used in most game events.
| Returns the entity index. This is the same type of index used in most game events.
|-
|-
| <code>GetForwardVector</code>
| <kbd>GetForwardVector</kbd> || <kbd>Vector GetForwardVector()</kbd>
| <code>Vector GetForwardVector()</code>
| Get the forward vector of the entity.
| Get the forward vector of the entity.
|-
|-
| <code>GetHealth</code>
| <kbd>GetHealth</kbd> || <kbd>int GetHealth()</kbd>
| <code>int GetHealth()</code>
| Returns the current health of the entity (does not include survivor temporary health).
| Returns the current health of the entity (does not include survivor temporary health).
|-
|-
| <code>GetLocalAngles</code>
| <kbd>GetLocalAngles</kbd> || <kbd>QAngle GetLocalAngles()</kbd>
| <code>QAngle GetLocalAngles()</code>
| Returns the orientation of the entity relative to it's parent or attachment point.
| Returns the orientation of the entity relative to it's parent or attachment point.
|-
|-
| <code>GetLocalAngularVelocity</code>
| <kbd>GetLocalAngularVelocity</kbd> || <kbd>QAngle GetLocalAngularVelocity()</kbd>
| <code>QAngle GetLocalAngularVelocity()</code>
| Maybe local angvel
| Maybe local angvel
|-
|-
| <code>GetLocalOrigin</code>
| <kbd>GetLocalOrigin</kbd> || <kbd>Vector GetLocalOrigin()</kbd>
| <code>Vector GetLocalOrigin()</code>
| Returns the origin of the entity relative to it's parent or attachment point.
| Returns the origin of the entity relative to it's parent or attachment point.
|-
|-
| <code>GetLocalVelocity</code>
| <kbd>GetLocalVelocity</kbd> || <kbd>Vector GetLocalVelocity()</kbd>
| <code>Vector GetLocalVelocity()</code>
| Get Entity relative velocity
| Get Entity relative velocity
|-
|-
| <code>GetMaxHealth</code>
| <kbd>GetMaxHealth</kbd> || <kbd>int GetMaxHealth()</kbd>
| <code>int GetMaxHealth()</code>
| Returns the maximum health of the entity.
| Returns the maximum health of the entity.
|-
|-
| <code>GetModelName</code>
| <kbd>GetModelName</kbd> || <kbd>string GetModelName()</kbd>
| <code>string GetModelName()</code>
| Returns the file name of the model used by the entity (if applicable).
| Returns the file name of the model used by the entity (if applicable).
|-
|-
| <code>GetMoveParent</code>
| <kbd>GetMoveParent</kbd> || <kbd>handle GetMoveParent()</kbd>
| <code>handle GetMoveParent()</code>
| If in hierarchy, retrieves the entity's parent
| If in hierarchy, retrieves the entity's parent
|-
|-
| <code>GetName</code>
| <kbd>GetName</kbd> || <kbd>string GetName()</kbd>
| <code>string GetName()</code>
| Returns the targetname of the entity.
| Returns the targetname of the entity.
|-
|-
| <code>GetOrigin</code>
| <kbd>GetOrigin</kbd> || <kbd>Vector GetOrigin()</kbd>
| <code>Vector GetOrigin()</code>
| Returns the origin of the entity in the world.
| Returns the origin of the entity in the world.
|-
|-
| <code>GetOwnerEntity</code>
| <kbd>GetOwnerEntity</kbd> || <kbd>handle GetOwnerEntity()</kbd>
| <code>handle GetOwnerEntity()</code>
| Get the owner entity, if there is one.
| Get the owner entity, if there is one.
|-
|-
| <code>GetPreTemplateName</code>
| <kbd>GetPreTemplateName</kbd> || <kbd>string GetPreTemplateName()</kbd>
| <code>string GetPreTemplateName()</code>
| Get the entity name stripped of template unique decoration.
| Get the entity name stripped of template unique decoration.
|-
|-
| <code>GetRootMoveParent</code>
| <kbd>GetRootMoveParent</kbd> || <kbd>handle GetRootMoveParent()</kbd>
| <code>handle GetRootMoveParent()</code>
| If in hierarchy, walks up the hierarchy to find the root parent.
| If in hierarchy, walks up the hierarchy to find the root parent.
|-
|-
| <code>GetScriptId</code>
| <kbd>GetScriptId</kbd> || <kbd>string GetScriptId()</kbd>
| <code>string GetScriptId()</code>
| Returns the name of the entity's think function. {{tip|Retrieve the actual script identifier with {{Code|NetProps.GetPropString(ent, "m_iszScriptId")}}}}
| Returns the name of the entity's think function. {{tip|Retrieve the actual script identifier with <code>NetProps.GetPropString(ent, "m_iszScriptId")</code>}}
|-
|-
| <code>GetScriptScope</code>
| <kbd>GetScriptScope</kbd> || <kbd>table GetScriptScope()</kbd>
| <code>table GetScriptScope()</code>
| Retrieve the table storing the Entity Script associated with this entity, null otherwise.
| Retrieve the table storing the Entity Script associated with this entity.
|-
|-
| <code>GetVelocity</code>
| <kbd>GetVelocity</kbd> || <kbd>Vector GetVelocity()</kbd>
| <code>Vector GetVelocity()</code>
| Returns a local velocity Vector.
| Returns a local velocity Vector.
|-
|-
| <code>IsPlayer</code>
| <kbd>IsPlayer</kbd> || <kbd>bool IsPlayer()</kbd>
| <code>bool IsPlayer()</code>
| Does this entity belong to the player class.
| Does this entity belong to the player class.
|-
|-
| <code>IsValid</code>
| <kbd>IsValid</kbd> || <kbd>bool IsValid()</kbd>
| <code>bool IsValid()</code>
| Whether the handle still belongs to an entity that's still valid, could become invalid in cases such as the entity, like a destroyed func_breakable.(?)
| Whether the handle still belongs to an entity that's still valid, could become invalid in cases such as the entity, like a <code>func_breakable</code> being destroyed.
|-
|-
| <code>Kill</code>
| <kbd>Kill</kbd> || <kbd>void Kill()</kbd>
| <code>void Kill()</code>
| Removes the entity.
| Removes the entity.
|-
|-
| <code>NextMovePeer</code>
| <kbd>NextMovePeer</kbd> || <kbd>handle NextMovePeer()</kbd>
| <code>handle NextMovePeer()</code>
| Returns the next child of this entity's parent. Used to continue iteration from FirstMoveChild().
| Returns the next child of this entity's parent. Used to continue iteration from FirstMoveChild().
|-
|-
| <code>OverrideFriction</code>
| <kbd>OverrideFriction</kbd> || <kbd>void OverrideFriction(float ''duration'', float ''friction'')</kbd>
| <code>void OverrideFriction(float ''duration'', float ''friction'')</code>
| Takes duration, value for a temporary override
| Takes duration, value for a temporary override
|-
|-
| <code>PrecacheModel</code>
| <kbd>PrecacheModel</kbd> || <kbd>int PrecacheModel(string ''filename'')</kbd>
| <code>void PrecacheModel(string ''filename'')</code>
| Precache a model after the map has loaded and return index of the model.
|  
|-
|-
| <code>PrecacheScriptSound</code>
| <kbd>PrecacheScriptSound</kbd> || <kbd>void PrecacheScriptSound(string ''soundscript'')</kbd>
| <code>void PrecacheScriptSound(string)</code>
| Precache a sound file, used by the specified soundscript.
| {{TODO|Is this for raw files or soundscripts?}}
|-
|-
| <code>SetAngles</code>
| <kbd>SetAngles</kbd> || <kbd>void SetAngles(QAngle ''direction'')</kbd>
| <code>void SetAngles(QAngle ''direction'')</code>
| Sets the orientation of the entity.  
| Sets the orientation of the entity.  
|-
|-
| <code>SetContext</code>
| <kbd>SetContext</kbd> || <kbd>void SetContext(string ''name'', string ''value'', float ''duration'')</kbd>
| <code>void SetContext(string ''name'', string ''value'', float ''duration'')</code>
| Stores any key/value pair in this entity's dialog contexts. Value must be a string. Will last for duration (set -1 to mean 'forever').
| Stores any key/value pair in this entity's dialog contexts. Value must be a string. Will last for duration (set -1 to mean 'forever').
|-
|-
| <code>SetContextNum</code>
| <kbd>SetContextNum</kbd> || <kbd>void SetContextNum(string ''name'', float ''value'', float ''duration'')</kbd>
| <code>void SetContextNum(string ''name'', float ''value'', float ''duration'')</code>
| Stores any key/value pair in this entity's dialog contexts. Value must be a number (int or float). Will last for duration (set -1 to mean 'forever').
| Stores any key/value pair in this entity's dialog contexts. Value must be a number (int or float). Will last for duration (set -1 to mean 'forever'). {{warning|The context set with this will always return null, when<code>.GetContext()</code>is used to verify.
|-
|-
| <code>SetForwardVector</code>
| <kbd>SetForwardVector</kbd> || <kbd>void SetForwardVector(Vector ''direction'')</kbd>
| <code>void SetForwardVector(Vector ''direction'')</code>
| Set the orientation of the entity to have this forward vector.
| Set the orientation of the entity to have this forward vector.
|-
|-
| <code>SetFriction</code>
| <kbd>SetFriction</kbd> || <kbd>void SetFriction(float ''friction'')</kbd>
| <code>void SetFriction(float ''friction'')</code>
| Set PLAYER friction, ignored for objects.
| Set PLAYER friction, ignored for objects.
|-
|-
| <code>SetGravity</code>
| <kbd>SetGravity</kbd> || <kbd>void SetGravity(float ''gravity'')</kbd>
| <code>void SetGravity(float ''gravity'')</code>
| Set PLAYER gravity, ignored for objects.
| Set PLAYER gravity, ignored for objects.
|-
|-
| <code>SetHealth</code>
| <kbd>SetHealth</kbd> || <kbd>void SetHealth(int ''health'')</kbd>
| <code>void SetHealth(int ''health'')</code>
| Changes the health value of the entity. Does not check whether to kill players.
| Changes the health value of the entity. Does not check whether to kill players.
|-
|-
| <code>SetLocalAngles</code>
| <kbd>SetLocalAngles</kbd> || <kbd>void SetLocalAngles(QAngle ''direction'')</kbd>
| <code>void SetLocalAngles(QAngle ''direction'')</code>
| Sets the entity orientation relative to it's parent or attachment point.
| Sets the entity orientation relative to it's parent or attachment point.
|-
|-
| <code>SetLocalOrigin</code>
| <kbd>SetLocalOrigin</kbd> || <kbd>void SetLocalOrigin(Vector ''position'')</kbd>
| <code>void SetLocalOrigin(Vector ''position'')</code>
| Sets the entity position relative to it's parent or attachment point.
| Sets the entity position relative to it's parent or attachment point.
|-
|-
| <code>SetMaxHealth</code>
| <kbd>SetMaxHealth</kbd> || <kbd>void SetMaxHealth(int ''health'')</kbd>
| <code>void SetMaxHealth(int ''health'')</code>
| Changes the maximum health value of the entity.
| Changes the maximum health value of the entity.
|-
|-
| <code>SetModel</code>
| <kbd>SetModel</kbd> || <kbd>void SetModel(string ''modelName'')</kbd>
| <code>void SetModel(string ''modelName'')</code>
| Changes the model of the entity (if applicable).
| Changes the model of the entity (if applicable).
|-
|-
| <code>SetOrigin</code>
| <kbd>SetOrigin</kbd> || <kbd>void SetOrigin(Vector ''position'')</kbd>
| <code>void SetOrigin(Vector ''position'')</code>
| Sets the world entity position.
| Sets the world entity position.
|-
|-
| <code>SetVelocity</code>
| <kbd>SetVelocity</kbd> || <kbd>void SetVelocity(Vector ''velocity'')</kbd>
| <code>void SetVelocity(Vector ''velocity'')</code>
| Sets the entity velocity.
| Sets the entity velocity.
|-
|-
| <code>TakeDamage</code>
| <kbd>TakeDamage</kbd> || <kbd>void TakeDamage(float ''damage'', int ''damageType'', CBaseEntity ''attacker'')</kbd>
| <code>void TakeDamage(float ''damage'', int ''damageType'', CBaseEntity ''attacker'')</code>
| Damages the entity.
| Damages the entity.
|-
|-
| <code>TakeDamageEx</code>
| <kbd>TakeDamageEx</kbd> || <kbd>void TakeDamageEx(CBaseEntity ''inflictor'', CBaseEntity ''attacker'', CBaseEntity ''weapon'', Vector ''vecDamageForce'', Vector ''vecDamagePosition'', float ''damage'', int ''damageType'')</kbd>
| <code>void TakeDamageEx(CBaseEntity ''inflictor'', CBaseEntity ''attacker'', CBaseEntity ''weapon'', Vector ''vecDamageForce'', Vector ''vecDamagePosition'', float ''damage'', int ''damageType'')</code>
| Damages the entity (extended).
| Damages the entity (extended).
|-
|-
| <code>ValidateScriptScope</code>
| <kbd>ValidateScriptScope</kbd> || <kbd>bool ValidateScriptScope()</kbd>
| <code>bool ValidateScriptScope()</code>
| Ensures an entity has a script scope, if it doesn't have one then one is created. Returns true if created successfully.
| Ensures an entity has a script scope, if it doesn't have one then one is created. Returns true if created successfully.
|}
|}
Line 394: Line 344:


{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>Input[''InputName'']</code>
| <kbd>Input[''InputName'']</kbd> || <kbd>bool Input[''InputName'']()</kbd>
| <code>bool Input[''InputName'']()</code>
| Called when the entity receives an I/O input that matches the function's name. The name that follows after <kbd>Input</kbd> must match the casing, i.e. {{Code|InputFireUser1}} will catch any "FireUser1" inputs but not "fireuser1" inputs from the <kbd>[[ent_fire]]</kbd> command.
| Called when the entity receives an input from the I/O system that matches the function's name. The name of the function needs to be<code>Input</code>followed by the name of the input with the same casing (PascalCase). 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.
Variables {{Code|activator}} and {{Code|caller}} are added to the scope when the function is called. The function also must return a boolean value which controls if the input is allowed to be processed, i.e. returning false cancels the input.
|-
|-
| <code>OnEntText</code>
| <kbd>OnEntText</kbd> || <kbd>string OnEntText()</kbd>
| <code>string OnEntText()</code>
| If ent_text is used on an entity and this function exists, it will be called every tick. Returns a string that gets displayed as part of the ent_text overlay. This is a handy feature for displaying script data on objects when you ent_text the object, or running arbitrary code (such as turning on additional debugging visualizations) is using ent_text. NOTE: ent_text_allow_script 1 must be set in order for this feature to be active.  
| If ent_text is used on an entity and this function exists, it will be called every tick. Returns a string that gets displayed as part of the ent_text overlay. This is a handy feature for displaying script data on objects when you ent_text the object, or running arbitrary code (such as turning on additional debugging visualizations) is using ent_text. NOTE: ent_text_allow_script 1 must be set in order for this feature to be active.  
|-
|-
| <code>OnPostSpawn</code>
| <kbd>OnPostSpawn</kbd> || <kbd>void OnPostSpawn()</kbd>
| <code>void OnPostSpawn()</code>
| Called after the entity spawns, which is after scripts and players have loaded. This could be used to have an entity register itself with a master script, or adjusting the entity parameters in a programmatic way.
| Called after the entity spawns, which is after scripts and players have loaded. This could be used to have an entity register itself with a master script, or adjusting the entity parameters in a programmatic way.
|-
|-
| <code>Precache</code>
| <kbd>Precache</kbd> || <kbd>void Precache()</kbd>
| <code>void Precache()</code>
| Called after the script executes. Can be used to call precache functions for models and sounds on map load.
| Called after the script executes. Can be used to call precache functions for models and sounds on map load.
|}
|}


=== CBaseAnimating ===
=== CBaseAnimating ===
Extends [[#CBaseEntity|CBaseEntity]]
{{↑|toc}}
Extends {{↑|CBaseEntity}}
Extended by:
{{↓|CBaseFlex}}
{{↓|CTerrorWeapon}}


Script handle class for animating entities such as props.
Script handle class for animating entities such as props.
Line 424: Line 372:
==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>FindBodygroupByName</code>
| <kbd>FindBodygroupByName</kbd> || <kbd>int FindBodygroupByName(string ''name'')</kbd>
| <code>int FindBodygroupByName(string ''name'')</code>
| Find a bodygroup ID by name. Returns -1 if the bodygroup does not exist.
| Find a bodygroup ID by name. Returns -1 if the bodygroup does not exist.
|-
|-
| <code>GetAttachmentAngles</code>
| <kbd>GetAttachmentAngles</kbd> || <kbd>QAngle GetAttachmentAngles(int ''ID'')</kbd>
| <code>QAngle GetAttachmentAngles(int ''ID'')</code>
| Get the attachment ID's angles as a QAngle.
| Get the attachment ID's angles as a QAngle.
|-
|-
| <code>GetAttachmentBone</code>
| <kbd>GetAttachmentBone</kbd> || <kbd>int GetAttachmentBone(int ''ID'')</kbd>
| <code>int GetAttachmentBone(int ''ID'')</code>
| Get the attachment ID's parent bone index.
| Get the attachment ID's parent bone index.
|-
|-
| <code>GetAttachmentOrigin</code>
| <kbd>GetAttachmentOrigin</kbd> || <kbd>Vector GetAttachmentOrigin(int ''ID'')</kbd>
| <code>Vector GetAttachmentOrigin(int ''ID'')</code>
| Get the attachment ID's origin as a Vector.
| Get the attachment ID's origin as a Vector.
|-
|-
| <code>GetBodygroup</code>
| <kbd>GetBodygroup</kbd> || <kbd>int GetBodygroup(int ''ID'')</kbd>
| <code>int GetBodygroup(int ''ID'')</code>
| Get the bodygroup value by bodygroup ID.
| Get the bodygroup value by bodygroup ID.
|-
|-
| <code>GetBodygroupName</code>
| <kbd>GetBodygroupName</kbd> || <kbd>string GetBodygroupName(int ''ID'')</kbd>
| <code>string GetBodygroupName(int ''ID'')</code>
| Get the bodygroup ID's name.
| Get the bodygroup ID's name.
|-
|-
| <code>GetBodygroupPartName</code>
| <kbd>GetBodygroupPartName</kbd> || <kbd>string GetBodygroupPartName(int ''group'', int ''part'')</kbd>
| <code>string GetBodygroupPartName(int ''group'', int ''part'')</code>
| Get name by group and part.
| Get name by group and part.
|-
|-
| <code>GetBodygroupName</code>
| <kbd>GetBoneAngles</kbd> || <kbd>QAngle GetBoneAngles(int ''ID'')</kbd>
| <code>string GetBodygroupName(int ''ID'')</code>
| Get the bodygroup ID's name.
|-
| <code>GetBoneAngles</code>
| <code>QAngle GetBoneAngles(int ''ID'')</code>
| Get the bone ID's angles as a QAngle.
| Get the bone ID's angles as a QAngle.
|-
|-
| <code>GetBoneOrigin</code>
| <kbd>GetBoneOrigin</kbd> || <kbd>Vector GetBoneOrigin(int ''ID'')</kbd>
| <code>Vector GetBoneOrigin(int ''ID'')</code>
| Get the bone ID's origin Vector.
| Get the bone ID's origin Vector.
|-
|-
| <code>GetModelScale</code>
| <kbd>GetModelScale</kbd> || <kbd>float GetModelScale()</kbd>
| <code>float GetModelScale()</code>
| Get the model scale.
| Get the model scale.
|-
|-
| <code>GetSequence</code>
| <kbd>GetSequence</kbd> || <kbd>int GetSequence()</kbd>
| <code>int GetSequence()</code>
| Get the currently playing sequence ID.
| Get the currently playing sequence ID.
|-
|-
| <code>GetSequenceActivityName</code>
| <kbd>GetSequenceActivityName</kbd> || <kbd>string GetSequenceActivityName(int ''ID'')</kbd>
| <code>string GetSequenceActivityName(int ''ID'')</code>
| Get the activity name for a sequence by sequence ID.
| Get the activity name for a sequence by sequence ID.
|-
|-
| <code>GetSequenceDuration</code>
| <kbd>GetSequenceDuration</kbd> || <kbd>float GetSequenceDuration(int ''ID'')</kbd>
| <code>float GetSequenceDuration(int ''ID'')</code>
| Get a sequence duration in seconds by sequence ID.
| Get a sequence duration in seconds by sequence ID.
|-
|-
| <code>GetSequenceName</code>
| <kbd>GetSequenceName</kbd> || <kbd>string GetSequenceName(int ''ID'')</kbd>
| <code>string GetSequenceName(int ''ID'')</code>
| Get a sequence name by sequence ID.
| Get a sequence name by sequence ID.
|-
|-
| <code>IsSequenceFinished</code>
| <kbd>IsSequenceFinished</kbd> || <kbd>bool IsSequenceFinished()</kbd>
| <code>bool IsSequenceFinished()</code>
| Returns true if the current sequence has finished playing.
| Returns true if the current sequence has finished playing.
|-
|-
| <code>LookupActivity</code>
| <kbd>LookupActivity</kbd> || <kbd>int LookupActivity(string ''activity'')</kbd>
| <code>int LookupActivity(string ''activity'')</code>
| Get the named activity index. Returns -1 if the activity does not exist.
| Get the named activity index. Returns -1 if the activity does not exist.
|-
|-
| <code>LookupAttachment</code>
| <kbd>LookupAttachment</kbd> || <kbd>int LookupAttachment(string ''name'')</kbd>
| <code>int LookupAttachment(string ''name'')</code>
| Get the named attachment index. Returns 0 if the attachment does not exist.
| Get the named attachment index. Returns 0 if the attachment does not exist.
|-
|-
| <code>LookupBone</code>
| <kbd>LookupBone</kbd> || <kbd>int LookupBone(string ''bone'')</kbd>
| <code>int LookupBone(string ''bone'')</code>
| Get the named bone index. Returns -1 if the bone does not exist.
| Get the named bone index. Returns -1 if the bone does not exist.
|-
|-
| <code>LookupSequence</code>
| <kbd>LookupSequence</kbd> || <kbd>int LookupSequence(string ''name'')</kbd>
| <code>int LookupSequence(string ''name'')</code>
| Looks up a sequence by sequence name or activity name. Returns -1 if the sequence does not exist.
| Looks up a sequence by sequence name or activity name. Returns -1 if the sequence does not exist.
|-
|-
| <code>ResetSequence</code>
| <kbd>ResetSequence</kbd> || <kbd>void ResetSequence(int ''ID'')</kbd>
| <code>void ResetSequence(int ''ID'')</code>
| Reset a sequence by sequence ID. If the ID is different than the current sequence, switch to the new sequence.
| Reset a sequence by sequence ID. If the ID is different than the current sequence, switch to the new sequence.
|-
|-
| <code>SetBodygroup</code>
| <kbd>SetBodygroup</kbd> || <kbd>void SetBodygroup(int ''ID'', int ''value'')</kbd>
| <code>void SetBodygroup(int ''ID'', int ''value'')</code>
| Set the bodygroup by ID.
| Set the bodygroup by ID.
|-
|-
| <code>SetModelScale</code>
| <kbd>SetModelScale</kbd> || <kbd>void SetModelScale(float ''scale'', float ''change_duration'')</kbd>
| <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.
| Changes a model's scale over time. Set the change duration to 0.0 to change the scale instantly.
|-
|-
| <code>SetPoseParameter</code>
| <kbd>SetPoseParameter</kbd> || <kbd>float SetPoseParameter(int ''ID'', float ''value'')</kbd>
| <code>float SetPoseParameter(int ''ID'', float ''value'')</code>
| Sets a pose parameter value. Returns the effective value after clamping or looping.
| Sets a pose parameter value. Returns the effective value after clamping or looping.
|-
|-
| <code>SetSequence</code>
| <kbd>SetSequence</kbd> || <kbd>void SetSequence(int ''ID'')</kbd>
| <code>void SetSequence(int ''ID'')</code>
| Plays a sequence by sequence ID.
| Plays a sequence by sequence ID.
|}
|}


=== CBaseFlex ===
=== CBaseFlex ===
Extends [[#CBaseAnimating|CBaseAnimating]]
{{↑|toc}}
Extends {{↑|CBaseAnimating}}


Animated characters who have vertex flex capability (e.g., facial expressions).
Animated characters who have vertex flex capability (e.g., facial expressions).
Line 536: Line 456:
==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>GetCurrentScene</code>
| <kbd>GetCurrentScene</kbd> || <kbd>handle GetCurrentScene()</kbd>
| <code>handle GetCurrentScene()</code>
| Returns the instance of the oldest active scene entity (if any).
| Returns the instance of the oldest active scene entity (if any).
|-
|-
| <code>GetSceneByIndex</code>
| <kbd>GetSceneByIndex</kbd> || <kbd>handle GetSceneByIndex(int ''index'')</kbd>
| <code>handle GetSceneByIndex(int ''index'')</code>
| Returns the instance of the scene entity at the specified index.
| Returns the instance of the scene entity at the specified index.
|-
|-
| <code>PlayScene</code>
| <kbd>PlayScene</kbd> || <kbd>float PlayScene(string ''sceneFile'', float ''delay'')</kbd>
| <code>float PlayScene(string ''sceneFile'', float ''delay'')</code>
| Play the specified .vcd file, causing the related characters to speak and subtitles to play.
| Play the specified .vcd file, causing the related characters to speak and subtitles to play.
|}
|}


=== CBaseCombatCharacter ===
=== CBaseCombatCharacter ===
Extends [[#CBaseFlex|CBaseFlex]]
{{↑|toc}}
Extends {{↑|CBaseFlex}}


Combat character. Common and uncommon infected and witches belong to this.
Combat character. Common and uncommon infected and witches belong to this.
Line 560: Line 476:
==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>GetLastKnownArea</code>
| <kbd>GetLastKnownArea</kbd> || <kbd>TerrorNavArea GetLastKnownArea()</kbd>
| <code>TerrorNavArea GetLastKnownArea()</code>
| Return the last nav area occupied - NULL if unknown.
| Return the last nav area occupied - NULL if unknown.
|}
|}


=== CTerrorPlayer ===
=== CTerrorPlayer ===
Extends [[#CBaseCombatCharacter|CBaseCombatCharacter]]
{{↑|toc}}
Extends {{↑|CBaseCombatCharacter}}


Script handle class for player entities. Both survivors and special infected belong to this.
Script handle class for player entities. Both survivors and special infected belong to this.
Line 577: Line 491:


{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>DropItem</code>
| <kbd>DropItem</kbd> || <kbd>void DropItem(string ''classname'')</kbd>
| <code>void DropItem(string ''classname'')</code>
| Make the player drop an item/weapon from their inventory, by classname.
| Make the player drop an item/weapon from their inventory, by classname.
|-
|-
| <code>Extinguish</code>
| <kbd>Extinguish</kbd> || <kbd>void Extinguish()</kbd>
| <code>void Extinguish()</code>
| Extinguish a burning player.
| Extinguish a burning player.
|-
|-
| <code>EyeAngles</code>
| <kbd>EyeAngles</kbd> || <kbd>QAngle EyeAngles()</kbd>
| <code>QAngle EyeAngles()</code>
| Returns the direction the player is looking.
| Returns the direction the player is looking.
|-
|-
| <code>EyePosition</code>
| <kbd>EyePosition</kbd> || <kbd>Vector EyePosition()</kbd>
| <code>Vector EyePosition()</code>
| Returns the players eye position in the world.
| Returns the players eye position in the world.
|-
|-
| <code>GetActiveWeapon</code>
| <kbd>GetActiveWeapon</kbd> || <kbd>handle GetActiveWeapon()</kbd>
| <code>handle GetActiveWeapon()</code>
| Get the player's active weapon entity.
| Get the player's active weapon entity.
|-
|-
| <code>GetAliveDuration</code>
| <kbd>GetAliveDuration</kbd> || <kbd>float GetAliveDuration()</kbd>
| <code>float GetAliveDuration()</code>
| Returns the time the character has been alive (only valid when alive).
| Returns the time the character has been alive (only valid when alive).
|-
|-
| <code>GetButtonMask</code>
| <kbd>GetButtonMask</kbd> || <kbd>int GetButtonMask()</kbd>
| <code>int GetButtonMask()</code>
| Returns a bitfield of currently pressed buttons. Test against each value to see which button is pressed. Recognized buttons are:<br>1 - <kbd>IN_ATTACK</kbd><br>2 - <kbd>IN_JUMP</kbd><br>4 - <kbd>IN_DUCK</kbd><br>8 - <kbd>IN_FORWARD</kbd><br>16 - <kbd>IN_BACK</kbd><br>32 - <kbd>IN_USE</kbd><br>2048 - <kbd>IN_ATTACK2</kbd><br>8192 - <kbd>IN_RELOAD</kbd>
| Returns a bitfield of currently pressed buttons. Recognized buttons are: <code>IN_ATTACK, IN_ATTACK2, IN_JUMP, IN_DUCK, IN_FORWARD, IN_BACK, IN_USE, IN_MOVELEFT, IN_MOVERIGHT, IN_RELOAD</code>
|-
|-
| <code>GetHealthBuffer</code>
| <kbd>GetHealthBuffer</kbd> || <kbd>float GetHealthBuffer()</kbd>
| <code>float GetHealthBuffer()</code>
| Returns the current temporary health of a survivor.
| Returns the current temporary health of a survivor.
|-
|-
| <code>GetNetworkIDString</code>
| <kbd>GetNetworkIDString</kbd> || <kbd>string GetNetworkIDString()</kbd>
| <code>string GetNetworkIDString()</code>
| Get the player's network (i.e. Steam) ID.
| Get the player's network (i.e. Steam) ID.
|-
|-
| <code>GetPlayerName</code>
| <kbd>GetPlayerName</kbd> || <kbd>string GetPlayerName()</kbd>
| <code>string GetPlayerName()</code>
| Get the players name.
| Get the players name.
|-
|-
| <code>GetPlayerUserId</code>
| <kbd>GetPlayerUserId</kbd> || <kbd>int GetPlayerUserId()</kbd>
| <code>int GetPlayerUserId()</code>
| Get the players userID.
| Get the players userID.
|-
|-
| <code>GetSenseFlags</code>
| <kbd>GetSenseFlags</kbd> || <kbd>int GetSenseFlags()</kbd>
| <code>int GetSenseFlags()</code>
| Get the current bot sense flags. Test against each value to see which flag is set. Values:<br>1 - <kbd>BOT_CANT_SEE</kbd><br>2 - <kbd>BOT_CANT_HEAR</kbd><br> 4 - <kbd>BOT_CANT_FEEL</kbd>
| Get the current bits for the bot sense flags: <code>BOT_CANT_SEE, BOT_CANT_HEAR, BOT_CANT_FEEL</code>
|-
|-
| <code>GetSpecialInfectedDominatingMe</code>
| <kbd>GetSpecialInfectedDominatingMe</kbd> || <kbd>CTerrorPlayer GetSpecialInfectedDominatingMe()</kbd>
| <code>CTerrorPlayer GetSpecialInfectedDominatingMe()</code>
| Get the Special Infected dominating this Survivor.
| Get the Special Infected dominating this Survivor.
|-
|-
| <code>GetSurvivorSlot</code>
| <kbd>GetSurvivorSlot</kbd> || <kbd>int GetSurvivorSlot()</kbd>
| <code>int GetSurvivorSlot()</code>
| Get the player's slot number.
| Get the player's slot number.
|-
|-
| <code>GetZombieType</code>
| <kbd>GetZombieType</kbd> || <kbd>int GetZombieType()</kbd>
| <code>int GetZombieType()</code>
| If an infected, find out what type. Recognized ZombieTypes are: Smoker = 1, Boomer = 2, Hunter = 3, Spitter = 4, Jockey = 5, Charger = 6, Witch = 7, Tank = 8, Survivor = 9
| If an infected, find out what type. Recognized ZombieTypes are: Smoker = 1, Boomer = 2, Hunter = 3, Spitter = 4, Jockey = 5, Charger = 6, Witch = 7, Tank = 8, Survivor = 9  
{{tip|1=witch is not a CTerrorPlayer derived entity therefore trying to check her zombie type with this method would result in an error. Use check like <code>ent.GetClassname() == "witch"</code> instead.}}
|-
|-
| <code>GiveAmmo</code>
| <kbd>GiveAmmo</kbd> || <kbd>void GiveAmmo(int ''amount'')</kbd>
| <code>void GiveAmmo(int ''amount'')</code>
| Adds ammo for the player's primary weapon ammo pool.
| Adds ammo for the player's primary weapon ammo pool.
|-
|-
| <code>GiveItem</code>
| <kbd>GiveItem</kbd> || <kbd>void GiveItem(string ''itemname'')</kbd>
| <code>void GiveItem(string ''itemname'')</code>
| Give an item/weapon by name. Uses the same names as the {{Code|give}} console command(<kbd>health, katana, rifle_ak47</kbd>, etc.). {{bug*|Cannot give item to a player that is currently running a chainsaw (same applies to GiveItemWithSkin)}}
| Give an item/weapon by name. Uses the same names as the <code>give</code> console command(<code>health, katana, rifle_ak47</code>, etc.).
|-
|-
| <code>GiveItemWithSkin</code>
| <kbd>GiveItemWithSkin</kbd> || <kbd>void GiveItemWithSkin(string ''classname'', int ''skin'')</kbd>
| <code>void GiveItemWithSkin(string ''classname'', int ''skin'')</code>
| Gives the player a skinned weapon.
| Gives the player a skinned weapon.
|-
|-
| <code>GiveUpgrade</code>
| <kbd>GiveUpgrade</kbd> || <kbd>void GiveUpgrade(int ''upgradeType'')</kbd>
| <code>void GiveUpgrade(int ''upgradeType'')</code>
| Give a primary weapon upgrade. Possible values:<br>0 - <kbd>UPGRADE_INCENDIARY_AMMO</kbd><br>1 - <kbd>UPGRADE_EXPLOSIVE_AMMO</kbd><br>2 - <kbd>UPGRADE_LASER_SIGHT</kbd>
| Give a primary weapon upgrade: <code>UPGRADE_INCENDIARY_AMMO, UPGRADE_EXPLOSIVE_AMMO, UPGRADE_LASER_SIGHT</code>
|-
|-
| <code>HasEverBeenInjured</code>
| <kbd>HasEverBeenInjured</kbd> || <kbd>bool HasEverBeenInjured(int ''team'')</kbd>
| <code>bool HasEverBeenInjured(int ''team'')</code>
| Returns true if the character has ever been injured by a member of the given team.
| Returns true if the character has ever been injured by a member of the given team.
|-
|-
| <code>HitWithVomit</code>
| <kbd>HitWithVomit</kbd> || <kbd>void HitWithVomit()</kbd>
| <code>void HitWithVomit()</code>
| Cover the player with a boomer vomit attack.
| Cover the player with a boomer vomit attack.
|-
|-
| <code>IsAdrenalineActive</code>
| <kbd>IsAdrenalineActive</kbd> || <kbd>bool IsAdrenalineActive()</kbd>
| <code>bool IsAdrenalineActive()</code>
| Return true if adrenaline is active.
| Return true if adrenaline is active.
|-
|-
| <code>IsDead</code>
| <kbd>IsDead</kbd> || <kbd>bool IsDead()</kbd>
| <code>bool IsDead()</code>
| Returns true when a player is dead for more than 5 seconds. Note that taking over a dying bot immediately switches to the dead phase.
| Returns true when a player is dead for more than 5 seconds.
|-
|-
| <code>IsDominatedBySpecialInfected</code>
| <kbd>IsDominatedBySpecialInfected</kbd> || <kbd>bool IsDominatedBySpecialInfected()</kbd>
| <code>bool IsDominatedBySpecialInfected()</code>
| Return true if being dominated by a Special Infected (i.e. held by smoker, charger, jockey or hunter)
| Return true if being dominated by a Special Infected.
|-
|-
| <code>IsDying</code>
| <kbd>IsDying</kbd> || <kbd>bool IsDying()</kbd>
| <code>bool IsDying()</code>
| Returns true when a player has recently died for 5 seconds. Note that taking over a dying bot skips the dying phase.
| Returns true when a player has recently died for 5 seconds.
|-
|-
| <code>IsFiringWeapon</code>
| <kbd>IsFiringWeapon</kbd> || <kbd>bool IsFiringWeapon()</kbd>
| <code>bool IsFiringWeapon()</code>
| Return true if player is firing a weapon.
| Return true if player is firing a weapon.
|-
|-
| <code>IsIncapacitated</code>
| <kbd>IsIncapacitated</kbd> || <kbd>bool IsIncapacitated()</kbd>
| <code>bool IsIncapacitated()</code>
| Returns true if in incapacitated state.
| Returns true if in incapacitated state.
|-
|-
| <code>IsHangingFromLedge</code>
| <kbd>IsHangingFromLedge</kbd> || <kbd>bool IsHangingFromLedge()</kbd>
| <code>bool IsHangingFromLedge()</code>
| Returns true if in ledge hang state.
| Returns true if in ledge hang state.
|-
|-
| <code>IsGettingUp</code>
| <kbd>IsGettingUp</kbd> || <kbd>bool IsGettingUp()</kbd>
| <code>bool IsGettingUp()</code>
| Return true if player is currently getting up.
| Return true if player is currently getting up.
|-
|-
| <code>IsGhost</code>
| <kbd>IsGhost</kbd> || <kbd>bool IsGhost()</kbd>
| <code>bool IsGhost()</code>
| Returns true if in ghost infected state.
| Returns true if in ghost infected state.
|-
|-
| <code>IsImmobilized</code>
| <kbd>IsImmobilized</kbd> || <kbd>bool IsImmobilized()</kbd>
| <code>bool IsImmobilized()</code>
| Return true if currently immobilized. {{tip|Is true when in getting up animation, punched by tank, flung by charger, caught by charger, smoker or hunter, hanging, incapacitated, dead, being healed, using kit, defibrillator or unpacking an upgrade pack, using timed button, pouring gas can, handing in cola or using minigun (not true when staggering or caught by jockey)}}
| Return true if currently immobilized.
|-
|-
| <code>IsInCombat</code>
| <kbd>IsInCombat</kbd> || <kbd>bool IsInCombat()</kbd>
| <code>bool IsInCombat()</code>
| Return true if currently in combat.
| Return true if currently in combat.
|-
|-
| <code>IsIT</code>
| <kbd>IsIT</kbd> || <kbd>bool IsIT()</kbd>
| <code>bool IsIT()</code>
| Return true if currently IT from bile.
| Return true if currently IT from bile.
|-
|-
| <code>IsOnFire</code>
| <kbd>IsOnFire</kbd> || <kbd>bool IsOnFire()</kbd>
| <code>bool IsOnFire()</code>
| Returns true if a player is on fire, e.g. Standing in fireworks crate explosions.
| Returns true if a player is on fire, e.g. Standing in fireworks crate explosions.
|-
|-
| <code>IsOnThirdStrike</code>
| <kbd>IsOnThirdStrike</kbd> || <kbd>bool IsOnThirdStrike()</kbd>
| <code>bool IsOnThirdStrike()</code>
| Return true if on third-strike.
| Return true if on third-strike.
|-
|-
| <code>IsStaggering</code>
| <kbd>IsStaggering</kbd> || <kbd>bool IsStaggering()</kbd>
| <code>bool IsStaggering()</code>
| Return true if player is staggering.
| Return true if player is staggering.
|-
|-
| <code>IsSuppressingFallingDamage</code>
| <kbd>IsSuppressingFallingDamage</kbd> || <kbd>bool IsSuppressingFallingDamage()</kbd>
| <code>bool IsSuppressingFallingDamage()</code>
| Returns true if falling damage is currently suppressed, which is if the entity received the {{Code|IgnoreFallDamage}} or {{Code|IgnoreFallDamageWithoutReset}} input, provided that it is still active.
| Returns true if falling damage is currently suppressed, which is if the entity received the <code>IgnoreFallDamage</code> or <code>IgnoreFallDamageWithoutReset</code> input, provided that it is still active.
|-
|-
| <code>IsSurvivor</code>
| <kbd>IsSurvivor</kbd> || <kbd>bool IsSurvivor()</kbd>
| <code>bool IsSurvivor()</code>
| Returns true if entity is on the survivor or l4d1 survivor team (Otherwise, unknown, spectator or infected).
| Returns true if entity is on the survivor team (Otherwise, infected).
|-
|-
| <code>RemoveUpgrade</code>
| <kbd>RemoveUpgrade</kbd> || <kbd>void RemoveUpgrade(int ''upgradeType'')</kbd>
| <code>void RemoveUpgrade(int ''upgradeType'')</code>
| Remove a primary weapon upgrade. Possible values:<br>0 - <kbd>UPGRADE_INCENDIARY_AMMO</kbd><br>1 - <kbd>UPGRADE_EXPLOSIVE_AMMO</kbd><br>2 - <kbd>UPGRADE_LASER_SIGHT</kbd>
| Remove a primary weapon upgrade: <code>UPGRADE_INCENDIARY_AMMO, UPGRADE_EXPLOSIVE_AMMO, UPGRADE_LASER_SIGHT</code>
|-
|-
| <code>ReviveByDefib</code>
| <kbd>ReviveByDefib</kbd> || <kbd>void ReviveByDefib()</kbd>
| <code>void ReviveByDefib()</code>
| Revive a dead player by defib.  
| Revive a dead player by defib.  
|-
|-
| <code>ReviveFromIncap</code>
| <kbd>ReviveFromIncap</kbd> || <kbd>void ReviveFromIncap()</kbd>
| <code>void ReviveFromIncap()</code>
| Revive an incapacitated player.
| Revive an incapacitated player.
|-
|-
| <code>SetFriction</code>
| <kbd>SetFriction</kbd> || <kbd>void SetFriction(int ''friction'')</kbd>
| <code>void SetFriction(int ''friction'')</code>
| Set player friction.
| Set player friction.
|-
|-
| <code>SetGravity</code>
| <kbd>SetGravity</kbd> || <kbd>void SetGravity(int ''gravity'')</kbd>
| <code>void SetGravity(int ''gravity'')</code>
| Set player gravity.
| Set player gravity.
|-
|-
| <code>SetHealthBuffer</code>
| <kbd>SetHealthBuffer</kbd> || <kbd>void SetHealthBuffer(float ''health'')</kbd>
| <code>void SetHealthBuffer(float ''health'')</code>
| Sets the temporary health of a survivor; No effect for infecteds. Does not incapacitate or kill when set to zero.
| Sets the temporary health of a survivor; No effect for infecteds. Does not incapacitate or kill when set to zero.
|-
|-
| <code>SetReviveCount</code>
| <kbd>SetReviveCount</kbd> || <kbd>void SetReviveCount(int ''count'')</kbd>
| <code>void SetReviveCount(int ''count'')</code>
| Sets the number of times a survivor has been revived, and updates third-strike state (B&W) and heartbeat sound.
| Sets the number of times a survivor has been revived, and updates third-strike state and effects.
{{bug*|Doesn't update the <kbd>m_isGoingToDie</kbd> netprop, which controls the dying quotes.|only=l4d2}}
|-
|-
| <code>SetSenseFlags</code>
| <kbd>SetSenseFlags</kbd> || <kbd>void SetSenseFlags(int ''flags'')</kbd>
| <code>void SetSenseFlags(int ''flags'')</code>
| Set the set of bot sense flags. Combine values to set appropriate flags:<br>1 - <kbd>BOT_CANT_SEE</kbd><br>2 - <kbd>BOT_CANT_HEAR</kbd><br> 4 - <kbd>BOT_CANT_FEEL</kbd>
| Set the current bits for the bot sense flags:<code>BOT_CANT_SEE, BOT_CANT_HEAR, BOT_CANT_FEEL</code>
|-
|-
| <code>SnapEyeAngles</code>
| <kbd>SnapEyeAngles</kbd> || <kbd>void SnapEyeAngles(QAngle ''angles'')</kbd>
| <code>void SnapEyeAngles(QAngle ''angles'')</code>
| Sets the view angles. Supports rolling the view.
| Sets the view angles. Supports rolling the view.
|-
|-
| <code>Stagger</code>
| <kbd>Stagger</kbd> || <kbd>void Stagger(Vector ''position'')</kbd>
| <code>void Stagger(Vector ''position'')</code>
| Stagger a player away from a position. Use Vector(0,0,0) to just stagger forward.
| Stagger a player away from a position. Use Vector(0,0,0) to just stagger forward.
|-
|-
| <code>SwitchToItem</code>
| <kbd>SwitchToItem</kbd> || <kbd>bool SwitchToItem(string ''classname'')</kbd>
| <code>bool SwitchToItem(string ''classname'')</code>
| Make the player switch to an item/weapon by classname. Returns true if the switch was performed.
| Make the player switch to an item/weapon by classname. Returns true if the switch was performed.
|-
|-
| <code>TryGetPathableLocationWithin</code>
| <kbd>TryGetPathableLocationWithin</kbd> || <kbd>Vector TryGetPathableLocationWithin(float ''radius'')</kbd>
| <code>Vector TryGetPathableLocationWithin(float ''radius'')</code>
| Get a location on the nav the player can path to within the desired radius.
| Get a location on the nav the player can path to within the desired radius.
|-
|-
| <code>UseAdrenaline</code>
| <kbd>UseAdrenaline</kbd> || <kbd>void UseAdrenaline(float ''duration'')</kbd>
| <code>void UseAdrenaline(float ''duration'')</code>
| Causes Adrenaline's speed and visual effect, no change to health.
| Causes Adrenaline's speed and visual effect, no change to health.
|}
|}


=== CTerrorWeapon ===
=== CTerrorWeapon ===
Extends [[#CBaseAnimating|CBaseAnimating]]. All weapon entities that are part of a player's inventory ([[weapon_rifle]] and such), holstered or not, belongs to this. All<code>Clip2</code>related functions have no gameplay effects (unless weapon scripts are modded), but can be used for your own custom weapon ammunition needs. E.g. A Hunting Rifle with 3 Oxygen Tank throwables.
{{↑|toc}}
{{note|[[weapon_chainsaw]]'s fuel can be modified with the<code>Clip1</code>related functions!}}
Extends {{↑|CBaseAnimating}}.
 
All weapon entities that are part of a player's inventory, holstered or not, belongs to this. All {{Code|Clip2}} related functions have no gameplay effects (unless weapon scripts are modded), but can be used for your own custom weapon ammunition needs. E.g. A Hunting Rifle with 3 Oxygen Tank throwables.
{{note|[[weapon_chainsaw]]'s fuel can be modified with the {{Code|Clip1}} related functions!}}
{{note|[[weapon_pistol]]'s {{Code|GetDefaultClip1}} is always treated as a single pistol, but {{Code|GetMaxClip1}} will account for dual pistols as well! }}


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>Clip1</code>
| <kbd>Clip1</kbd> || <kbd>int Clip1()</kbd>
| <code>int Clip1()</code>
| Current amount of ammo in a weapon's clip.
| Current amount of ammo in a weapon's clip.
|-
|-
| <code>Clip2</code>
| <kbd>Clip2</kbd> || <kbd>int Clip2()</kbd>
| <code>int Clip2()</code>
| Current 'secondary clip' ammo count. Always -1 in default game.
| Current 'secondary clip' ammo count. Always -1 in default game.
|-
|-
| <code>GetDefaultClip1</code>
| <kbd>GetDefaultClip1</kbd> || <kbd>int GetDefaultClip1()</kbd>
| <code>int GetDefaultClip1()</code>
| Clip count of a weapon when its newly picked up.
| Clip count of a weapon when its newly picked up. {{note|To find the respective cvar, find <code>ammo_X_max</code> at [[List_of_L4D2_Cvars|here]], where ''X'' is the weapon's respective classname.}}
|-
|-
| <code>GetDefaultClip2</code>
| <kbd>GetDefaultClip2</kbd> || <kbd>int GetDefaultClip2()</kbd>
| <code>int GetDefaultClip2()</code>
| Default 'secondary clip' ammo count. Always -1 in default game; Only a positive value if a custom weapon script has {{Code|clip2_size}} set.
| Default 'secondary clip' ammo count. Always -1 in default game; Only a positive value if a custom weapon script has<code>clip2_size</code>set.
|-
|-
| <code>GetMaxClip1</code>
| <kbd>GetMaxClip1</kbd> || <kbd>int GetMaxClip1()</kbd>
| <code>int GetMaxClip1()</code>
| Max clip count a weapon can hold. Will always return the same value as the {{Code|GetDefaultClip1}} function.
| Max clip count a weapon can hold. Will always return the same value as<code>CTerrorWeapon::GetDefaultClip1</code>.
|-
|-
| <code>GetMaxClip2</code>
| <kbd>GetMaxClip2</kbd> || <kbd>int GetMaxClip2()</kbd>
| <code>int GetMaxClip2()</code>
| Max 'secondary clip' count. Always -1 in default game; Only a positive value if a custom weapon script has {{Code|clip2_size}} set. Will always return the same value as the {{Code|GetDefaultClip2}} function.
| Max 'secondary clip' count. Always -1 in default game; Only a positive value if a custom weapon script has<code>clip2_size</code>set. Will always return the same value as<code>CTerrorWeapon::GetDefaultClip2</code>.
|-
|-
| <code>GiveDefaultAmmo</code>
| <kbd>GiveDefaultAmmo</kbd> || <kbd>void GiveDefaultAmmo()</kbd>
| <code>void GiveDefaultAmmo()</code>
| Revert both weapons's clip to their default values.
| Revert both weapons's clip to their default values.
|-
|-
| <code>Reload</code>
| <kbd>Reload</kbd> || <kbd>bool Reload()</kbd>
| <code>bool Reload()</code>
| Forces the weapon to reload if it is not full. Returns true if it could start a weapon reload.
| Forces the weapon to reload if it is not full. Returns true if it could start a weapon reload.
|-
|-
| <code>SetClip1</code>
| <kbd>SetClip1</kbd> || <kbd>void SetClip1(int ''amount'')</kbd>
| <code>void SetClip1(int ''amount'')</code>
| Sets a weapon's clip count.
| Sets a weapon's clip count.
|-
|-
| <code>SetClip2</code>
| <kbd>SetClip2</kbd> || <kbd>void SetClip2(int ''amount'')</kbd>
| <code>void SetClip2(int ''amount'')</code>
| Sets a weapon's 'secondary clip' count; Works just fine but has no gameplay effect in default game.
| Sets a weapon's 'secondary clip' count; Works just fine but has no gameplay effect in default game.
|}
|}


=== CBaseTrigger ===
=== CBaseTrigger ===
Extends [[#CBaseEntity|CBaseEntity]]
{{↑|toc}}
Extends {{↑|CBaseEntity}}


Entity class for triggers, so entities like [[trigger_once]] or [[script_trigger_hurt]] belong to this.
Entity class for [[:Category:CBaseTrigger|all entities inheriting CBaseTrigger]]


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function  
! Function !! Signature !! Description  
! Signature  
! Description  
|-
|-
| <code>Disable</code>
| <kbd>Disable</kbd> || <kbd>void Disable() </kbd>
| <code>void Disable() </code>
| Disable the trigger. Identical to the {{Code|Disable}} input.
| Disable the trigger from thinking. Identical to the<code>Disable</code>input.
|-
|-
| <code>Enable</code>
| <kbd>Enable</kbd> || <kbd>void Enable() </kbd>
| <code>void Enable() </code>
| Enable the trigger. Identical to the {{Code|Enable}} input.
| Enable the trigger from thinking. Identical to the<code>Enable</code>input.
|-
|-
| <code>IsTouching</code>
| <kbd>IsTouching</kbd> || <kbd>bool IsTouching(handle ''entity'') </kbd>
| <code>bool IsTouching(handle ''entity'') </code>
| Checks whether the passed entity is touching the trigger.
| Checks whether the passed entity is touching the trigger.
|}
|}


=== AI_Response ===
=== AI_Response ===
{{↑|toc}}
''Opaque type representing a return value from the old response system.''
''Opaque type representing a return value from the old response system.''


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>GetMatchScore</code>
| <kbd>GetMatchScore</kbd> ||  
|  
| Relative score of this match's quality (based on number of criteria matched)).
| Relative score of this match's quality (based on number of criteria matched)).
|}
|}


=== CCallChainer ===
=== CDirector ===
{{todo}}
{{↑|toc}}
{{↑|Instances}} Game Instance: <kbd>Director</kbd>
 
Provides methods for reading information and forcing events in the AI Director. To influence the Director behavior, the {{Code|[[L4D2_Director_Scripts#DirectorOptions|DirectorOptions]]}} table is used instead.


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>constructor</code>
| <kbd>AreAllSurvivorsInBattlefield</kbd> || <kbd>bool AreAllSurvivorsInBattlefield()</kbd>
| <code>CCallChainer(string ''functionPrefix'', table ''scope'' = null)</code>
| Returns true if all Survivors are in the battlefield.
|  
|-
|-
| <code>PostScriptExecute</code>
| <kbd>AreAllSurvivorsInFinaleArea</kbd> || <kbd>bool AreAllSurvivorsInFinaleArea()</kbd>
| <code>void PostScriptExecute()</code>
| True when all survivors are within the finale area.
| Method finds all specified non-native functions and fills <code>chains</code> table with them.
|-
|-
| <code>Call</code>
| <kbd>AreTeamsFlipped</kbd> || <kbd>bool AreTeamsFlipped()</kbd>
| <code>bool Call()</code>
| True when teams are flipped in Versus modes.
| Argument is a <code>vargv</code> list, the first argument of the list must be the name of function passed as the string (the string must match a key in <code>chains</code> table), then arguments of called function.
|}
 
==== Members ====
{| class="standard-table" style="width: 100%;"
! Instance
! Type
! Description
|-
|-
| <code>chains</code>
| <kbd>ClearCachedBotQueries</kbd> || <kbd>void ClearCachedBotQueries()</kbd>
| <code>table</code>
| Mark all cached bot query results as invalid.
| Contents keys with name of functions, points to array of functions to call.
|-
|-
| <code>prefix</code>
| <kbd>ForceNextStage</kbd> || <kbd>void ForceNextStage()</kbd>
| <code>string</code>
| Push the ScriptedMode to next stage - i.e. request GNSS be called.
| Prefix to find a function (and add it without that prefix to <code>chains</code> table).
|-
|-
| <code>scope</code>
| <kbd>GetAveragedSurvivorSpan</kbd> || <kbd>float GetAveragedSurvivorSpan()</kbd>
| <code>table</code>
| Get the distance between the lead and trailing survivors, smoothed over time.
| Scope to seek functions, pass <code>null</code> to use global space.
|}
 
=== CDirector ===
Game Instance: <code>Director</code>
 
Provides methods for reading information and forcing events in the AI Director. To influence the Director behavior, the <code>[[L4D2_Director_Scripts#DirectorOptions|DirectorOptions]]</code> table is used instead.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function
! Signature
! Description
|-
|-
| <code>AreAllSurvivorsInFinaleArea</code>
| <kbd>GetAveragedSurvivorSpeed</kbd> || <kbd>float GetAveragedSurvivorSpeed()</kbd>
| <code>bool AreAllSurvivorsInFinaleArea()</code>
| Get the rate at which the lead survivor is moving along the flow, smoothed over time.
| True when all survivors are within the finale area.
|-
|-
| <code>AreTeamsFlipped</code>
| <kbd>GetClosestActivePipeBomb</kbd> || <kbd>CBaseEntity GetClosestActivePipeBomb(Vector ''origin'')</kbd>
| <code>bool AreTeamsFlipped()</code>
| Returns the closest active pipe bomb from this origin.
| True when teams are flipped in Versus modes.
|-
| <code>ClearCachedBotQueries</code>
| <code>void ClearCachedBotQueries()</code>
| Mark all cached bot query results as invalid.
|-
| <code>ForceNextStage</code>
| <code>void ForceNextStage()</code>
| Push the ScriptedMode to next stage - i.e. request GNSS be called.
|-
| <code>GetAveragedSurvivorSpan</code>
| <code>float GetAveragedSurvivorSpan()</code>
| Get the distance between the lead and trailing survivors, smoothed over time.
|-
|-
| <code>GetAveragedSurvivorSpeed</code>
| <kbd>GetClosestCharacterWhoIsIT</kbd> || <kbd>CBaseCombatCharacter GetClosestCharacterWhoIsIT(CBaseCombatCharacter ''character'')</kbd>
| <code>float GetAveragedSurvivorSpeed()</code>
| Returns the closest character who is IT to the passed character.
| Get the rate at which the lead survivor is moving along the flow, smoothed over time.
|-
|-
| <code>GetClosestActivePipeBomb</code>
| <kbd>GetClosestSurvivor</kbd> || <kbd>CTerrorPlayer GetClosestSurvivor(Vector ''origin'', bool bIncludeIncap, bool bIncludeOnRescueVehicle)</kbd>
| <code>CBaseEntity GetClosestActivePipeBomb(Vector ''origin'')</code>
| Returns the closest Survivor from the passed origin, if incapped Survivors are included in search, or on rescue vehicle.
| Returns the closest active pipe bomb from this origin.
|-
|-
| <code>GetCommonInfectedCount</code>
| <kbd>GetCommonInfectedCount</kbd> || <kbd>int GetCommonInfectedCount()</kbd>
| <code>int GetCommonInfectedCount()</code>
| Returns number for infected currently spawned.
| Returns number for infected currently spawned.
|-
|-
| <code>GetFurthestSurvivorFlow</code>
| <kbd>GetFurthestSurvivorFlow</kbd> || <kbd>float GetFurthestSurvivorFlow()</kbd>
| <code>float GetFurthestSurvivorFlow()</code>
| Get the maximum distance along the flow that the survivors have reached.
| Get the maximum distance along the flow that the survivors have reached.
|-
|-
| <code>GetGameMode</code>
| <kbd>GetGameMode</kbd> || <kbd>string GetGameMode()</kbd>
| <code>string GetGameMode()</code>
| Get the current game mode. If called in a mutation, it returns the current mutation, not the base mode. Will '''only''' look for the specific game mode/mutation.
| Get the current game mode. If called in a mutation, it returns the current mutation, not the base mode.
|-
|-
| <code>GetGameModeBase</code>
| <kbd>GetGameModeBase</kbd> || <kbd>string GetGameModeBase()</kbd>
| <code>string GetGameModeBase()</code>
| Get the current base game mode. Does not return the current mutation. Example, if looking for survival, it will also count for all game modes using survival as base. Such as Mutation 15 (Survival Versus)
| Get the current base game mode. Does not return the current mutation.
|-
|-
| <code>GetHoldoutCooldownEndTime</code>
| <kbd>GetHighestFlowSurvivor</kbd> || <kbd>CTerrorPlayer GetHighestFlowSurvivor()</kbd>
| <code>float GetHoldoutCooldownEndTime()</code>
| Returns the Survivor with the highest flow.
|-
| <kbd>GetHoldoutCooldownEndTime</kbd> || <kbd>float GetHoldoutCooldownEndTime()</kbd>
| Get the end time of the cooldown timer.
| Get the end time of the cooldown timer.
|-
|-
| <code>GetMapName</code>
| <kbd>GetLowestFlowSurvivor</kbd> || <kbd>CTerrorPlayer GetLowestFlowSurvivor()</kbd>
| <code>string GetMapName()</code>
| Returns the Survivor with the lowest flow.
|-
| <kbd>GetMapName</kbd> || <kbd>string GetMapName()</kbd>
| Get the current map name.
| Get the current map name.
|-
|-
| <code>GetMapNumber</code>
| <kbd>GetMapNumber</kbd> || <kbd>int GetMapNumber()</kbd>
| <code>int GetMapNumber()</code>
| Return the current map number.
| Return the current map number.
|-
|-
| <code>GetMissionWipes</code>
| <kbd>GetMissionWipes</kbd> || <kbd>int GetMissionWipes()</kbd>
| <code>int GetMissionWipes()</code>
| Returns the current number of mission wipes.
| Returns the current number of mission wipes.
|-
|-
| <code>GetPendingMobCount</code>
| <kbd>GetPendingMobCount</kbd> || <kbd>int GetPendingMobCount()</kbd>
| <code>int GetPendingMobCount()</code>
| Returns the number of infected waiting to spawn.
| Returns the number of infected waiting to spawn.
|-
|-
| <code>GetSurvivorSet</code>
| <kbd>GetRandomSurvivor</kbd> || <kbd>CTerrorPlayer GetRandomSurvivor()</kbd>
| <code>int GetSurvivorSet()</code>
| Returns a random alive Survivor.
| Get the current survivor set. L4D1 Survivors = 1, L4D2 Survivors = 2.
|-
| <kbd>GetSurvivorSet</kbd> || <kbd>int GetSurvivorSet()</kbd>
| Get the current survivor set. L4D1 Survivors = 1, L4D2 Survivors = 2. {{bug*|Calling this inside mapspawn_addon or response_testbed_addon will give survivor set value of previous loaded map}}
|-
|-
| <code>GetTimeSinceSpecialZombieKilled</code>
| <kbd>GetTimeSinceSpecialZombieKilled</kbd> || <kbd>float GetTimeSinceSpecialZombieKilled(int ''zombieType'')</kbd>
| <code>float GetTimeSinceSpecialZombieKilled(int ''zombieType'')</code>
| Returns the time since the passed zombie type was killed.
| Returns the time since the passed zombie type was killed.
|-
|-
| <code>GetTotalElapsedMissionTime</code>
| <kbd>GetTotalElapsedMissionTime</kbd> || <kbd>float GetTotalElapsedMissionTime()</kbd>
| <code>float GetTotalElapsedMissionTime()</code>
| Returns the total elapsed mission time.
| Returns the total elapsed mission time.
|-
|-
| <code>HasAnySurvivorLeftSafeArea</code>
| <kbd>HasAnySurvivorLeftSafeArea</kbd> || <kbd>bool HasAnySurvivorLeftSafeArea()</kbd>
| <code>bool HasAnySurvivorLeftSafeArea()</code>
| True when one or more survivors have left the starting safe area.
| True when one or more survivors have left the starting safe area.
|-
|-
| <code>IsAnySurvivorBypassingTank</code>
| <kbd>IsAnySurvivorBypassingTank</kbd> || <kbd>bool IsAnySurvivorBypassingTank()</kbd>
| <code>bool IsAnySurvivorBypassingTank()</code>
| True when one or more survivors are bypassing the Tank.
| True when one or more survivors are bypassing the Tank.
|-
|-
| <code>IsAnySurvivorInCombat</code>
| <kbd>IsAnySurvivorInCombat</kbd> || <kbd>bool IsAnySurvivorInCombat()</kbd>
| <code>bool IsAnySurvivorInCombat()</code>
| Returns true if any survivor recently dealt or took damage.
| Returns true if any survivor recently dealt or took damage.
|-
|-
| <code>IsAnySurvivorInExitCheckpoint</code>
| <kbd>IsAnySurvivorInExitCheckpoint</kbd> || <kbd>bool IsAnySurvivorInExitCheckpoint()</kbd>
| <code>bool IsAnySurvivorInExitCheckpoint()</code>
| True when one or more survivors are in the exit checkpoint.
| True when one or more survivors are in the exit checkpoint.
|-
|-
| <code>IsAnySurvivorInStartArea</code>
| <kbd>IsAnySurvivorInStartArea</kbd> || <kbd>bool IsAnySurvivorInStartArea()</kbd>
| <code>bool IsAnySurvivorInStartArea()</code>
| True when one or more survivors are in the starting safe area.
| True when one or more survivors are in the starting safe area.
|-
|-
| <code>IsFinale</code>
| <kbd>IsFinale</kbd> || <kbd>bool IsFinale()</kbd>
| <code>bool IsFinale()</code>
| True when the finale has started.
| True when the finale has started.
|-
|-
| <code>IsFinaleEscapeInProgress</code>
| <kbd>IsFinaleEscapeInProgress</kbd> || <kbd>bool IsFinaleEscapeInProgress()</kbd>
| <code>bool IsFinaleEscapeInProgress()</code>
| True when the finale escape is in progress.
| True when the finale escape is in progress.
|-
|-
| <code>IsFinaleVehicleReady</code>
| <kbd>IsFinaleVehicleReady</kbd> || <kbd>bool IsFinaleVehicleReady()</kbd>
| <code>bool IsFinaleVehicleReady()</code>
| True when the finale vehicle is ready.
| True when the finale vehicle is ready.
|-
|-
| <code>IsFinaleWon</code>
| <kbd>IsFinaleWon</kbd> || <kbd>bool IsFinaleWon()</kbd>
| <code>bool IsFinaleWon()</code>
| Returns true if the finale has been won.
| Returns true if the finale has been won.
|-
|-
| <code>IsFirstMapInScenario</code>
| <kbd>IsFirstMapInScenario</kbd> || <kbd>bool IsFirstMapInScenario()</kbd>
| <code>bool IsFirstMapInScenario()</code>
| True if the first map in a scenario.
| True if the first map in a scenario.
|-
|-
| <code>IsL4D1Campaign</code>
| <kbd>IsL4D1Campaign</kbd> || <kbd>bool IsL4D1Campaign()</kbd>
| <code>bool IsL4D1Campaign()</code>
| Return true if the current campaign is originally from L4D1.
| Return true if the current campaign is originally from L4D1.
|-
|-
| <code>IsLocationFoggedToSurvivors</code>
| <kbd>IsLocationFoggedToSurvivors</kbd> || <kbd>bool IsLocationFoggedToSurvivors(Vector ''origin'')</kbd>
| <code>bool IsLocationFoggedToSurvivors(Vector ''origin'')</code>
| Returns true if the passed location is fogged to Survivors.
| Returns true if the passed location is fogged to Survivors.
|-
|-
| <code>IsPlayingIntro</code>
| <kbd>IsPlayingIntro</kbd> || <kbd>bool IsPlayingIntro()</kbd>
| <code>bool IsPlayingIntro()</code>
| True if the intro is currently playing.
| True if the intro is currently playing.
|-
|-
| <code>IsPlayingOnConsole</code>
| <kbd>IsPlayingOnConsole</kbd> || <kbd>bool IsPlayingOnConsole()</kbd>
| <code>bool IsPlayingOnConsole()</code>
| Return true if game is running on a console (such as Xbox 360).
| Return true if game is running on a console (such as Xbox 360).
|-
|-
| <code>IsSessionStartMap</code>
| <kbd>IsSessionStartMap</kbd> || <kbd>bool IsSessionStartMap()</kbd>
| <code>bool IsSessionStartMap()</code>
| True if the map is the start of the session.
| True if the map is the start of the session.
|-
|-
| <code>IsSinglePlayerGame</code>
| <kbd>IsSinglePlayerGame</kbd> || <kbd>bool IsSinglePlayerGame()</kbd>
| <code>bool IsSinglePlayerGame()</code>
| Return true if game is in single player.
| Return true if game is in single player.
|-
|-
| <code>IsValid</code>
| <kbd>IsValid</kbd> || <kbd>bool IsValid()</kbd>
| <code>bool IsValid()</code>
| Whether<kbd>Director</kbd>belongs to a valid entity. Seems futile to use.
| Whether<code>Director</code>belongs to a valid entity. Seems futile to use.
|-
|-
| <code>IsTankInPlay</code>
| <kbd>IsTankInPlay</kbd> || <kbd>bool IsTankInPlay()</kbd>
| <code>bool IsTankInPlay()</code>
| Returns true if any tanks are aggro on survivors.
| Returns true if any tanks are aggro on survivors.
|-
|-
| <code>L4D1SurvivorGiveItem</code>
| <kbd>L4D1SurvivorGiveItem</kbd> || <kbd>void L4D1SurvivorGiveItem()</kbd>
| <code>void L4D1SurvivorGiveItem()</code>
| Let the L4D1 survivors know that now is a good time to give the players an item.
| Let the L4D1 survivors know that now is a good time to give the players an item.
|-
|-
| <code>PlayMegaMobWarningSounds</code>
| <kbd>PlayMegaMobWarningSounds</kbd> || <kbd>void PlayMegaMobWarningSounds()</kbd>
| <code>void PlayMegaMobWarningSounds()</code>
| Plays a horde scream sound and asks survivors to speak ''incoming horde'' lines.
| Plays a horde scream sound and asks survivors to speak ''incoming horde'' lines.
|-
|-
| <code>RegisterForbiddenTarget</code>
| <kbd>RegisterForbiddenTarget</kbd> || <kbd>void RegisterForbiddenTarget(CBaseEntity ''entity'')</kbd>
| <code>void RegisterForbiddenTarget(CBaseEntity ''entity'')</code>
| Registers a target entity as forbidden.
| Registers a target entity as forbidden.
|-
|-
| <code>ResetMobTimer</code>
| <kbd>ResetMobTimer</kbd> || <kbd>void ResetMobTimer()</kbd>
| <code>void ResetMobTimer()</code>
| Trigger a mob as soon as possible when in {{Code|BUILD_UP}}.
| Trigger a mob as soon as possible when in <code>BUILD_UP</code>.
|-
|-
| <code>ResetSpecialTimers</code>
| <kbd>ResetSpecialTimers</kbd> || <kbd>void ResetSpecialTimers()</kbd>
| <code>void ResetSpecialTimers()</code>
| Reset all special timers (by type and by slot) so that hopefully mobs will spawn asap.
| Reset all special timers (by type and by slot) so that hopefully mobs will spawn asap.
|-
|-
| <code>SetHoldoutCooldownEndTime</code>
| <kbd>SetHoldoutCooldownEndTime</kbd> || <kbd>void SetHoldoutCooldownEndTime(float ''time'')</kbd>
| <code>void SetHoldoutCooldownEndTime(float ''time'')</code>
|  
|  
|-
|-
| <code>UnregisterForbiddenTarget</code>
| <kbd>UnregisterForbiddenTarget</kbd> || <kbd>void UnregisterForbiddenTarget(CBaseEntity ''entity'')</kbd>
| <code>void UnregisterForbiddenTarget(CBaseEntity ''entity'')</code>
| Unregisters a target entity as forbidden.
| Unregisters a target entity as forbidden.
|-
|-
| <code>UserDefinedEvent1</code>
| <kbd>UserDefinedEvent1</kbd><br><kbd>UserDefinedEvent2</kbd><br><kbd>UserDefinedEvent3</kbd><br><kbd>UserDefinedEvent4</kbd> || <kbd>void UserDefinedEvent1()</kbd><br><kbd>void UserDefinedEvent2()</kbd><br><kbd>void UserDefinedEvent3()</kbd><br><kbd>void UserDefinedEvent4()</kbd>
| <code>void UserDefinedEvent1()</code>
| When called, these trigger the appropriate output of the {{Code|[[info_director]]}} entity.
| These trigger the appropriate output from the [[info_director]] entity when called.
|-
| <code>UserDefinedEvent2</code>
| <code>void UserDefinedEvent2()</code>
|
|-
| <code>UserDefinedEvent3</code>
| <code>void UserDefinedEvent3()</code>
|  
|  
|-
|-
| <code>UserDefinedEvent4</code>
| <kbd>WarpAllSurvivorsToBattlefield</kbd> || <kbd>void WarpAllSurvivorsToBattlefield()</kbd>
| <code>void UserDefinedEvent4()</code>
|  
|-
| <code>WarpAllSurvivorsToBattlefield</code>
| <code>void WarpAllSurvivorsToBattlefield()</code>
| Warp all Survivors to the battlefield.
| Warp all Survivors to the battlefield.
|-
|-
| <code>WarpAllSurvivorsToCheckpoint</code>
| <kbd>WarpAllSurvivorsToCheckpoint</kbd> || <kbd>void WarpAllSurvivorsToCheckpoint()</kbd>
| <code>void WarpAllSurvivorsToCheckpoint()</code>
| Warp all Survivors to the exit checkpoint.
| Warp all Survivors to the exit checkpoint.
|-
|-
| <code>WarpAllSurvivorsToFinale</code>
| <kbd>WarpAllSurvivorsToFinale</kbd> || <kbd>void WarpAllSurvivorsToFinale()</kbd>
| <code>void WarpAllSurvivorsToFinale()</code>
| Warp all Survivors to the finale radio.
| Warp all Survivors to the finale radio.
|}
|}


=== CEntities ===
=== CEntities ===
Game Instance:<code>Entities</code>
{{↑|toc}}
{{↑|Instances}} Game Instance: <kbd>Entities</kbd>


An interface to find and iterate over the script handles for the entities in play.
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.


For methods with the<code>previous</code>parameter, any found entity with an [[Entity_index|entity index]] smaller than the one in<code>previous</code>is skipped over. An iteration over a set of entities can be done using the former parameter, like so:
The following are two equivalent examples and iterate over all weapons on the map:
 
{| width=100%
|- style="vertical-align:top;"
|
<source lang=js>
<source lang=js>
local ent = null                                         // The variable name "ent" is arbitrary. 'null' is the same as using 'Entities.First()'
local ent = null;
while ( ent = Entities.FindByClassname(ent, "weapon_*") ) // Assign the found entity with '=', which will be used again later.
while ( ent = Entities.FindByClassname(ent, "weapon_*") )
{
{
   // ...                                                  // In every iteration, "ent" is a weapon in the map and not null.
   // ...
}
}
</source>
</source>
|
<source lang=js>
for (local ent; ent = Entities.FindByClassname(ent, "weapon_*"); )
{
  // ...
}
</source>
|}
{{Note |
* The variable name <kbd>ent</kbd> is arbitrary.
* Indeed, we mean "{{=}}" and not "{{=}}{{=}}" in the loop conditions! The loops end if <kbd>ent</kbd> becomes <kbd>null</kbd>, 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 <kbd>for</kbd> statement.
* The string parameters of the <kbd>FindBy...</kbd> functions support the wildcard star <kbd>*</kbd>. In the above example, <kbd>FindByClassname</kbd> only returns either a handle of an entity whose classname begins with "<kbd>weapon_</kbd>" or it returns <kbd>null</kbd>.
}}


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>FindByClassname</code>
| <kbd>FindByClassname</kbd> || <kbd>handle FindByClassname(handle ''previous'', string ''class'')</kbd>
| <code>handle FindByClassname(handle ''previous'', string ''class'')</code>
| Find entities by class name.  
| Find entities by class name.  
|-
|-
| <code>FindByClassnameNearest</code>
| <kbd>FindByClassnameNearest</kbd> || <kbd>handle FindByClassnameNearest(string ''class'', Vector ''origin'', float ''radius'')</kbd>
| <code>handle FindByClassnameNearest(string ''class'', Vector ''origin'', float ''radius'')</code>
| Find the entity with the given class name nearest to the specified point.
| Find the entity with the given class name nearest to the specified point.
|-
|-
| <code>FindByClassnameWithin</code>
| <kbd>FindByClassnameWithin</kbd> || <kbd>handle FindByClassnameWithin(handle ''previous'', string ''class'', Vector ''origin'', float ''radius'')</kbd>
| <code>handle FindByClassnameWithin(handle ''previous'', string ''class'', Vector ''origin'', float ''radius'')</code>
| Find entities by class name within a radius, while within a set radius.  
| Find entities by class name within a radius, while within a set radius.  
|-
|-
| <code>FindByModel</code>
| <kbd>FindByModel</kbd> || <kbd>handle FindByModel(handle ''previous'', string ''filename'')</kbd>
| <code>handle FindByModel(handle ''previous'', string ''filename'')</code>
| Find entities by a model path name.  
| Find entities by a model path name.  
|-
|-
| <code>FindByName</code>
| <kbd>FindByName</kbd> || <kbd>handle FindByName(handle ''previous'', string ''name'')</kbd>
| <code>handle FindByName(handle ''previous'', string ''name'')</code>
| Find entities by targetname. Special ones including {{Code|!bill}} will work.  
| Find entities by targetname. Special ones including<code>!bill</code> will work.  
|-
|-
| <code>FindByNameNearest</code>
| <kbd>FindByNameNearest</kbd> || <kbd>handle FindByNameNearest(string ''name'', Vector ''origin'', float ''radius'')</kbd>
| <code>handle FindByNameNearest(string ''name'', Vector ''origin'', float ''radius'')</code>
| Find entities by targetname nearest to a point, while within a set radius. Special ones including {{Code|!bill}} will work.  
| Find entities by targetname nearest to a point, while within a set radius. Special ones including<code>!bill</code> will work.  
|-
|-
| <code>FindByNameWithin</code>
| <kbd>FindByNameWithin</kbd> || <kbd>handle FindByNameWithin(handle ''previous'', string ''name'', Vector ''origin'', float ''radius'')</kbd>
| <code>handle FindByNameWithin(handle ''previous'', string ''name'', Vector ''origin'', float ''radius'')</code>
| Find entities by targetname within a radius. Special ones including {{Code|!bill}} will work.
| Find entities by targetname within a radius. Special ones including<code>!bill</code> will work.
|-
|-
| <code>FindByTarget</code>
| <kbd>FindByTarget</kbd> || <kbd>handle FindByTarget(handle ''previous'', string ''targetname'')</kbd>
| <code>handle FindByTarget(handle ''previous'', string ''targetname'')</code>
| Find entities by its target.
| Find entities by its target.
|-
|-
| <code>FindInSphere</code>
| <kbd>FindInSphere</kbd> || <kbd>handle FindInSphere(handle ''previous'', Vector ''origin'', float ''radius'')</kbd>
| <code>handle FindInSphere(handle ''previous'', Vector ''origin'', float ''radius'')</code>
| Returns entities within a set radius.
| Returns entities within a set radius.
|-
|-
| <code>First</code>
| <kbd>First</kbd> || <kbd>handle First()</kbd>
| <code>handle First()</code>
| The first entity that spawned (Always <kbd>worldspawn</kbd>). Can be used to begin an iteration for a list of entities.
| The first entity that spawned (Always<code>worldspawn</code>). Can be used to begin an iteration for a list of entities.
|-
|-
| <code>Next</code>
| <kbd>Next</kbd> || <kbd>handle Next(handle ''previous'')</kbd>
| <code>handle Next(handle ''previous'')</code>
| At the given reference of a previously-found entity, returns the next one after it in the list.
| Continue an iteration over the list of entities, providing reference to a previously found entity.
|-
|-
| <code>IsValid</code>
| <kbd>IsValid</kbd> || <kbd>bool IsValid()</kbd>
| <code>bool IsValid()</code>
| Whether the handle for <kbd>Entities</kbd> is a valid handle.
| Whether the handle for<code>Entities</code>belongs to a valid entity.
|}
|}
<!--
<!--
Line 1,210: Line 987:


=== CEnvEntityMaker ===
=== CEnvEntityMaker ===
Extends [[#CBaseEntity|CBaseEntity]]
{{↑|toc}}
Extends {{↑|CBaseEntity}}


Script handle class for [[env_entity_maker]].  
Script handle class for [[env_entity_maker]].  
Line 1,216: Line 994:
==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>SpawnEntity</code>
| <kbd>SpawnEntity</kbd> || <kbd>void SpawnEntity()</kbd>
| <code>void SpawnEntity()</code>
| Create an entity at the location of the maker.
| Create an entity at the location of the maker.
|-
|-
| <code>SpawnEntityAtEntityOrigin</code>
| <kbd>SpawnEntityAtEntityOrigin</kbd> || <kbd>void SpawnEntityAtEntityOrigin(CBaseEntity ''entity'')</kbd>
| <code>void SpawnEntityAtEntityOrigin(CBaseEntity ''entity'')</code>
| Create an entity at the location of a specified entity instance.
| Create an entity at the location of a specified entity instance.
|-
|-
| <code>SpawnEntityAtLocation</code>
| <kbd>SpawnEntityAtLocation</kbd> || <kbd>void SpawnEntityAtLocation(Vector ''origin'', QAngle ''orientation'')</kbd>
| <code>void SpawnEntityAtLocation(Vector ''origin'', QAngle ''orientation'')</code>
| Create an entity at a specified location and orientation.
| Create an entity at a specified location and orientation.
|-
|-
| <code>SpawnEntityAtNamedEntityOrigin</code>
| <kbd>SpawnEntityAtNamedEntityOrigin</kbd> || <kbd>void SpawnEntityAtNamedEntityOrigin(string ''name'')</kbd>
| <code>void SpawnEntityAtNamedEntityOrigin(string ''name'')</code>
| Create an entity at the location of a named entity.
| Create an entity at the location of a named entity.
|}
|}
Line 1,239: Line 1,011:


=== CInfoItemPosition ===
=== CInfoItemPosition ===
Extends [[#CBaseEntity|CBaseEntity]]
{{↑|toc}}
Extends {{↑|CBaseEntity}}


Script handle class for [[info_item_position]].
Script handle class for [[info_item_position]].
Line 1,245: Line 1,018:
==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>GetGroup</code>
| <kbd>GetGroup</kbd> ||  
|  
| Get the group number for this item position
| Get the group number for this item position
|-
|-
| <code>GetRarity</code>
| <kbd>GetRarity</kbd> ||  
|  
| Get the rarity for this item position.
| Get the rarity for this item position.
|-
|-
| <code>GetReplaceParm</code>
| <kbd>GetReplaceParm</kbd> ||  
|  
| Get a replacement parameter by index.
| Get a replacement parameter by index.
|-
|-
| <code>SetGroup</code>
| <kbd>SetGroup</kbd> ||  
|  
| Set the group number for this item position.
| Set the group number for this item position.
|-
|-
| <code>SetRarity</code>
| <kbd>SetRarity</kbd> ||  
|  
| Set the rarity for this item position.
| Set the rarity for this item position.
|}
|}


=== CNavMesh ===
{{↑|toc}}
{{↑|Instances}} Game Instance: <kbd>NavMesh</kbd>


=== TerrorNavArea ===
An interface to the Navigation Mesh.
This is a script handle class for nav areas.


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>AddIncomingConnection</code>
| <kbd>FindLadderAlongRay</kbd> || <kbd>CNavLadder FindLadderAlongRay(Vector ''startpos'', Vector ''endpos'', TerrorNavArea ''ignoreArea'')</kbd>
| <code>void AddIncomingConnection(TerrorNavArea ''area'', int ''dir'')</code>
| Get nav ladder from ray.
| Add areas that connect TO this area by a ONE-WAY link.
|-
|-
| <code>ComputeDirection</code>
| <kbd>FindNavAreaAlongRay</kbd> || <kbd>TerrorNavArea FindNavAreaAlongRay(Vector ''startpos'', Vector ''endpos'', TerrorNavArea ''ignoreArea'')</kbd>
| <code>int ComputeDirection(Vector ''point'')</code>
| Get nav area from ray.
| Return direction from this area to the given point.
|-
|-
| <code>ConnectTo</code>
| <kbd>GetAllAreas</kbd> || <kbd>void GetAllAreas(table)</kbd>
| <code>void ConnectTo(TerrorNavArea ''area'', int ''dir'')</code>
| Fills a passed in table of all nav areas.
| Connect this area to given area in given direction. If you set direction to -1, it will be automatically applied.
|-
|-
| <code>ConnectToLadder</code>
| <kbd>GetAllLadders</kbd> || <kbd>void GetAllLadders(table)</kbd>
| <code>void ConnectToLadder(CNavLadder ''ladder'')</code>
| Fills a passed in table of all nav ladders.
| Connect this area to given ladder.
|-
|-
| <code>Contains</code>
| <kbd>GetAreasWithAttributes</kbd> || <kbd>void GetAreasWithAttributes(int ''bits'', table)</kbd>
| <code>bool Contains(TerrorNavArea ''area'')</code>
| Fills a passed in table of all nav areas that have the specified attributes.
| Return true if other area is on or above this area, but no others.
|-
|-
| <code>ContainsOrigin</code>
| <kbd>GetLadderByID</kbd> || <kbd>CNavLadder GetLadderByID(int ''id'')</kbd>
| <code>bool ContainsOrigin(Vector ''point'')</code>
| Get nav ladder by ID.
| Return true if given point is on or above this area, but no others.
|-
|-
| <code>DebugDrawFilled</code>
| <kbd>GetLadderCount</kbd> || <kbd>int GetLadderCount()</kbd>
| <code>void DebugDrawFilled(int ''r'', int ''g'', int ''b'', int ''a'', float ''duration'', bool ''noDepthTest'')</code>
| Return total number of nav ladders.
| Draw area as a filled rectangle of the given color.
|-
|-
| <code>Disconnect</code>
| <kbd>GetNavArea</kbd> || <kbd>TerrorNavArea GetNavArea(Vector ''origin'', float ''flBeneath'')</kbd>
| <code>void Disconnect(TerrorNavArea ''area'')</code>
| Given a position in the world, return the nav area that is closest and at the same height, or beneath it.
| Disconnect this area from given area.
|-
|-
| <code>DisconnectLadder</code>
| <kbd>GetNavAreaByID</kbd> || <kbd>TerrorNavArea GetNavAreaByID(int ''id'')</kbd>
| <code>void DisconnectLadder(CNavLadder ''ladder'')</code>
| Get nav area by ID.
| Disconnect this area from given ladder.
|-
|-
| <code>FindRandomSpot</code>
| <kbd>GetNavAreaCount</kbd> || <kbd>int GetNavAreaCount()</kbd>
| <code>Vector FindRandomSpot()</code>
| Return total number of nav areas.
| Get random origin within extent of area.
|-
|-
| <code>GetAdjacentArea</code>
| <kbd>GetNavAreasFromBuildPath</kbd> || <kbd>bool GetNavAreasFromBuildPath(TerrorNavArea ''startArea'', TerrorNavArea ''endArea'', Vector ''goalPos'', float ''flMaxPathLength'', int ''teamID'', bool ''ignoreNavBlockers'', table)</kbd>
| <code>TerrorNavArea GetAdjacentArea(int ''dir'', int ''nAreas'')</code>
| Fills table with areas from a path. Returns whether a path was found. If 'endArea' is NULL, will compute a path as close as possible to 'goalPos'.
| Return the n'th adjacent area in the given direction.
|-
|-
| <code>GetAdjacentAreas</code>
| <kbd>GetNavAreasInRadius</kbd> || <kbd>void GetNavAreasInRadius(Vector ''origin'', float ''radius'', table)</kbd>
| <code>void GetAdjacentAreas(int ''dir'', table)</code>
| Fills a passed in table of nav areas within radius.
| Fills a passed in table with all adjacent areas in the given direction.
|-
|-
| <code>GetAdjacentCount</code>
| <kbd>GetNavAreasOverlappingEntityExtent</kbd> || <kbd>void GetNavAreasOverlappingEntityExtent(CBaseEntity ''entity'', table)</kbd>
| <code>int GetAdjacentCount(int ''dir'')</code>
| Fills passed in table with areas overlapping entity's extent.
| Get the number of adjacent areas in the given direction.
|-
|-
| <code>GetAttributes</code>
| <kbd>GetNearestNavArea</kbd> || <kbd>TerrorNavArea GetNearestNavArea(Vector ''origin'', float ''maxDist'', bool ''checkLOS'', bool ''checkGround'')</kbd>
| <code>int GetAttributes()</code>
| Given a position in the world, return the nav area that is closest and at the same height, or beneath it.
| Get area attribute bits.
|-
|-
| <code>GetAvoidanceObstacleHeight</code>
| <kbd>GetObstructingEntities</kbd> || <kbd>void GetObstructingEntities(table)</kbd>
| <code>float GetAvoidanceObstacleHeight()</code>
| Fills a passed in table of all obstructing entities.
| Returns the maximum height of the obstruction above the ground.
|-
|-
| <code>GetCenter</code>
| <kbd>IsValid</kbd> || <kbd>bool IsValid()</kbd>
| <code>Vector GetCenter()</code>
| Whether the handle belongs to a valid entity. Redundant as navigation meshes are not entity related.
| Get center origin of area.
|-
|-
| <code>GetCorner</code>
| <kbd>NavAreaBuildPath</kbd> || <kbd>bool NavAreaBuildPath(TerrorNavArea ''startArea'', TerrorNavArea ''endArea'', Vector ''goalPos'', float ''flMaxPathLength'', int ''teamID'', bool ''ignoreNavBlockers'')</kbd>
| <code>Vector GetCorner(int ''corner'')</code>
| Returns true if a path exists. If 'endArea' is NULL, will compute a path as close as possible to 'goalPos'.
| Get corner origin of area.
|-
|-
| <code>GetDistanceSquaredToPoint</code>
| <kbd>NavAreaTravelDistance</kbd> || <kbd>float NavAreaTravelDistance(TerrorNavArea ''startArea'', TerrorNavArea ''endArea'', float ''flMaxPathLength'')</kbd>
| <code>float GetDistanceSquaredToPoint(Vector ''pos'')</code>
| Compute distance between two areas. Return -1 if can't reach 'endArea' from 'startArea'.
| Return shortest distance between point and this area.
|-
|-
| <code>GetDoor</code>
| <kbd>RegisterAvoidanceObstacle</kbd> || <kbd>void RegisterAvoidanceObstacle(CBaseEntity ''entity'')</kbd>
| <code>CBaseEntity GetDoor()</code>
| Registers an entity as an avoidance obstacle.
| Returns the door entity above the area.
|-
|-
| <code>GetElevator</code>
| <kbd>UnblockRescueVehicleNav</kbd> || <kbd>void UnblockRescueVehicleNav()</kbd>
| <code>CBaseEntity GetElevator()</code>
| Unblock the rescue vehicle nav areas so bots can path through them.
| Returns the elevator if in an elevator's path.
|-
|-
| <code>GetElevatorAreas</code>
| <kbd>UnregisterAvoidanceObstacle</kbd> || <kbd>void UnregisterAvoidanceObstacle(CBaseEntity ''entity'')</kbd>
| <code>void GetElevatorAreas(table)</code>
| Unregisters an entity as an avoidance obstacle.
| Fills a passed in table with a collection of areas reachable via elevator from this area.
|}
 
=== TerrorNavArea ===
{{↑|toc}}
This is a script handle class for nav areas. Nav areas may also have [[List_of_L4D_Series_Nav_Mesh_Attributes|attributes]] applied on them.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
|-
| <code>GetID</code>
| <kbd>AddIncomingConnection</kbd> || <kbd>void AddIncomingConnection(TerrorNavArea ''area'', int ''dir'')</kbd>
| <code>int GetID()</code>
| Add areas that connect TO this area by a ONE-WAY link.
| Get area ID.
|-
|-
| <code>GetIncomingConnections</code>
| <kbd>ComputeDirection</kbd> || <kbd>int ComputeDirection(Vector ''point'')</kbd>
| <code>void GetIncomingConnections(int ''dir'', table)</code>
| Return direction from this area to the given point.
| 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>GetLadders</code>
| <kbd>ConnectTo</kbd> || <kbd>void ConnectTo(TerrorNavArea ''area'', int ''dir'')</kbd>
| <code>void GetLadders(int ''dir'', table)</code>
| Connect this area to given area in given direction. If you set direction to -1, it will be automatically applied.
| Fills a passed in table of ladders in direction.
|-
|-
| <code>GetParent</code>
| <kbd>ConnectToLadder</kbd> || <kbd>void ConnectToLadder(CNavLadder ''ladder'')</kbd>
| <code>TerrorNavArea GetParent()</code>
| Connect this area to given ladder.
| Returns the area just prior to this one in the search path.
|-
|-
| <code>GetParentHow</code>
| <kbd>Contains</kbd> || <kbd>bool Contains(TerrorNavArea ''area'')</kbd>
| <code>int GetParentHow()</code>
| Return true if other area is on or above this area, but no others.
| Returns how we get from parent to us.
|-
|-
| <code>GetPlaceName</code>
| <kbd>ContainsOrigin</kbd> || <kbd>bool ContainsOrigin(Vector ''point'')</kbd>
| <code>string GetPlaceName()</code>
| Return true if given point is on or above this area, but no others.
| Get place name, null if no name.
|-
|-
| <code>GetPlayerCount</code>
| <kbd>DebugDrawFilled</kbd> || <kbd>void DebugDrawFilled(int ''r'', int ''g'', int ''b'', int ''a'', float ''duration'', bool ''noDepthTest'')</kbd>
| <code>int GetPlayerCount(int ''team'')</code>
| Draw area as a filled rectangle of the given color.
| Return number of players of given team currently within this area (team of zero means any/all).
|-
|-
| <code>GetRandomAdjacentArea</code>
| <kbd>Disconnect</kbd> || <kbd>void Disconnect(TerrorNavArea ''area'')</kbd>
| <code>TerrorNavArea GetRandomAdjacentArea(int ''dir'')</code>
| Disconnect this area from given area.
| Return a random adjacent area in the given direction.
|-
|-
| <code>GetSizeX</code>
| <kbd>DisconnectLadder</kbd> || <kbd>void DisconnectLadder(CNavLadder ''ladder'')</kbd>
| <code>float GetSizeX()</code>
| Disconnect this area from given ladder.
| Return the area size along the X axis.
|-
|-
| <code>GetSizeY</code>
| <kbd>FindRandomSpot</kbd> || <kbd>Vector FindRandomSpot()</kbd>
| <code>float GetSizeY()</code>
| Get random origin within extent of area.
| Return the area size along the Y axis.
|-
|-
| <code>GetSpawnAttributes</code>
| <kbd>GetAdjacentArea</kbd> || <kbd>TerrorNavArea GetAdjacentArea(int ''dir'', int ''nAreas'')</kbd>
| <code>int GetSpawnAttributes()</code>
| Return the n'th adjacent area in the given direction.
| Get spawn attribute bits.
|-
|-
| <code>GetTimeSinceCleared</code>
| <kbd>GetAdjacentAreas</kbd> || <kbd>void GetAdjacentAreas(int ''dir'', table)</kbd>
| <code>float GetTimeSinceCleared()</code>
| Fills a passed in table with all adjacent areas in the given direction.
| Returns the time since the area was cleared.
|-
|-
| <code>GetZ</code>
| <kbd>GetAdjacentCount</kbd> || <kbd>int GetAdjacentCount(int ''dir'')</kbd>
| <code>float GetZ(Vector ''pos'')</code>
| Get the number of adjacent areas in the given direction.
| Returns the height of the area at the specified point.
|-
|-
| <code>HasAttributes</code>
| <kbd>GetAttributes</kbd> || <kbd>int GetAttributes()</kbd>
| <code>bool HasAttributes(int ''bits'')</code>
| Get area attribute bits.
| Has area attribute bits.
|-
|-
| <code>HasAvoidanceObstacle</code>
| <kbd>GetAvoidanceObstacleHeight</kbd> || <kbd>float GetAvoidanceObstacleHeight()</kbd>
| <code>bool HasAvoidanceObstacle(float ''maxHeight'')</code>
| Returns the maximum height of the obstruction above the ground.
| Returns true if there's a large, immobile object obstructing this area.
|-
|-
| <code>HasSpawnAttributes</code>
| <kbd>GetCenter</kbd> || <kbd>Vector GetCenter()</kbd>
| <code>bool HasSpawnAttributes(int ''bits'')</code>
| Get center origin of area.
| Has spawn attribute bits.
|-
|-
| <code>IsBlocked</code>
| <kbd>GetCorner</kbd> || <kbd>Vector GetCorner(int ''corner'')</kbd>
| <code>bool IsBlocked(int ''team'', bool ''affectsFlow'')</code>
| Get corner origin of area.
| Return true if team is blocked in this area.
|-
|-
| <code>IsBottleneck</code>
| <kbd>GetDistanceSquaredToPoint</kbd> || <kbd>float GetDistanceSquaredToPoint(Vector ''pos'')</kbd>
| <code>bool IsBottleneck()</code>
| Return shortest distance between point and this area.
| Returns true if area is a bottleneck.
|-
|-
| <code>IsCleared</code>
| <kbd>GetDoor</kbd> || <kbd>CBaseEntity GetDoor()</kbd>
| <code>bool IsCleared(CTerrorPlayer ''player'')</code>
| Returns the door entity above the area.
| Returns true if this area has been cleared for the player.
|-
|-
| <code>IsCompletelyVisibleToTeam</code>
| <kbd>GetElevator</kbd> || <kbd>CBaseEntity GetElevator()</kbd>
| <code>bool IsCompletelyVisibleToTeam(int ''team'')</code>
| Returns the elevator if in an elevator's path.
| Return true if given area is completely visible from somewhere in this area by someone on the team.
|-
|-
| <code>IsConnected</code>
| <kbd>GetElevatorAreas</kbd> || <kbd>void GetElevatorAreas(table)</kbd>
| <code>bool IsConnected(TerrorNavArea ''area'', int ''dir'')</code>
| Fills a passed in table with a collection of areas reachable via elevator from this area.
| 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>IsConnectedLadder</code>
| <kbd>GetID</kbd> || <kbd>int GetID()</kbd>
| <code>bool IsConnectedLadder(CNavLadder ''ladder'', int ''dir'')</code>
| Get area ID.
| Return true if this area is connected to ladder in given direction.
|-
|-
| <code>IsCoplanar</code>
| <kbd>GetIncomingConnections</kbd> || <kbd>void GetIncomingConnections(int ''dir'', table)</kbd>
| <code>bool IsCoplanar(TerrorNavArea ''area'')</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).
| Return true if this area and given area are approximately co-planar.
|-
|-
| <code>IsDamaging</code>
| <kbd>GetLadders</kbd> || <kbd>void GetLadders(int ''dir'', table)</kbd>
| <code>bool IsDamaging()</code>
| Fills a passed in table of ladders in direction.
| Return true if continuous damage (ie: fire) is in this area.
|-
|-
| <code>IsDegenerate</code>
| <kbd>GetParent</kbd> || <kbd>TerrorNavArea GetParent()</kbd>
| <code>bool IsDegenerate()</code>
| Returns the area just prior to this one in the search path.
| Return true if this area is badly formed.
|-
|-
| <code>IsEdge</code>
| <kbd>GetParentHow</kbd> || <kbd>int GetParentHow()</kbd>
| <code>bool IsEdge(int ''dir'')</code>
| Returns how we get from parent to us.
| Return true if there are no bi-directional links on the given side.
|-
|-
| <code>IsFlat</code>
| <kbd>GetPlaceName</kbd> || <kbd>string GetPlaceName()</kbd>
| <code>bool IsFlat()</code>
| Get place name, null if no name.
| Return true if this area is approximately flat.
|-
|-
| <code>IsOverlapping</code>
| <kbd>GetPlayerCount</kbd> || <kbd>int GetPlayerCount(int ''team'')</kbd>
| <code>bool IsOverlapping(TerrorNavArea ''area'')</code>
| Return number of players of given team currently within this area (team of zero means any/all).
| Return true if 'area' overlaps our 2D extents.
|-
|-
| <code>IsOverlappingOrigin</code>
| <kbd>GetRandomAdjacentArea</kbd> || <kbd>TerrorNavArea GetRandomAdjacentArea(int ''dir'')</kbd>
| <code>bool IsOverlappingOrigin(Vector ''pos'', float ''tolerance'')</code>
| Return a random adjacent area in the given direction.
| Return true if 'pos' is within 2D extents of area.
|-
|-
| <code>IsPotentiallyVisibleToTeam</code>
| <kbd>GetSizeX</kbd> || <kbd>float GetSizeX()</kbd>
| <code>bool IsPotentiallyVisibleToTeam(int ''team'')</code>
| Return the area size along the X axis.
| Return true if any portion of this area is visible to anyone on the given team.
|-
|-
| <code>IsRoughlySquare</code>
| <kbd>GetSizeY</kbd> || <kbd>float GetSizeY()</kbd>
| <code>bool IsRoughlySquare()</code>
| Return the area size along the Y axis.
| Return true if this area is approximately square.
|-
|-
| <code>IsSpawningAllowed</code>
| <kbd>GetSpawnAttributes</kbd> || <kbd>int GetSpawnAttributes()</kbd>
| <code>bool IsSpawningAllowed()</code>
| Get spawn attribute bits.
| Returns true if spawning is allowed in this area.
|-
|-
| <code>IsUnderwater</code>
| <kbd>GetTimeSinceCleared</kbd> || <kbd>float GetTimeSinceCleared()</kbd>
| <code>bool IsUnderwater()</code>
| Returns the time since the area was cleared.
| Return true if area is underwater.
|-
|-
| <code>IsValid</code>
| <kbd>GetZ</kbd> || <kbd>float GetZ(Vector ''pos'')</kbd>
| <code>bool IsValid()</code>
| Returns the height of the area at the specified point.
| Whether the handle belongs to a valid area.
|-
|-
| <code>IsValidForWanderingPopulation</code>
| <kbd>HasAttributes</kbd> || <kbd>bool HasAttributes(int ''bits'')</kbd>
| <code>bool IsValidForWanderingPopulation()</code>
| Has area attribute bits.
| Returns true if area is valid for wandering population.
|-
|-
| <code>IsVisible</code>
| <kbd>HasAvoidanceObstacle</kbd> || <kbd>bool HasAvoidanceObstacle(float ''maxHeight'')</kbd>
| <code>bool IsVisible(Vector ''point'')</code>
| Returns true if there's a large, immobile object obstructing this area.
| Return true if area is visible from the given point.
|-
|-
| <code>MarkAreaCleared</code>
| <kbd>HasSpawnAttributes</kbd> || <kbd>bool HasSpawnAttributes(int ''bits'')</kbd>
| <code>void MarkAreaCleared(CTerrorPlayer ''player'')</code>
| Has spawn attribute bits.
| Mark this area as cleared for the player.
|-
|-
| <code>MarkAreaNotCleared</code>
| <kbd>IsBlocked</kbd> || <kbd>bool IsBlocked(int ''team'', bool ''affectsFlow'')</kbd>
| <code>void MarkAreaNotCleared()</code>
| Return true if team is blocked in this area.
| Mark this area as not cleared.
|-
|-
| <code>MarkAsBlocked</code>
| <kbd>IsBottleneck</kbd> || <kbd>bool IsBottleneck()</kbd>
| <code>void MarkAsBlocked(int ''team'')</code>
| Returns true if area is a bottleneck.
| Mark this area as blocked for team.
|-
|-
| <code>MarkAsDamaging</code>
| <kbd>IsCleared</kbd> || <kbd>bool IsCleared(CTerrorPlayer ''player'')</kbd>
| <code>void MarkAsDamaging(float ''duration'')</code>
| Returns true if this area has been cleared for the player.
| Mark this area is damaging for the next 'duration' seconds.
|-
|-
| <code>MarkObstacleToAvoid</code>
| <kbd>IsCompletelyVisibleToTeam</kbd> || <kbd>bool IsCompletelyVisibleToTeam(int ''team'')</kbd>
| <code>void MarkObstacleToAvoid(float ''height'')</code>
| Return true if given area is completely visible from somewhere in this area by someone on the team.
| Marks the obstructed status of the nav area.
|-
|-
| <code>RemoveAttributes</code>
| <kbd>IsConnected</kbd> || <kbd>bool IsConnected(TerrorNavArea ''area'', int ''dir'')</kbd>
| <code>void RemoveAttributes(int ''bits'')</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)
| Removes area attribute bits.
|-
|-
| <code>RemoveOrthogonalConnections</code>
| <kbd>IsConnectedLadder</kbd> || <kbd>bool IsConnectedLadder(CNavLadder ''ladder'', int ''dir'')</kbd>
| <code>void RemoveOrthogonalConnections(int ''dir'')</code>
| Return true if this area is connected to ladder in given direction.
| Removes all connections in directions to left and right of specified direction.
|-
|-
| <code>RemoveSpawnAttributes</code>
| <kbd>IsCoplanar</kbd> || <kbd>bool IsCoplanar(TerrorNavArea ''area'')</kbd>
| <code>void RemoveSpawnAttributes(int ''bits'')</code>
| Return true if this area and given area are approximately co-planar.
| Remove spawn attribute bits.
|-
|-
| <code>SetAttributes</code>
| <kbd>IsDamaging</kbd> || <kbd>bool IsDamaging()</kbd>
| <code>void SetAttributes(int ''bits'')</code>
| Return true if continuous damage (ie: fire) is in this area.
| Set area attribute bits.
|-
|-
| <code>SetPlaceName</code>
| <kbd>IsDegenerate</kbd> || <kbd>bool IsDegenerate()</kbd>
| <code>void SetPlaceName(string ''name'')</code>
| Return true if this area is badly formed.
| Set place name. If you pass null, the place name will be set to nothing.
|-
|-
| <code>SetSpawnAttributes</code>
| <kbd>IsEdge</kbd> || <kbd>bool IsEdge(int ''dir'')</kbd>
| <code>void SetSpawnAttributes(int ''bits'')</code>
| Return true if there are no bi-directional links on the given side.
| Set spawn attribute bits.
|-
|-
| <code>UnblockArea</code>
| <kbd>IsFlat</kbd> || <kbd>bool IsFlat()</kbd>
| <code>void UnblockArea()</code>
| Return true if this area is approximately flat.
| Unblocks this area.
|}
 
=== CNavLadder ===
This is a script handle class for nav ladders.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function
! Signature
! Description
|-
|-
| <code>ConnectTo</code>
| <kbd>IsOverlapping</kbd> || <kbd>bool IsOverlapping(TerrorNavArea ''area'')</kbd>
| <code>void ConnectTo(TerrorNavArea ''area'')</code>
| Return true if 'area' overlaps our 2D extents.
| Connect this ladder to given area.
|-
|-
| <code>Disconnect</code>
| <kbd>IsOverlappingOrigin</kbd> || <kbd>bool IsOverlappingOrigin(Vector ''pos'', float ''tolerance'')</kbd>
| <code>void Disconnect(TerrorNavArea ''area'')</code>
| Return true if 'pos' is within 2D extents of area.
| Disconnect this ladder from given area.
|-
|-
| <code>GetBottomArea</code>
| <kbd>IsPotentiallyVisibleToTeam</kbd> || <kbd>bool IsPotentiallyVisibleToTeam(int ''team'')</kbd>
| <code>TerrorNavArea GetBottomArea()</code>
| Return true if any portion of this area is visible to anyone on the given team.
| Area of the bottom of the ladder.
|-
|-
| <code>GetBottomOrigin</code>
| <kbd>IsRoughlySquare</kbd> || <kbd>bool IsRoughlySquare()</kbd>
| <code>Vector GetBottomOrigin()</code>
| Return true if this area is approximately square.
| World coords of the bottom of the ladder.
|-
|-
| <code>GetDir</code>
| <kbd>IsSpawningAllowed</kbd> || <kbd>bool IsSpawningAllowed()</kbd>
| <code>int GetDir()</code>
| Returns true if spawning is allowed in this area.
| Return the way the ladder faces (ie: surface normal of climbable side).
|-
|-
| <code>GetID</code>
| <kbd>IsUnderwater</kbd> || <kbd>bool IsUnderwater()</kbd>
| <code>int GetID()</code>
| Return true if area is underwater.
| Get ladder ID.
|-
|-
| <code>GetLadderEntity</code>
| <kbd>IsValid</kbd> || <kbd>bool IsValid()</kbd>
| <code>CBaseEntity GetLadderEntity()</code>
| Whether the handle belongs to a valid area.
| Returns the ladder entity.
|-
|-
| <code>GetLength</code>
| <kbd>IsValidForWanderingPopulation</kbd> || <kbd>bool IsValidForWanderingPopulation()</kbd>
| <code>float GetLength()</code>
| Returns true if area is valid for wandering population.
| Return the length of the ladder.
|-
|-
| <code>GetPosAtHeight</code>
| <kbd>IsVisible</kbd> || <kbd>bool IsVisible(Vector ''point'')</kbd>
| <code>Vector GetPosAtHeight(float ''height'')</code>
| Return true if area is visible from the given point.
| Return x,y coordinate of the ladder at a given height.
|-
|-
| <code>GetTopArea</code>
| <kbd>MarkAreaCleared</kbd> || <kbd>void MarkAreaCleared(CTerrorPlayer ''player'')</kbd>
| <code>TerrorNavArea GetTopArea()</code>
| Mark this area as cleared for the player.
| Area of the top of the ladder.
|-
|-
| <code>GetTopOrigin</code>
| <kbd>MarkAreaNotCleared</kbd> || <kbd>void MarkAreaNotCleared()</kbd>
| <code>Vector GetTopOrigin()</code>
| Mark this area as not cleared.
| World coords of the top of the ladder.
|-
|-
| <code>GetWidth</code>
| <kbd>MarkAsBlocked</kbd> || <kbd>void MarkAsBlocked(int ''team'')</kbd>
| <code>float GetWidth()</code>
| Mark this area as blocked for team.
| Return the width of the ladder.
|-
|-
| <code>IsConnected</code>
| <kbd>MarkAsDamaging</kbd> || <kbd>void MarkAsDamaging(float ''duration'')</kbd>
| <code>bool IsConnected(TerrorNavArea ''area'', int ''dir'')</code>
| Mark this area is damaging for the next 'duration' seconds.
| Return true if given ladder is connected in given direction.
|-
|-
| <code>IsInUse</code>
| <kbd>MarkObstacleToAvoid</kbd> || <kbd>void MarkObstacleToAvoid(float ''height'')</kbd>
| <code>bool IsInUse(CBaseEntity ''ignore'')</code>
| Marks the obstructed status of the nav area.
| Return true if someone is on this ladder (other than 'ignore').
|-
|-
| <code>IsUsableByTeam</code>
| <kbd>RemoveAttributes</kbd> || <kbd>void RemoveAttributes(int ''bits'')</kbd>
| <code>bool IsUsableByTeam(int ''teamID'')</code>
| Removes area attribute bits.
| Returns true if ladder is usable for team.
|-
|-
| <code>IsValid</code>
| <kbd>RemoveOrthogonalConnections</kbd> || <kbd>void RemoveOrthogonalConnections(int ''dir'')</kbd>
| <code>bool IsValid()</code>
| Removes all connections in directions to left and right of specified direction.
| Whether the handle belongs to a valid ladder.
|-
| <kbd>RemoveSpawnAttributes</kbd> || <kbd>void RemoveSpawnAttributes(int ''bits'')</kbd>
| Remove spawn attribute bits.
|-
| <kbd>SetAttributes</kbd> || <kbd>void SetAttributes(int ''bits'')</kbd>
| Set area attribute bits.
|-
| <kbd>SetPlaceName</kbd> || <kbd>void SetPlaceName(string ''name'')</kbd>
| Set place name. If you pass null, the place name will be set to nothing.
|-
| <kbd>SetSpawnAttributes</kbd> || <kbd>void SetSpawnAttributes(int ''bits'')</kbd>
| Set spawn attribute bits.
|-
| <kbd>UnblockArea</kbd> || <kbd>void UnblockArea()</kbd>
| Unblocks this area.
|}
|}


=== CNavMesh ===
=== CNavLadder ===
Game Instance: <code>NavMesh</code>
{{↑|toc}}
This is a script handle class for nav ladders.


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>FindLadderAlongRay</code>
| <kbd>ConnectTo</kbd> || <kbd>void ConnectTo(TerrorNavArea ''area'')</kbd>
| <code>CNavLadder FindLadderAlongRay(Vector ''startpos'', Vector ''endpos'', TerrorNavArea ''ignoreArea'')</code>
| Connect this ladder to given area.
| Get nav ladder from ray.
|-
|-
| <code>FindNavAreaAlongRay</code>
| <kbd>Disconnect</kbd> || <kbd>void Disconnect(TerrorNavArea ''area'')</kbd>
| <code>TerrorNavArea FindNavAreaAlongRay(Vector ''startpos'', Vector ''endpos'', TerrorNavArea ''ignoreArea'')</code>
| Disconnect this ladder from given area.
| Get nav area from ray.
|-
|-
| <code>GetAllAreas</code>
| <kbd>GetBottomArea</kbd> || <kbd>TerrorNavArea GetBottomArea()</kbd>
| <code>void GetAllAreas(table)</code>
| Area of the bottom of the ladder.
| Fills a passed in table of all nav areas.
|-
|-
| <code>GetAllLadders</code>
| <kbd>GetBottomOrigin</kbd> || <kbd>Vector GetBottomOrigin()</kbd>
| <code>void GetAllLadders(table)</code>
| World coords of the bottom of the ladder.
| Fills a passed in table of all nav ladders.
|-
|-
| <code>GetAreasWithAttributes</code>
| <kbd>GetDir</kbd> || <kbd>int GetDir()</kbd>
| <code>void GetAreasWithAttributes(int ''bits'', table)</code>
| Return the way the ladder faces (ie: surface normal of climbable side).
| Fills a passed in table of all nav areas that have the specified attributes.
|-
|-
| <code>GetLadderByID</code>
| <kbd>GetID</kbd> || <kbd>int GetID()</kbd>
| <code>CNavLadder GetLadderByID(int ''id'')</code>
| Get ladder ID.
| Get nav ladder by ID.
|-
|-
| <code>GetLadderCount</code>
| <kbd>GetLadderEntity</kbd> || <kbd>CBaseEntity GetLadderEntity()</kbd>
| <code>int GetLadderCount()</code>
| Returns the ladder entity.
| Return total number of nav ladders.
|-
|-
| <code>GetNavArea</code>
| <kbd>GetLength</kbd> || <kbd>float GetLength()</kbd>
| <code>TerrorNavArea GetNavArea(Vector ''origin'', float ''flBeneath'')</code>
| Return the length of the ladder.
| Given a position in the world, return the nav area that is closest and at the same height, or beneath it.
|-
|-
| <code>GetNavAreaByID</code>
| <kbd>GetPosAtHeight</kbd> || <kbd>Vector GetPosAtHeight(float ''height'')</kbd>
| <code>TerrorNavArea GetNavAreaByID(int ''id'')</code>
| Return x,y coordinate of the ladder at a given height.
| Get nav area by ID.
|-
|-
| <code>GetNavAreaCount</code>
| <kbd>GetTopArea</kbd> || <kbd>TerrorNavArea GetTopArea()</kbd>
| <code>int GetNavAreaCount()</code>
| Area of the top of the ladder.
| Return total number of nav areas.
|-
|-
| <code>GetNavAreasFromBuildPath</code>
| <kbd>GetTopOrigin</kbd> || <kbd>Vector GetTopOrigin()</kbd>
| <code>bool GetNavAreasFromBuildPath(TerrorNavArea ''startArea'', TerrorNavArea ''endArea'', Vector ''goalPos'', float ''flMaxPathLength'', int ''teamID'', bool ''ignoreNavBlockers'', table)</code>
| World coords of the top of the ladder.
| Fills table with areas from a path. Returns whether a path was found. If 'endArea' is NULL, will compute a path as close as possible to 'goalPos'.
|-
|-
| <code>GetNavAreasInRadius</code>
| <kbd>GetWidth</kbd> || <kbd>float GetWidth()</kbd>
| <code>void GetNavAreasInRadius(Vector ''origin'', float ''radius'', table)</code>
| Return the width of the ladder.
| Fills a passed in table of nav areas within radius.
|-
|-
| <code>GetNavAreasOverlappingEntityExtent</code>
| <kbd>IsConnected</kbd> || <kbd>bool IsConnected(TerrorNavArea ''area'', int ''dir'')</kbd>
| <code>void GetNavAreasOverlappingEntityExtent(CBaseEntity ''entity'', table)</code>
| Return true if given ladder is connected in given direction.
| Fills passed in table with areas overlapping entity's extent.
|-
|-
| <code>GetNearestNavArea</code>
| <kbd>IsInUse</kbd> || <kbd>bool IsInUse(CBaseEntity ''ignore'')</kbd>
| <code>TerrorNavArea GetNearestNavArea(Vector ''origin'', float ''maxDist'', bool ''checkLOS'', bool ''checkGround'')</code>
| Return true if someone is on this ladder (other than 'ignore').
| Given a position in the world, return the nav area that is closest and at the same height, or beneath it.
|-
|-
| <code>GetObstructingEntities</code>
| <kbd>IsUsableByTeam</kbd> || <kbd>bool IsUsableByTeam(int ''teamID'')</kbd>
| <code>void GetObstructingEntities(table)</code>
| Returns true if ladder is usable for team.
| Fills a passed in table of all obstructing entities.
|-
|-
| <code>IsValid</code>
| <kbd>IsValid</kbd> || <kbd>bool IsValid()</kbd>
| <code>bool IsValid()</code>
| Whether the handle belongs to a valid ladder.
| Whether the handle belongs to a valid entity. Redundant as navigation meshes are not entity related.
|}
|-
 
| <code>NavAreaBuildPath</code>
=== CNetPropManager ===
| <code>bool NavAreaBuildPath(TerrorNavArea ''startArea'', TerrorNavArea ''endArea'', Vector ''goalPos'', float ''flMaxPathLength'', int ''teamID'', bool ''ignoreNavBlockers'')</code>
{{↑|toc}}
| Returns true if a path exists. If 'endArea' is NULL, will compute a path as close as possible to 'goalPos'.
 
|-
{{↑|Instances}} Game Instance: <kbd>NetProps</kbd>
| <code>NavAreaTravelDistance</code>
 
| <code>float NavAreaTravelDistance(TerrorNavArea ''startArea'', TerrorNavArea ''endArea'', float ''flMaxPathLength'')</code>
| Compute distance between two areas. Return -1 if can't reach 'endArea' from 'startArea'.
|-
| <code>RegisterAvoidanceObstacle</code>
| <code>void RegisterAvoidanceObstacle(CBaseEntity ''entity'')</code>
| Registers an entity as an avoidance obstacle.
|-
| <code>UnblockRescueVehicleNav</code>
| <code>void UnblockRescueVehicleNav()</code>
| Unblock the rescue vehicle nav areas so bots can path through them.
|-
| <code>UnregisterAvoidanceObstacle</code>
| <code>void UnregisterAvoidanceObstacle(CBaseEntity ''entity'')</code>
| Unregisters an entity as an avoidance obstacle.
|}
 
=== CNetPropManager ===
 
Game Instance: <code>NetProps</code>
 
Allows reading and updating the [[Networking_Entities#Network_Variables|network properties]] of an entity.  
Allows reading and updating the [[Networking_Entities#Network_Variables|network properties]] 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").
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. i.e. {{Code|m_itTimer.m_timestamp}}.


{{warning|Each netprop has a set size in bits, exceeding the size may desync the clients from the server causing unpredictable behavior.}}
{{warning|Each netprop has a set size in bits, exceeding the size may desync the clients from the server causing unpredictable behavior.}}
Line 1,737: Line 1,399:
==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>GetPropArraySize</code>
| <kbd>GetPropArraySize</kbd> || <kbd>int GetPropArraySize(CBaseEntity ''entity'', string ''propertyName'')</kbd>
| <code>int GetPropArraySize(CBaseEntity ''entity'', string ''propertyName'')</code>
| Returns the size of an netprop array, or -1.
| Returns the size of an netprop array, or -1.
|-
|-
| <code>GetPropEntity</code>
| <kbd>GetPropEntity</kbd> || <kbd>CBaseEntity GetPropEntity(CBaseEntity ''entity'', string ''propertyName'')</kbd>
| <code>CBaseEntity GetPropEntity(CBaseEntity ''entity'', string ''propertyName'')</code>
| Reads an EHANDLE-valued netprop (21 bit integer). Returns the script handle of the entity.
| Reads an EHANDLE valued netprop (21 bit integer). Returns the script handle of the entity.
|-
|-
| <code>GetPropEntityArray</code>
| <kbd>GetPropEntityArray</kbd> || <kbd>CBaseEntity GetPropEntityArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</kbd>
| <code>CBaseEntity GetPropEntityArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| Reads an EHANDLE-valued netprop (21 bit integer) from an array. Returns the script handle of the entity.
| Reads an EHANDLE valued netprop (21 bit integer) from an array. Returns the script handle of the entity.
|-
|-
| <code>GetPropFloat</code>
| <kbd>GetPropFloat</kbd> || <kbd>float GetPropFloat(CBaseEntity ''entity'', string ''propertyName'')</kbd>
| <code>float GetPropFloat(CBaseEntity ''entity'', string ''propertyName'')</code>
| Reads a float-valued netprop.
| Reads a float valued netprop.
|-
|-
| <code>GetPropFloatArray</code>
| <kbd>GetPropFloatArray</kbd> || <kbd>float GetPropFloatArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</kbd>
| <code>float GetPropFloatArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| Reads a float-valued netprop from an array.
| Reads a float valued netprop from an array.
|-
|-
| <code>GetPropInt</code>
| <kbd>GetPropInt</kbd> || <kbd>int GetPropInt(CBaseEntity ''entity'', string ''propertyName'')</kbd>
| <code>int GetPropInt(CBaseEntity ''entity'', string ''propertyName'')</code>
| Reads an integer-valued netprop.
| Reads an integer valued netprop.
|-
|-
| <code>GetPropIntArray</code>
| <kbd>GetPropIntArray</kbd> || <kbd>int GetPropIntArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</kbd>
| <code>int GetPropIntArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| Reads an integer-valued netprop from an array.
| Reads an integer valued netprop from an array.
|-
|-
| <code>GetPropString</code>
| <kbd>GetPropString</kbd> || <kbd>string GetPropString(CBaseEntity ''entity'', string ''propertyName'')</kbd>
| <code>string GetPropString(CBaseEntity ''entity'', string ''propertyName'')</code>
| Reads an string-valued netprop.
| Reads an string valued netprop.
|-
|-
| <code>GetPropStringArray</code>
| <kbd>GetPropStringArray</kbd> || <kbd>string GetPropStringArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</kbd>
| <code>string GetPropStringArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| Reads an string-valued netprop from an array.
| Reads an string valued netprop from an array.
|-
|-
| <code>GetPropType</code>
| <kbd>GetPropType</kbd> || <kbd>string GetPropType(CBaseEntity ''entity'', string ''propertyName'')</kbd>
| <code>string GetPropType(CBaseEntity ''entity'', string ''propertyName'')</code>
| Returns the name of the netprop type as a string.
| Returns the name of the netprop type as a string.
|-
|-
| <code>GetPropVector</code>
| <kbd>GetPropVector</kbd> || <kbd>Vector GetPropVector(CBaseEntity ''entity'', string ''propertyName'')</kbd>
| <code>Vector GetPropVector(CBaseEntity ''entity'', string ''propertyName'')</code>
| Reads a 3D vector-valued netprop. {{todo | Does it work for other dimensions too?}}
| Reads a 3D vector valued netprop. {{todo | Does it work for other dimensions too?}}
|-
|-
| <code>GetPropVectorArray</code>
| <kbd>GetPropVectorArray</kbd> || <kbd>Vector GetPropVectorArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</kbd>
| <code>Vector GetPropVectorArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| Reads a 3D vector-valued netprop from an array.  
| Reads a 3D vector valued netprop from an array.  
|-
|-
| <code>HasProp</code>
| <kbd>HasProp</kbd> || <kbd>bool HasProp(CBaseEntity ''entity'', string ''propertyName'')</kbd>
| <code>bool HasProp(CBaseEntity ''entity'', string ''propertyName'')</code>
| Checks if a netprop exists.
| Checks if a netprop exists.
|-
|-
| <code>SetPropEntity</code>
| <kbd>SetPropEntity</kbd> || <kbd>void SetPropEntity(CBaseEntity ''entity'', string ''propertyName'', CBaseEntity ''value'')</kbd>
| <code>void SetPropEntity(CBaseEntity ''entity'', string ''propertyName'', CBaseEntity ''value'')</code>
| Sets an EHANDLE-valued netprop (21 bit integer) to reference the specified entity.
| Sets an EHANDLE valued netprop (21 bit integer) to reference the specified entity.
|-
|-
| <code>SetPropEntityArray</code>
| <kbd>SetPropEntityArray</kbd> || <kbd>void SetPropEntityArray(CBaseEntity ''entity'', string ''propertyName'', CBaseEntity ''value'', int ''arrayElement'')</kbd>
| <code>void SetPropEntityArray(CBaseEntity ''entity'', string ''propertyName'', CBaseEntity ''value'', int ''arrayElement'')</code>
| Sets an EHANDLE-valued netprop (21 bit integer) from an array to reference the specified entity.
| Sets an EHANDLE valued netprop (21 bit integer) from an array to reference the specified entity.
|-
|-
| <code>SetPropFloat</code>
| <kbd>SetPropFloat</kbd> || <kbd>void SetPropFloat(CBaseEntity ''entity'', string ''propertyName'', float ''value'')</kbd>
| <code>void SetPropFloat(CBaseEntity ''entity'', string ''propertyName'', float ''value'')</code>
| Sets a netprop to the specified float.
| Sets a netprop to the specified float.
|-
|-
| <code>SetPropFloatArray</code>
| <kbd>SetPropFloatArray</kbd> || <kbd>void SetPropFloatArray(CBaseEntity ''entity'', string ''propertyName'', float ''value'', int ''arrayElement'')</kbd>
| <code>void SetPropFloatArray(CBaseEntity ''entity'', string ''propertyName'', float ''value'', int ''arrayElement'')</code>
| Sets a netprop from an array to the specified float.
| Sets a netprop from an array to the specified float.
|-
|-
| <code>SetPropInt</code>
| <kbd>SetPropInt</kbd> || <kbd>void SetPropInt(CBaseEntity ''entity'', string ''propertyName'', int ''value'')</kbd>
| <code>void SetPropInt(CBaseEntity ''entity'', string ''propertyName'', int ''value'')</code>
| Sets a netprop to the specified integer.
| Sets a netprop to the specified integer.
|-
|-
| <code>SetPropIntArray</code>
| <kbd>SetPropIntArray</kbd> || <kbd>void SetPropIntArray(CBaseEntity ''entity'', string ''propertyName'', int ''value'', int ''arrayElement'')</kbd>
| <code>void SetPropInt(CBaseEntity ''entity'', string ''propertyName'', int ''value'', int ''arrayElement'')</code>
| Sets a netprop from an array to the specified integer.
| Sets a netprop from an array to the specified integer.
|-
|-
| <code>SetPropString</code>
| <kbd>SetPropString</kbd> || <kbd>void SetPropString(CBaseEntity ''entity'', string ''propertyName'', string ''value'')</kbd>
| <code>void SetPropString(CBaseEntity ''entity'', string ''propertyName'', string ''value'')</code>
| Sets a netprop to the specified string.
| Sets a netprop to the specified string.
|-
|-
| <code>SetPropStringArray</code>
| <kbd>SetPropStringArray</kbd> || <kbd>void SetPropStringArray(CBaseEntity ''entity'', string ''propertyName'', string ''value'', int ''arrayElement'')</kbd>
| <code>void SetPropStringArray(CBaseEntity ''entity'', string ''propertyName'', string ''value'', int ''arrayElement'')</code>
| Sets a netprop from an array to the specified string.
| Sets a netprop from an array to the specified string.
|-
|-
| <code>SetPropVector</code>
| <kbd>SetPropVector</kbd> || <kbd>void SetPropVector(CBaseEntity ''entity'', string ''propertyName'', Vector ''value'')</kbd>
| <code>void SetPropVector(CBaseEntity ''entity'', string ''propertyName'', Vector ''value'')</code>
| Sets a netprop to the specified vector.
| Sets a netprop to the specified vector.
|-
|-
| <code>SetPropVectorArray</code>
| <kbd>SetPropVectorArray</kbd> || <kbd>void SetPropVectorArray(CBaseEntity ''entity'', string ''propertyName'', Vector ''value'', int ''arrayElement'')</kbd>
| <code>void SetPropVectorArray(CBaseEntity ''entity'', string ''propertyName'', Vector ''value'', int ''arrayElement'')</code>
| Sets a netprop from an array to the specified vector.
| Sets a netprop from an array to the specified vector.
|}
|}


=== CScriptEntityOutputs ===
=== CScriptEntityOutputs ===
{{↑|toc}}
{{↑|Instances}} Game Instance: <kbd>EntityOutputs</kbd>


Game Instance: <code>EntityOutputs</code>
Allows reading and changing of entities' output data.
 
Allows manipulation of entity output data.


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>AddOutput</code>
| <kbd>AddOutput</kbd> || <kbd>void AddOutput(CBaseEntity ''entity'', string ''outputName'', string ''targetName'', string ''inputName'', string ''parameter'', float ''delay'', int ''timesToFire'')</kbd>
| <code>void AddOutput(CBaseEntity ''entity'', string ''outputName'', string ''targetName'', string ''inputName'', string ''parameter'', float ''delay'', int ''timesToFire'')</code>
| Adds a new output to the entity.
| Adds a new output to the entity.
|-
|-
| <code>GetNumElements</code>
| <kbd>GetNumElements</kbd> || <kbd>int GetNumElements(CBaseEntity ''entity'', string ''outputName'')</kbd>
| <code>int GetNumElements(CBaseEntity ''entity'', string ''outputName'')</code>
| Returns the number of array elements.
| Returns the number of array elements.
|-
|-
| <code>GetOutputTable</code>
| <kbd>GetOutputTable</kbd> || <kbd>void GetOutputTable(CBaseEntity ''entity'', string ''outputName'', table, int ''arrayElement'')</kbd>
| <code>void GetOutputTable(CBaseEntity ''entity'', string ''outputName'', table, int ''arrayElement'')</code>
| Fills the passed table with output information.
| Fills the passed table with output information.
|-
|-
| <code>HasAction</code>
| <kbd>HasAction</kbd> || <kbd>bool HasAction(CBaseEntity ''entity'', string ''outputName'')</kbd>
| <code>bool HasAction(CBaseEntity ''entity'', string ''outputName'')</code>
| Returns true if an action exists for the output.
| Returns true if an action exists for the output.
|-
|-
| <code>HasOutput</code>
| <kbd>HasOutput</kbd> || <kbd>bool HasOutput(CBaseEntity ''entity'', string ''outputName'')</kbd>
| <code>bool HasOutput(CBaseEntity ''entity'', string ''outputName'')</code>
| Returns true if the output exists.
| Returns true if the output exists.
|-
|-
| <code>RemoveOutput</code>
| <kbd>RemoveOutput</kbd> || <kbd>void RemoveOutput(CBaseEntity ''entity'', string ''outputName'', string ''targetName'', string ''inputName'', string ''parameter'')</kbd>
| <code>void RemoveOutput(CBaseEntity ''entity'', string ''outputName'', string ''targetName'', string ''inputName'', string ''parameter'')</code>
| Removes an output from the entity.
| Removes an output from the entity.
|}
|}


=== CScriptResponseCriteria ===
=== CScriptResponseCriteria ===
{{↑|toc}}


Game Instance: <code>ResponseCriteria</code>
{{↑|Instances}} Game Instance: <kbd>ResponseCriteria</kbd>


Allows reading the response rules of an entity.  
Allows reading the response rules of an entity.  
Line 1,879: Line 1,510:
==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>GetTable</code>
| <kbd>GetTable</kbd> || <kbd>void GetTable(CBaseEntity ''entity'', table)</kbd>
| <code>void GetTable(CBaseEntity ''entity'', table)</code>
| Fills the passed table with all criteria.
| Fills the passed table with all criteria.
|-
|-
| <code>GetValue</code>
| <kbd>GetValue</kbd> || <kbd>string GetValue(CBaseEntity ''entity'', string ''criteriaName'')</kbd>
| <code>string GetValue(CBaseEntity ''entity'', string ''criteriaName'')</code>
| Returns a string.
| Returns a string.
|-
|-
| <code>HasCriterion</code>
| <kbd>HasCriterion</kbd> || <kbd>bool HasCriterion(CBaseEntity ''entity'', string ''criteriaName'')</kbd>
| <code>bool HasCriterion(CBaseEntity ''entity'', string ''criteriaName'')</code>
| Returns true if the criterion exists.
| Returns true if the criterion exists.
|}
|}


=== Convars ===
=== Convars ===
Game Instance: <code>Convars</code>
{{↑|toc}}
{{↑|Instances}} Game Instance: <kbd>Convars</kbd>


Provides an interface for getting and setting [[Convar|convars]] on the server.
An interface to manipulate the [[List of L4D2 Cvars|convars]] on the server.
 
<!--
{{todo|The class for this doesn't seem to be directly available.}}
The class for this isn't directly available but is <kbd>CScriptConvarAccessor</kbd>. Not that it's important.
-->


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>GetClientConvarValue</code>
| <kbd>GetClientConvarValue</kbd> || <kbd>string GetClientConvarValue(string ''name'', int ''entindex'')</kbd>
| <code>string GetClientConvarValue(string ''name'', int ''entindex'')</code>
| Returns the convar value for the entindex as a string. Only works on client convars with the FCVAR_USERINFO flag. Convars without FCVAR_USERINFO or non-existent ones return empty string
| Returns the convar value for the entindex as a string. Only works with client convars with the FCVAR_USERINFO flag.  
|-
|-
| <code>GetStr</code>
| <kbd>GetStr</kbd> || <kbd>string GetStr(string ''name'')</kbd>
| <code>string GetStr(string ''name'')</code>
| Returns the convar as a string. Returns null if no such convar.  
| Returns the convar as a string. May return null if no such convar.  
|-
|-
| <code>GetFloat</code>
| <kbd>GetFloat</kbd> || <kbd>float GetFloat(string ''name'')</kbd>
| <code>float GetFloat(string ''name'')</code>
| Returns the convar as a float. Returns null if no such convar.
| Returns the convar as a float. May return null if no such convar.
|-
|-
| <code>SetValue</code>
| <kbd>SetValue</kbd> || <kbd>void SetValue(string ''name'', ''value'')</kbd>
| <code>void SetValue(string ''name'', ''value'')</code>
| Sets the value of the convar. Supported types are bool, int, float, string.  
| Sets the value of the convar. Supported types are bool, int, float, string.  
|}
|}


=== CPointTemplate ===
=== CPointTemplate ===
Extends [[#CBaseEntity|CBaseEntity]]
{{↑|toc}}
Extends {{↑|CBaseEntity}}


Script handle class for [[point_template]].
Script handle class for [[point_template]].
Line 1,933: Line 1,556:
==== Hooks ====
==== Hooks ====


;<code>table PreSpawnInstance(string ''entityClass'', string ''entityName'')</code>
;<kbd>table PreSpawnInstance(string ''entityClass'', string ''entityName'')</kbd>
:If this is defined, it will be called right before the entity is created, and any KeyValues returned will be assigned to the entity.
:If this is defined, it will be called right before the entity is created, and any KeyValues returned will be assigned to the entity.


Line 1,948: Line 1,571:
</source>
</source>


;<code>void PostSpawn(table ''entities'')</code>
;<kbd>void PostSpawn(table ''entities'')</kbd>
:Called after the entities are spawned. A table with the handles of the spawned entities indexed by name is passed to the function. Could use this to connect outputs or do whatever needs to be done after the entity was created.  
:Called after the entities are spawned. A table with the handles of the spawned entities indexed by name is passed to the function. Could use this to connect outputs or do whatever needs to be done after the entity was created.  


Line 1,961: Line 1,584:


=== CPointScriptTemplate ===
=== CPointScriptTemplate ===
Extends [[#CBaseEntity|CBaseEntity]]
{{↑|toc}}
Extends {{↑|CBaseEntity}}


Script handle class for [[point_script_template]].
Script handle class for [[point_script_template]].
Line 1,968: Line 1,592:


{| class=standard-table style="width: 100%;"
{| class=standard-table style="width: 100%;"
! Function  
! Function !! Signature !! Description
! Signature
! Description
|-
|-
|<code>AddTemplate</code>
| <kbd>AddTemplate</kbd> || <kbd>void AddTemplate(string, handle)</kbd>
|<code>void AddTemplate(string, handle)</code>
|Add an entity to the template spawner.
|Add an entity to the template spawner.
|-
|-
|<code>SetGroupSpawnTables</code>
| <kbd>SetGroupSpawnTables</kbd> || <kbd>void SetGroupSpawnTables(handle, handle)</kbd>
|<code>void SetGroupSpawnTables(handle, handle)</code>
|Cache the group spawn tables.
|Cache the group spawn tables.
|}
|}




=== CSimpleCallChainer ===
=== CPointScriptUseTarget ===
{{todo}}
{{↑|toc}}
Extends {{↑|CBaseEntity}}
 
Script handle class for the [[point_script_use_target]] entity.


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
 
! Function
{| class=standard-table style="width: 100%;"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>constructor</code>
| <kbd>CanShowBuildPanel</kbd> || <kbd>void CanShowBuildPanel(bool ''showPanel'')</kbd>
| <code>CSimpleCallChainer(string ''functionPrefix'', table ''scope'' = null)</code>
|Sets if the UI panel for the button is shown.
|  
|-
|-
| <code>PostScriptExecute</code>
| <kbd>GetUseModelName</kbd> || <kbd>string GetUseModelName()</kbd>
| <code>void PostScriptExecute()</code>
|Get the entity name of the prop bound to this button.
| Method finds all specified non-native functions and fills <code>chain</code> array with them.
|-
|-
| <code>Call</code>
| <kbd>SetProgressBarText</kbd> || <kbd>void SetProgressBarText(string ''text'')</kbd>
| <code>bool Call()</code>
|Sets the use text for the button UI.
|
|}
 
==== Members ====
{| class="standard-table" style="width: 100%;"
! Instance
! Type
! Description
|-
| <code>chain</code>
| <code>array</code>
| Contents functions to call.
|-
| <code>exactMatch</code>
| <code>bool</code>
| Use <code>prefix</code> to find exact function name (def. <code>false</code>).
|-
| <code>prefix</code>
| <code>string</code>
| Prefix to find a function.
|-
| <code>scope</code>
| <code>table</code>
| Scope to seek functions, pass <code>null</code> to use global space.
|}
 
 
=== CPointScriptUseTarget ===
Extends [[#CBaseEntity|CBaseEntity]]
 
Script handle class for the [[point_script_use_target]] entity.
 
==== Methods ====
 
{| class=standard-table style="width: 100%;"
! Function
! Signature
! Description
|-
|<code>CanShowBuildPanel</code>
|<code>void CanShowBuildPanel(bool ''showPanel'')</code>
|Sets if the UI panel for the button is shown.
|-
|<code>GetUseModelName</code>
|<code>string GetUseModelName()</code>
|Get the entity name of the prop bound to this button.
|-
|<code>SetProgressBarText</code>
|<code>void SetProgressBarText(string ''text'')</code>
|Sets the use text for the button UI.
|-
|-
|<code>SetProgressBarSubText</code>
| <kbd>SetProgressBarSubText</kbd> || <kbd>void SetProgressBarText(string ''text'')</kbd>
|<code>void SetProgressBarText(string ''text'')</code>
|Sets the subtext below the progress bar for the button UI.
|Sets the subtext below the progress bar for the button UI.
|-
|-
|<code>SetProgressBarFinishTime</code>
| <kbd>SetProgressBarFinishTime</kbd> || <kbd>void SetProgressBarFinishTime(float ''time'')</kbd>
|<code>void SetProgressBarFinishTime(float ''time'')</code>
|Sets the total time the button takes to use. If '0', no progress bar will be displayed.
|Sets the total time the button takes to use. If '0', no progress bar will be displayed.
|-
|-
|<code>SetProgressBarCurrentProgress</code>
| <kbd>SetProgressBarCurrentProgress</kbd> || <kbd>void SetProgressBarCurrentProgress(float ''time'')</kbd>
|<code>void SetProgressBarCurrentProgress(float ''time'')</code>
|Sets the current use progress. It can be used to save the use progress when the user releases the use key.
|Sets the current use progress. It can be used to save the use progress when the user releases the use key.
|-
|-
|<code>StopUse</code>
| <kbd>StopUse</kbd> || <kbd>void StopUse()</kbd>
|<code>void StopUse()</code>
|Stop the current use action.
|Stop the current use action.
|-
|-
Line 2,072: Line 1,638:


==== Members ====
==== Members ====
These variables are only available in the Entity Script after the entity has spawned. They're a custom C++ class, [[CHandle|CHandles]] which also is sometimes referred as EHANDLEs (Entity Handles). These can't be used or modified like the usual script handles, and really is only meant for verifications with comparing the output of the<code>[[#CBaseEntity|CBaseEntity]]::GetEntityHandle()</code>method.
These variables are only available in the Entity Script after the entity has spawned. They're a custom C++ class, [[CHandle|CHandles]] which also is sometimes referred as EHANDLEs (Entity Handles). These can't be used or modified like the usual script handles, and really is only meant for verifications with comparing the output of the<kbd>{{↑|CBaseEntity}}::GetEntityHandle()</kbd>method.


{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Instance
! Instance !! Type !! Description
! Type
! Description
|-
|-
| <code>UseModelEntity</code>
| <kbd>UseModelEntity</kbd> || <kbd><nowiki>[C++] CHandle<CBaseEntity></nowiki></kbd>
| <code><nowiki>[C++] CHandle<CBaseEntity></nowiki></code>
| The Use Model prop associated with this entity.
| The Use Model prop associated with this entity.
|-
|-
| <code>PlayerUsingMe</code>
| <kbd>PlayerUsingMe</kbd> || <kbd><nowiki>[C++] CHandle<CBaseEntity></nowiki></kbd>
| <code><nowiki>[C++] CHandle<CBaseEntity></nowiki></code>
| The current using player. {{todo|Recheck on this old info: Is it not 0 / null if not being used?}}.
| The current using player. {{todo|Recheck on this old info: Is it not 0 / null if not being used?}}.
|}
|}
Line 2,091: Line 1,653:
These VScript methods are called on the script set in the '''Entity Scripts''' keyvalue for the [[point_script_use_target]].
These VScript methods are called on the script set in the '''Entity Scripts''' keyvalue for the [[point_script_use_target]].
{| class=standard-table
{| class=standard-table
! Function  
! Function !! Signature !! Description
! Signature
! Description
|-
|-
|<code>OnUseFinished</code>
| <kbd>OnUseFinished</kbd> || <kbd>void OnUseFinished()</kbd>
|<code>void OnUseFinished()</code>
| Called when the player has used this button for at least 'FinishTime' seconds.
|Called when the player has used this button for at least 'FinishTime' seconds.
|-
|-
|<code>OnUseStart</code>
| <kbd>OnUseStart</kbd> || <kbd>bool OnUseStart()</kbd>
|<code>bool OnUseStart()</code>
|Called when the player begins to use this button. Return false to disable the third-person use animation.<br>{{bug*|This breaks <kbd>point_script_use_target</kbd> when declared. Use {{Code|ConnectOutput()}} and hook a function to the {{Code|OnUseStarted}} output instead.
|Called when the player begins to use this button. Return false to disable the third-person use animation.<br>{{bug|When declared, <code>point_script_use_target</code> cannot be interacted with, though <code>OnUseStart()</code> will still be ran. Use <code>ConnectOutput()</code> and hook a function to the <code>OnUseStarted</code> output instead.}}
|-
|-
|<code>OnUseStop</code>
| <kbd>OnUseStop</kbd> || <kbd>void OnUseStop(float ''timeUsed'')</kbd>
|<code>void OnUseStop(float ''timeUsed'')</code>
|Called when the player stops using this button. Passes the time this button has been used (time between StartUse and now).
|Called when the player stops using this button. Passes the time this button has been used (time between StartUse and now).
|-
|-
|<code>Precache</code>
| <kbd>Precache</kbd> || <kbd>void Precache()</kbd>
|<code>void Precache()</code>
|Called by the game engine when the entity first spawns, immediately after this script is run.
|Called by the game engine when the entity first spawns, immediately after this script is run.
|-
|-
Line 2,114: Line 1,670:


=== Decider ===
=== Decider ===
{{↑|toc}}
''An isolated instance of a rulescript database.''
''An isolated instance of a rulescript database.''


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>constructor</code>
| <kbd>constructor</kbd> ||  
|  
|  
|  
|-
|-
| <code>AddRule</code>
| <kbd>AddRule</kbd> || <kbd>bool AddRule(handle ''CRule'')</kbd>
| <code>bool AddRule(handle ''CRule'')</code>
| Add a CRule object (defined in rulescript_base.nut)  
| Add a CRule object (defined in rulescript_base.nut)  
|-
|-
| <code>FindAllMatches</code>
| <kbd>FindAllMatches</kbd> || <kbd>handle FindAllMatches(handle ''query'', float ''leeway'')</kbd>
| <code>handle FindAllMatches(handle ''query'', float ''leeway'')</code>
| Returns an array of all matching responses. If leeway is nonzero, all results scoring within 'leeway' of the best score return.
| Returns an array of all matching responses. If leeway is nonzero, all results scoring within 'leeway' of the best score return.
|-
|-
| <code>FindBestMatch</code>
| <kbd>FindBestMatch</kbd> || <kbd>handle FindBestMatch(handle ''query'')</kbd>
| <code>handle FindBestMatch(handle ''query'')</code>
| Query the database and return the best result found. If multiple of equal score found, an arbitrary one returns.  
| Query the database and return the best result found. If multiple of equal score found, an arbitrary one returns.  
|-
|-
| <code>IsValid</code>
| <kbd>IsValid</kbd> || <kbd>bool IsValid()</kbd>
| <code>bool IsValid()</code>
| Whether the object belongs to a valid entity(?).
| Whether the object belongs to a valid entity(?).
|}
|}
Line 2,145: Line 1,695:


=== regexp ===
=== regexp ===
{{↑|toc}}
The built-in [http://squirrel-lang.org/doc/sqstdlib3.html#d0e2591 Squirrel class] for regular expressions.
The built-in [http://squirrel-lang.org/doc/sqstdlib3.html#d0e2591 Squirrel class] for regular expressions.


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>constructor</code>
| <kbd>constructor</kbd> || <kbd>regexp()</kbd>
| <code>regexp()</code>
|  
|  
|-
|-
| <code>capture</code>
| <kbd>capture</kbd> || <kbd> [table] capture(''str'', [''start''])</kbd>
| <code> [table] capture(''str'', [''start''])</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.  
| 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>
| <kbd>match</kbd> || <kbd> bool match(''str'')</kbd>
| <code> bool match(''str'')</code>
| Returns a true if the regular expression matches the string str, otherwise returns false.  
| Returns a true if the regular expression matches the string str, otherwise returns false.  
|-
|-
| <code>search</code>
| <kbd>search</kbd> || <kbd>table search(''str'', [''start''])</kbd>
| <code>table search(''str'', [''start''])</code>
| Returns a table containing two indexes ("begin" and "end") of the first match of the regular expression in the string ''str'', otherwise if no match occurs returns null. The search starts from the index start of the string, if start is omitted the search starts from the beginning of the string.  
| 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>
| <kbd>subexpcount</kbd> ||  
|  
|  
|  
|}
|}




=== LateBinder ===
=== CCallChainer ===
{{↑|toc}}
'''CCallChainer''' objects collect all functions with a matching prefix in a given scope, then inserts it all into the {{Code|chains}} table with the prefix removed. All collected unprefixed functions can then be called in a chain using the class's {{Code|Call()}} method, given the method's ''event'' argument matches the functions' name.
 
Whenever a '''CCallChainer''' object is created, a function named {{Code|Dispatch}} followed by its given prefix will also be created, which the class binds the environment of its {{Code|Call()}} method to.


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>Begin</code>
| <kbd>constructor</kbd> || <kbd>CCallChainer(string ''functionPrefix'', table ''scope'' = null)</kbd>
|  
| Creates a CCallChainer object that'll collect functions that have a matching prefix in the given scope.
|  
|-
|-
| <code>End</code>
| <kbd>PostScriptExecute</kbd> || <kbd>void PostScriptExecute()</kbd>
|  
| Search for all non-native functions with matching prefixes, then push them into the {{Code|chains}} table.
|  
|-
|-
| <code>EstablishDelegation</code>
| <kbd>Call</kbd> || <kbd>bool Call(string ''event'', any ...)</kbd>
|
| Find an unprefixed function name in the {{Code|chains}} table and call it with the given arguments.
|  
|}
|-
 
| <code>HookRootMetamethod</code>
==== Members ====
|  
{| class="standard-table" style="width: 100%;"
|  
! Instance !! Type !! Description
|-
|-
| <code>UnhookRootMetamethod</code>
| <kbd>chains</kbd> || <kbd>table</kbd>
|  
| Contains names of unprefixed functions, each with an array of functions to call.
|  
|-
|-
| <code>RemoveDelegation</code>
| <kbd>prefix</kbd> || <kbd>string</kbd>
|  
| Prefix that functions should have to be added into the {{Code|chains}} table. Set by the constructor.
|  
|-
|-
| <code>Resolve</code>
| <kbd>scope</kbd> || <kbd>table</kbd>
|  
| If set, seek functions in this scope instead. Set by the constructor.
|  
|}
|}




==== Members ====
=== CSimpleCallChainer ===
{{↑|toc}}
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 {{Code|Call()}} method does not need a function's name.
 
This class is also used internally by these {{↑|CBaseEntity}} hooks: {{Code|Precache()}} and {{Code|OnPostSpawn()}}.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Instance
! Function !! Signature !! Description
! Type
! Description
|-
|-
| <code>m_bindNamesStack</code>
| <kbd>constructor</kbd> || <kbd>CSimpleCallChainer(string ''functionPrefix'', table ''scope'' = null, exactMatch = false)</kbd>
| <code>array</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>m_fixupSet</code>
| <kbd>PostScriptExecute</kbd> || <kbd>void PostScriptExecute()</kbd>
| <code>array</code>
| Begin searching for all non-native functions with matching prefixes, then push them into the {{Code|chain}} array.
|  
|-
|-
| <code>m_log</code>
| <kbd>Call</kbd> || <kbd>bool Call(any ...)</kbd>
| <code>bool</code>
| Call all functions inside the {{Code|chain}} array with the given arguments.
|  
|}
 
==== Members ====
{| class="standard-table" style="width: 100%;"
! Instance !! Type !! Description
|-
|-
| <code>m_logIndent</code>
| <kbd>chain</kbd> || <kbd>array</kbd>
| <code>int</code>
| All functions to be called by the {{Code|Call()}} method.
|  
|-
| <kbd>exactMatch</kbd> || <kbd>bool</kbd>
| If set, names of non-native functions and {{Code|prefix}} must be an exact match.  Set by the constructor.
|-
|-
| <code>m_targetTable</code>
| <kbd>prefix</kbd> || <kbd>string</kbd>
| <code>table?(null)</code>
| Prefix that functions should have to be added into the {{Code|chain}} array. Set by the constructor.
|  
|-
|-
| <kbd>scope</kbd> || <kbd>table</kbd>
| If set, seek functions in this scope instead. Set by the constructor.
|}
|}




=== QAngle ===
=== LateBinder ===
Squirrel equivalent of the C++ [[QAngle]] class.
{{↑|toc}}
 
Represents a three-dimensional orientation as Euler angles.
 
Has overloaded arithmetic operations with both QAngles and scalar values.


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>constructor</code>
| <kbd>Begin</kbd> ||
| <code>QAngle()</code>
|  
| Creates a new QAngle facing the positive x-axis.
|-
|-
| <code>constructor</code>
| <kbd>End</kbd> ||
| <code>QAngle(float ''pitch'', float ''yaw'', float ''roll'')</code>
|  
| Creates a new QAngle.
|-
|-
| <code>Forward </code>
| <kbd>EstablishDelegation</kbd> ||
| <code>Vector Forward()</code>
|  
| Returns the Forward Vector of the angles.
|-
|-
| <code>Left</code>
| <kbd>HookRootMetamethod</kbd> ||
| <code>Vector Left()</code>
|  
| Returns the left Vector of the angles.
|-
|-
| <code>Pitch</code>
| <kbd>UnhookRootMetamethod</kbd> ||
| <code>float Pitch()</code>
|  
| Returns the pitch angle in degrees.
|-
|-
| <code>Roll</code>
| <kbd>RemoveDelegation</kbd> ||
| <code>float Roll()</code>
|  
| Returns the roll angle in degrees.
|-
|-
| <code>ToKVString</code>
| <kbd>Resolve</kbd> ||  
| <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 ====
==== Members ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Instance
! Instance !! Type !! Description
! Type
|-
! Description
| <kbd>m_bindNamesStack</kbd> || <kbd>array</kbd>
|
|-
| <kbd>m_fixupSet</kbd> || <kbd>array</kbd>
|
|-
|-
| <code>x</code>
| <kbd>m_log</kbd> || <kbd>bool</kbd>
| <code>float</code>
|
| Pitch in degrees.
|-
| <kbd>m_logIndent</kbd> || <kbd>int</kbd>
|  
|-
|-
| <code>y</code>
| <kbd>m_targetTable</kbd> || <kbd>table?(null)</kbd>
| <code>float</code>
|  
| Yaw in degrees.
|-
|-
| <code>z</code>
| <code>float</code>
| Roll in degrees.
|}
|}


== Data Types ==
{{↑|toc}}


=== Quaternion ===
=== Vector ===
[http://en.wikipedia.org/wiki/Quaternion Quaternion] represents rotations in three-dimensional space.
{{↑|toc}}
Squirrel equivalent of the C++ [[Vector]] class. It is a three-dimensional vector with overloaded arithmetic operations for both Vectors and scalar values.  


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>constructor</code>
| <kbd>constructor</kbd> || <kbd>Vector(float ''x'' = 0, float ''y'' = 0, float ''z'' = 0)</kbd>
| <code>Quaternion()</code>
| Creates a new vector with the specified Cartesian coordiantes.
| Creates a new identity quaternion.
|-
|-
| <code>constructor</code>
| <kbd>Cross</kbd> || <kbd>float Cross(Vector ''factor'')</kbd>
| <code>Quaternion(float ''x'',float ''y'',float ''z'',float ''w'')</code>
| The vector product of two vectors. Returns a vector orthogonal to the input vectors.
| Creates a new quaternion of the form <code>''w'' + ''x'''''i''' + ''y'''''j''' + ''z'''''k'''</code>.
|-
|-
| <code>Dot</code>
| <kbd>Dot</kbd> || <kbd>float Dot(Vector ''factor'')</kbd>
| <code>float Dot(Quaternion ''factor'')</code>
| The scalar product of two vectors.  
| The 4D scalar product of two quaternions. represents the angle between the quaternions in the range [1, 0].
|-
|-
| <code>Invert</code>
| <kbd>Length</kbd> || <kbd>float Length()</kbd>
| <code>Quaternion Invert()</code>
| Magnitude of the vector.
| Returns a quaternion with the complimentary rotation.
|-
|-
| <code>Norm</code>
| <kbd>LengthSqr</kbd> || <kbd>float LengthSqr()</kbd>
| <code>Quaternion Norm()</code>
| The magnitude of the vector squared. Faster than the above method.
| Normalizes the 4D vector length. {{todo|What effect does this have in quaternions?}}
|-
|-
| <code>SetPitchYawRoll</code>
| <kbd>Length2D</kbd> || <kbd>float Length2D()</kbd>
| <code>void SetPitchYawRoll(float ''pitch'', float ''yaw'', float ''roll'')</code>
| Returns the magnitude of the vector on the x-y plane. Meant to be used when working with the client's HUD.
| Recomputes the quaternion from the supplied Euler angles.
|-
| <kbd>Length2DSqr</kbd> || <kbd>float Length2DSqr()</kbd>
| Returns the square of the magnitude of the vector on the x-y plane. Faster than the above method.
|-
| <kbd>Norm</kbd> || <kbd>float Norm()</kbd>
| Seems to also return the vector length.
|-
| <kbd>Scale</kbd> || <kbd>Vector Scale(float ''factor'')</kbd>
| Scales the vector magnitude.
|-
|-
| <code>ToKVString</code>
| <kbd>ToKVString</kbd> || <kbd>string ToKVString()</kbd>
| <code>string ToKVString()</code>
| Returns a string without separations commas. {{note|Not required for the {{code|SpawnEntityWithTable}} function, as it understands the Vector data type.}}
| Returns a string with the values separated by one space.
|-
|-
| <code>ToQAngle</code>
| <kbd>tostring</kbd> || <kbd>string tostring()</kbd>
| <code>QAngle ToQAngle()</code>
| Returns a human readable string.
| Returns the angles resulting from the rotation.
|}
|}


==== Members ====
==== Members ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Instance
! Instance !! Type !! Description
! Type
|-
! Description
| <kbd>x</kbd> || <kbd>float</kbd>
| Cartesian X axis.
|-
| <kbd>y</kbd> || <kbd>float</kbd>
| Cartesian Y axis.
|-
|-
| <code>x</code>
| <kbd>z</kbd> || <kbd>float</kbd>
| <code>float</code>
| Cartesian Z axis.
| Vector component along the '''i''' axis.
|}
 
==== Operations ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Operation !! Return Type !! Description
|-
| <kbd>Vector + Vector</kbd> || <kbd>Vector</kbd>
| Returns the sum of both classes's members (XYZ).
|-
|-
| <code>y</code>
| <kbd>Vector - Vector</kbd> || <kbd>Vector</kbd>
| <code>float</code>
| Returns the subtraction of both classes's members (XYZ).
| Vector component along the '''j''' axis.
|-
|-
| <code>z</code>
| <kbd>Vector * int</kbd> || rowspan="2"| <kbd>Vector</kbd>
| <code>float</code>
|rowspan="2"| Returns the multiplication of a Vector against a scalar.
| Vector component along the '''k''' axis.
|-
|-
| <code>w</code>
| <kbd>Vector * float</kbd>
| <code>float</code>
| Scalar part.
|}
|}


=== Vector ===
=== QAngle ===
Squirrel equivalent of the C++ [[Vector]] class.
{{↑|toc}}
Squirrel equivalent of the C++ [[QAngle]] class. Represents a three-dimensional orientation as Euler angles.


Three-dimensional vector.
Has overloaded arithmetic operations with both QAngles and scalar values.
 
Has overloaded arithmetic operations with both Vectors and scalar values.
 
{{note|[http://www.leeland.net/hochsuch.html Example] declaration and manipulation of Vector}}


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>constructor</code>
| <kbd>constructor</kbd> || <kbd>QAngle(float ''pitch'' = 0, float ''yaw'' = 0, float ''roll'' = 0)</kbd>
| <code>Vector()</code>
| Creates a new QAngle.
| Creates a new null vector.
|-
|-
| <code>constructor</code>
| <kbd>Forward </kbd> || <kbd>Vector Forward()</kbd>
| <code>Vector(float ''x'', float ''y'', float ''z'')</code>
| Returns the Forward Vector of the angles.  
| Creates a new vector with the specified Cartesian coordiantes.
|-
|-
| <code>Cross</code>
| <kbd>Left</kbd> || <kbd>Vector Left()</kbd>
| <code>float Cross(Vector ''factor'')</code>
| Returns the left Vector of the angles. {{bug*|Returns right Vector instead}}
| The vector product of two vectors. Returns a vector orthogonal to the input vectors.
|-
|-
| <code>Dot</code>
| <kbd>Pitch</kbd> || <kbd>float Pitch()</kbd>
| <code>float Dot(Vector ''factor'')</code>
| Returns the pitch angle in degrees.
| The scalar product of two vectors.  
|-
|-
| <code>Length</code>
| <kbd>Roll</kbd> || <kbd>float Roll()</kbd>
| <code>float Length()</code>
| Returns the roll angle in degrees.
| Magnitude of the vector.
|-
|-
| <code>LengthSqr</code>
| <kbd>ToKVString</kbd> || <kbd>string ToKVString()</kbd>
| <code>float LengthSqr()</code>
| Returns a string with the values separated by one space. {{tip|Use this with the {{Code|angles}} key when using the {{Code|SpawnEntityWithTable}} function.}}
| The magnitude of the vector squared. Faster than the above method.
|-
|-
| <code>Length2D</code>
| <kbd>ToQuat</kbd> || <kbd>Quaternion ToQuat()</kbd>
| <code>float Length2D()</code>
| Returns a quaternion representaion of the orientation.
| Returns the magnitude of the vector on the x-y plane. Meant to be used when working with the client's HUD.
|-
|-
| <code>Length2DSqr</code>
| <kbd>Up</kbd> || <kbd>Vector Up()</kbd>
| <code>float Length2DSqr()</code>
| Returns the Up Vector of the angles.
| Returns the square of the magnitude of the vector on the x-y plane. Faster than the above method.
|-
|-
| <code>Norm</code>
| <kbd>Yaw</kbd> || <kbd>float Yaw()</kbd>
| <code>float Norm()</code>
| Returns the yaw angle in degrees.
| Seems to also return the vector 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. {{note|Seemingly, a Vector not using this works fine when used with things such as<code>origin</code>key when using<code>SpawnEntityWithTable</code>function.}}
|-
| <code>tostring</code>
| <code>string tostring()</code>
| Returns a human readable string.
|}
|}


==== Members ====
==== Members ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Instance
! Instance !! Type !! Description
! Type
! Description
|-
|-
| <code>x</code>
| <kbd>x</kbd> || <kbd>float</kbd>
| <code>float</code>
| Pitch in degrees.
| Cartesian X axis.
|-
|-
| <code>y</code>
| <kbd>y</kbd> || <kbd>float</kbd>
| <code>float</code>
| Yaw in degrees.
| Cartesian Y axis.
|-
|-
| <code>z</code>
| <kbd>z</kbd> || <kbd>float</kbd>
| <code>float</code>
| Roll in degrees.
| Cartesian Z axis.
|}
|}


==== Operations ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Operation !! Return Type !! Description
|-
| <kbd>QAngle + QAngle</kbd> || <kbd>QAngle</kbd>
| Sum of both classes's members (XYZ).
|-
| <kbd>QAngle - QAngle</kbd> || <kbd>QAngle</kbd>
| Subtraction of both classes's members (XYZ).
|-
| <kbd>QAngle * int</kbd> || rowspan="2"| <kbd>QAngle</kbd>
|rowspan="2"| QAngle multiplied by a number.
|-
| <kbd>QAngle * float</kbd>
|}


=== Vector2D, Vector4D ===
=== Vector2D, Vector4D ===
Two and four-dimensional equivalents to Vector.
{{↑|toc}}
Two and four-dimensional equivalents of the Vector data type. Has the same overloaded operators.  


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>constructor</code>
| <kbd>constructor</kbd> || <kbd>Vector2D(float ''x'' = 0, float ''y'' = 0)</kbd>
| <code>Vector''X''D(float ''x'', float ''y'', ...)</code>
| Creates a new 2D vector with the specified Cartesian coordinates.
| Creates a new vector with the specified Cartesian coordiantes.
|-
| <kbd>constructor</kbd> || <kbd>Vector4D(float ''x'' = 0, float ''y'' = 0, float ''z'' = 0, float ''w'' = 0)</kbd>
| Creates a new 4D vector with the given coordinate numbers.
|-
|-
| <code>Dot</code>
| <kbd>Dot</kbd> || <kbd>float Dot(Vector''X''D ''factor'')</kbd>
| <code>float Dot(Vector''X''D ''factor'')</code>
| The scalar product of two vectors.
| The scalar product of two vectors.
|-
|-
| <code>Length</code>
| <kbd>Length</kbd> || <kbd>float Length()</kbd>
| <code>float Length()</code>
| Magnitude of the vector.
| Magnitude of the vector.
|-
|-
| <code>LengthSqr</code>
| <kbd>LengthSqr</kbd> || <kbd>float LengthSqr()</kbd>
| <code>float LengthSqr()</code>
| The magnitude of the vector squared. Faster than the above method.
| The magnitude of the vector squared. Faster than the above method.
|-
|-
| <code>Norm</code>
| <kbd>Norm</kbd> || <kbd>float Norm()</kbd>
| <code>float Norm()</code>
| Seems to also return the vector length.
| Seems to also return the vector length.
|-
|-
| <code>ToKVString</code>
| <kbd>ToKVString</kbd> || <kbd>string ToKVString()</kbd>
| <code>string ToKVString()</code>
| Returns a string without separations commas.
| Returns a string without separations commas.
|}
|}


== Scripted Mode ==
==== Members ====
Warning: Only one addon is able to actively use these functions, as more than one of them will have the last caller override the other. Usually mutations will be able to just call them. If you have a global addon that needs to call these functions, you need to use MSC https://steamcommunity.com/sharedfiles/filedetails/?id=2209484504
Enabling Scripted Mode makes a large amount of features, including [[L4D2_EMS/Appendix:_Entity_Groups|Entity Groups]], for the current script. Scripted Mode is enabled if a script is a mode specific VScript (<''mode_name''>.nut), or the script is ran with the <code>BeginScript</code> input from [[info_director]].
 
Scripted Mode data are stored under the <code>g_ModeScript</code> scope.
 
=== sm_utilities.nut ===
sm_utilities contains many wrapper functions for manipulating different features. Only a few of them are listed here, see the [[L4D2_EMS/Appendix:_Functions|EMS tutorial]] for more examples.
 
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Instance !! Type !! Description
! Signature
! Description
|-
|-
| <code>DeepPrintTable</code>
| <kbd>x</kbd> || <kbd>float</kbd>
| <code>void DeepPrintTable(handle ''table'', string ''prefix'' = "")</code>
| Cartesian X axis.
| Print out a table (and subtables) to the console. This works with classes as well (not instances).
|-
|-
| <code>DuplicateTable</code>
| <kbd>y</kbd> || <kbd>float</kbd>
| <code>table DuplicateTable(table ''source'')</code>
| Cartesian Y axis.
| This returns a deep copy of the passed in table.
|-
|-
| <code>InjectTable</code>
| <kbd>z</kbd> || <kbd>float</kbd>
| <code>void InjectTable(table ''override'', table ''base'')</code>
| Cartesian Z axis. Vector4D only.
| Inject the override data into the base table - i.e. add any new ones, overwrite dupes.
|-
|-
| <code>TimeToDisplayString</code>
| <kbd>w</kbd> || <kbd>float</kbd>
| <code>string TimeToDisplayString(float ''disp_time'')</code>
| Component for possibly creating homogeneous coordinates? Vector4D only.
| Convert a # of seconds to a displayable time string form m:ss
|}
|}


==== Operations ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Operation !! Return Type !! Description
|-
| <kbd>Vector2D + Vector2D</kbd><br><kbd>Vector4D + Vector4D</kbd> || <kbd>Vector2D</kbd><br><kbd>Vector4D</kbd>
| Returns the sum of both classes's members (XYZ).
|-
| <kbd>Vector2D - Vector2D</kbd><br><kbd>Vector4D - Vector4D</kbd> || <kbd>Vector2D</kbd><br><kbd>Vector4D</kbd>
| Returns the subtraction of both classes's members (XYZ).
|-
| <kbd>Vector2D * int</kbd><br><kbd>Vector4D * int</kbd> || rowspan="2"| <kbd>Vector2D</kbd><br><kbd>Vector4D</kbd>
|rowspan="2"| Returns the multiplication of the given Vector variant against a scalar.
|-
| <kbd>Vector2D * float</kbd><br><kbd>Vector4D * float</kbd>
|}


=== Hooks ===
=== Quaternion ===
Scripted mode provides hook functions, used by simply adding a function with the same name and arguments to the script, and are called back by the C++ code at the appropriate moments. {{todo|Update function is not Scripted Mode specific, it needs to be moved somewhere else, but where and how?}}
{{|toc}}
{{todo|Everything to know about OnGamePlayStart and OnActivate.}}
A [http://en.wikipedia.org/wiki/Quaternion Quaternion] represents rotations in three-dimensional space.


==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function !! Signature !! Description
|-
| <kbd>constructor</kbd> || <kbd>Quaternion()</kbd>
| Creates a new identity quaternion.
|-
| <kbd>constructor</kbd> || <kbd>Quaternion(float ''x'' = 0,float ''y'' = 0,float ''z'' = 0,float ''w'' = 0)</kbd>
| Creates a new quaternion of the form: <kbd>''w'' + ''x'''''i''' + ''y'''''j''' + ''z'''''k'''</kbd>.
|-
| <kbd>Dot</kbd> || <kbd>float Dot(Quaternion ''factor'')</kbd>
| The 4D scalar product of two quaternions. represents the angle between the quaternions in the range [1, 0].
|-
| <kbd>Invert</kbd> || <kbd>Quaternion Invert()</kbd>
| Returns a quaternion with the complimentary rotation.
|-
| <kbd>Norm</kbd> || <kbd>Quaternion Norm()</kbd>
| Normalizes the 4D vector length. {{todo|What effect does this have in quaternions?}}
|-
| <kbd>SetPitchYawRoll</kbd> || <kbd>void SetPitchYawRoll(float ''pitch'', float ''yaw'', float ''roll'')</kbd>
| Recomputes the quaternion from the supplied Euler angles.
|-
| <kbd>ToKVString</kbd> || <kbd>string ToKVString()</kbd>
| Returns a string with the values separated by one space.
|-
| <kbd>ToQAngle</kbd> || <kbd>QAngle ToQAngle()</kbd>
| Returns the angles resulting from the rotation.
|}


==== OnShutdown ====


<code>void OnShutdown()</code>: Called as the mutation is shutdown, happens for multiple scenarios, such as map change or a mission being lost. To retrieve the reason, use such a code:
==== Members ====
 
{| class="standard-table" style="width: 100%;"
<source lang="JavaScript">
! Instance !! Type !! Description
function OnShutdown()
|-
{
| <kbd>x</kbd> || <kbd>float</kbd>
local reason = SessionState.ShutdownReason
| Vector component along the '''i''' axis.
local nextmap = SessionState.NextMap
|-
| <kbd>y</kbd> || <kbd>float</kbd>
| Vector component along the '''j''' axis.
|-
| <kbd>z</kbd> || <kbd>float</kbd>
| Vector component along the '''k''' axis.
|-
| <kbd>w</kbd> || <kbd>float</kbd>
| Scalar part.
|}


printl("Mutation shut down under reason " + reason.tostring() + ", next map is " + nextmap)
==== Operations ====
}
{| class="standard-table" style="width:100%"
</source>  
! Operation !! Return Type !! Description
==== OnActivate ====
|-
| <kbd>Quaternion + Quaternion</kbd> || <kbd>Quaternion</kbd>
| Sum of the two Quaternions.
|-
| <kbd>Quaternion - Quaternion</kbd> || <kbd>Quaternion</kbd>
| Subtraction of the two Quaternions.
|-
| <kbd>Quaternion * int</kbd> || rowspan="2"| <kbd>Quaternion</kbd>
|rowspan="2"| Quaternion multiplied by a number.
|-
| <kbd>Quaternion * float</kbd>
|}


<code>void OnActivate()</code>: Called after OnGamePlayStart. Unknown anything else about it, comes likely from EMS and pulled via console command "script g_ModeScript.DeepPrintTable(getroottable())"
== Scripted Mode ==
{{↑|toc}}
Enabling Scripted Mode makes a large amount of features like cm_ director options and various hooks available. Scripted Mode is enabled if a script (<''current_mode_name''>.nut) is present.
{{warning|Only one addon is able to actively use these functions so using scripted mode features outside of mutations is conflict prone and discouraged}}


==== OnGameplayStart ====
Scripted Mode data are stored under the {{Code|g_ModeScript}} scope.


<code>void OnGameplayStart()</code>: Called whenever the gameplay starts.
=== sm_utilities.nut ===
{{↑|toc}}
sm_utilities contains many wrapper functions for manipulating different features. Only a few of them are listed here, see the [[L4D2_EMS/Appendix:_Functions|EMS tutorial]] for more examples. These functions are inside g_MapScript scope.


==== AllowBash ====
{| class="standard-table" style="width: 100%;"
 
! Function !! Signature !! Description
<code>int AllowBash(handle ''basher'', handle ''bashee'')</code>: called whenever melee bash is used. Returns these values:
|-
 
| <kbd>CheckOrSetMapCallback</kbd> || <kbd>void CheckOrSetMapCallback(''cb_name'', ''cb_default'')</kbd>
*ALLOW_BASH_ALL - normal melee behavior
| Pass a callback and default @ for it, if it doesnt exist in current table, place it there.
*ALLOW_BASH_NONE - do nothing at all
|-
*ALLOW_BASH_PUSHONLY - applies physics push but deals no damage (including prevention of insta-kill ambush behavior)
| <kbd>DeepPrintTable</kbd> || <kbd>void DeepPrintTable(handle ''table'', string ''prefix'' = "")</kbd>
| Print out a table (and subtables) to the console. This works with classes as well (not instances).
|-
| <kbd>DuplicateTable</kbd> || <kbd>table DuplicateTable(table ''source'')</kbd>
| This returns a deep copy of the passed in table.
|-
| <kbd>InjectTable</kbd> || <kbd>void InjectTable(table ''override'', table ''base'')</kbd>
| Inject the override data into the base table - i.e. add any new ones, overwrite dupes.
|-
| <kbd>SpawnStartBox</kbd> || <kbd>handle SpawnStartBox(''centerobjname'', ''useFloating'', ''width'', ''depth'', ''barriermodel'', ''min_gap'')</kbd>
| Auto-create a startbox that will give you a callback when the first player exits it.
|-
| <kbd>TeleportPlayersToStartPoints</kbd> || <kbd>void TeleportPlayersToStartPoints(string ''spawnpointName'')</kbd>
| Teleport players to start entities named by the argument - must have 4 spawnpoints.
|-
| <kbd>Ticker_AddToHud</kbd> || <kbd>void Ticker_AddToHud(table ''hudTable'', string ''strInit'', bool ''blink'')</kbd>
| Adds ticker data to a passed in HUDTable.
|-
| <kbd>Ticker_NewStr</kbd> || <kbd>void Ticker_NewStr(string ''newStr'', float ''newTimeout'')</kbd>
| Sets the current Ticker string, w/an optional timeout value.
|-
| <kbd>TimeToDisplayString</kbd> || <kbd>string TimeToDisplayString(float ''disp_time'')</kbd>
| Convert a # of seconds to a displayable time string form m:ss
|-
|}




=== Hooks ===
{{↑|toc}}
Scripted mode provides hook functions, used by simply adding a function with the same name and arguments to the script, and are called back by the C++ code at the appropriate moments.
{{todo|Everything to know about OnGamePlayStart and OnActivate.}}


==== AllowTakeDamage ====
==== OnShutdown ====
 
<kbd>void OnShutdown()</kbd>: Called as the mutation is shutdown, happens for multiple scenarios, such as map change or a mission being lost. To retrieve the reason, use such a code:
<code>bool AllowTakeDamage(table ''damageTable'')</code>: Adding a function with this name in the script causes C++ to call it on all damage events. The damageTable is actually defined in scriptedmode.nut and filled in as appropriate before each call.


<source lang="JavaScript">
<source lang="JavaScript">
ScriptedDamageInfo <-
function OnShutdown()
{
{
Attacker = null // hscript of the entity that attacked
local reason = SessionState.ShutdownReason
local nextmap = SessionState.NextMap
 
printl("Mutation shut down under reason " + reason.tostring() + ", next map is " + nextmap)
}
</source>
 
==== OnActivate ====
<kbd>void OnActivate()</kbd>: Called after OnGameplayStart. Unknown anything else about it, comes likely from EMS and pulled via console command "script g_ModeScript.DeepPrintTable(getroottable())"
 
==== OnGameplayStart ====
<kbd>void OnGameplayStart()</kbd>: Called whenever the gameplay starts.
 
==== AllowBash ====
<kbd>int AllowBash(handle ''basher'', handle ''bashee'')</kbd>: called whenever melee bash is used. Returns these values:
 
*ALLOW_BASH_ALL - normal melee behavior
*ALLOW_BASH_NONE - do nothing at all
*ALLOW_BASH_PUSHONLY - applies physics push but deals no damage (including prevention of insta-kill ambush behavior)
 
==== AllowTakeDamage ====
<kbd>bool AllowTakeDamage(table ''damageTable'')</kbd>: Adding a function with this name in the script causes C++ to call it on all damage events. The damageTable is actually defined in scriptedmode.nut and filled in as appropriate before each call.
 
<source lang="JavaScript">
ScriptedDamageInfo <-
{
Attacker = null // hscript of the entity that attacked
Victim = null // hscript of the entity that was hit
Victim = null // hscript of the entity that was hit
Inflictor = null // hscript of the entity that was the inflictor
Inflictor = null // hscript of the entity that was the inflictor
Line 2,594: Line 2,217:


==== BotQuery ====
==== BotQuery ====
 
<kbd>bool BotQuery(int ''queryflag'', handle ''entity'', bool ''defaultvalue'')</kbd>: Hook to control survivor bot behavior. Only one known flag is supported.
<code>bool BotQuery(int ''queryflag'', handle ''entity'', bool ''defaultvalue'')</code>: Hook to control survivor bot behavior. Only one known flag is supported.
* <kbd>BOT_QUERY_NOTARGET</kbd> - Fired when a bot wants to bash a prop. Returning {{Code|false}} disallows the bashing.
* <code>BOT_QUERY_NOTARGET</code> - Fired when a bot wants to bash a prop. Returning <code>false</code> disallows the bashing.
 
 


==== CanPickupObject ====
==== CanPickupObject ====
<kbd>bool CanPickupObject(handle ''object'')</kbd>: Hook function for deciding whether a given prop should be pickupable (HL2 style). Returning <kbd>true</kbd> makes the players able to pick up the object. Only functional for server side props. If this is defined it must return true in order the PickupObject() function to work.


<code>bool CanPickupObject(handle ''object'')</code>: Hook function for deciding whether a given prop should be pickupable (HL2 style). Returning <code>true</code> makes the players able to pick up the object. Only functional for server side props. If this is defined it must return true in order the PickupObject() function to work.
==== InterceptChat ====
<kbd>void InterceptChat(string ''message'', CTerrorPlayer ''speaker'')</kbd>: If you put a function with this name in your script, C++ will call it on all chat messages. Passing in the (annotated) chat string and the handle of the speaker. If the function returns false, it will prevent other players from seeing the chat message except for the player who entered it.


==== SetupModeHUD ====
{{todo}}


==== UserConsoleCommand ====
<kbd>void UserConsoleCommand(handle ''playerScript'', arg)</kbd>: when a user does a <kbd>scripted_user_func argument</kbd> at console (or bound to a key) this function is called (if it exists). The playerscript is which players console it came from. You can pass strings or whatever, of course. So could do a switch statement off {{Code|arg}} to give players special controls, etc.


==== InterceptChat ====
==== OnGameEvent_''x'' ====
 
<kbd>void OnGameEvent_''x''(table ''params'')</kbd>: A callback that is called when the game event ''x'' is fired. See {{Code|resource\gameevents.res}}, {{Code|resource\serverevents.res}} and {{Code|resource\modevents.res}} for valid events. The callback functions can be registered independently from Scripted Mode, using: <kbd>__CollectGameEventCallbacks(this)</kbd>
<code>void InterceptChat(string ''message'', CTerrorPlayer ''speaker'')</code>: If you put a function with this name in your script, C++ will call it on all chat messages. Passing in the (annotated) chat string and the handle of the speaker. If the function returns false, it will prevent other players from seeing the chat message except for the player who entered it.
 
 
 
==== UserConsoleCommand ====
 
<code>void UserConsoleCommand(handle ''playerScript'', arg)</code>: when a user does a <code>scripted_user_func argument</code> at console (or bound to a key) this function is called (if it exists). The playerscript is which players console it came from. You can pass strings or whatever, of course. So could do a switch statement off <code>arg</code> to give players special controls, etc.
 
 
 
==== OnGameEvent_''x'' ====
 
<code>void OnGameEvent_''x''(table ''params'')</code>: A callback that is called when the game event ''x'' is fired. See <code>scripts\gameevents.res</code> and <code>scripts\modeevents.res</code> for valid events. The callback functions can be registered independently from Scripted Mode, using: <code>__CollectEventCallbacks(this, "OnGameEvent_", "GameEventCallbacks", RegisterScriptGameEventListener)</code>
'''See [[L4D2_EMS/Appendix:_Game_Events|EMS Appendix - Game Events]] for more information.'''
'''See [[L4D2_EMS/Appendix:_Game_Events|EMS Appendix - Game Events]] for more information.'''


== Global Functions ==
== Global Functions ==
=== Printing and Drawing ===
{{↑|toc}}
Functions for printing out messages or drawing elements in the world, mostly for debugging reasons.
{{warning|Any function with the <kbd>Debug</kbd> prefix requires the cvar <kbd>developer</kbd> be enabled and the game unpaused.<br>They also do not appear in multiplayer, only on a local server.}}


=== Printing and Drawing ===
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
| <kbd>__DumpScope</kbd> || <kbd>void __DumpScope(int ''indentation'', table ''scope'')</kbd>
| Dumps a scope's contents and expands all tables and arrays; this is what the <kbd>ent_script_dump</kbd> command uses.
{{tip|You can use this to print tables/arrays.}}
{{Expand|title=Example|
Using this code:
<source lang=js>
local testTable =
{
integer = 20,
string = "hello",
array = [1, 2, 3]
};
 
printl("{");
__DumpScope(1, testTable);
printl("}");
</source>
 
Will print the following in console:
<source lang=js>
{
  string = "hello"
  array(ARRAY)
  [
      0 = 1
      1 = 2
      2 = 3
  ]
  integer = 20
}
</source>
}}
|-
|-
| <code>[[List_of_L4D2_Script_Functions/ClientPrint | ClientPrint]]</code>
| <kbd>[[/ClientPrint|ClientPrint]]</kbd> || <kbd>void ClientPrint(CTerrorPlayer ''player'', int ''destination'', string ''message'')</kbd>
| <code>void ClientPrint(CTerrorPlayer ''player'', int ''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.
| Print a client message. If you pass null instead of a valid player, the message will be sent to all clients.
|-
|-
| <code>DebugDrawBox</code>
| <kbd>DebugDrawBox</kbd> || <kbd>void DebugDrawBox(Vector ''origin'', vector ''min'', vector ''max'', int ''r'', int ''g'', int ''b'', int ''alpha'', float ''duration'')</kbd>
| <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.
| Draw a debug overlay box.
|-
|-
| <code>DebugDrawBoxAngles</code>
| <kbd>DebugDrawBoxAngles</kbd> || <kbd>void DebugDrawBoxAngles(Vector ''origin'', Vector ''min'', Vector ''max'', QAngle ''direction'', Vector ''rgb'', int ''alpha'', float ''duration'')</kbd>
| <code>void DebugDrawBoxAngles(Vector ''origin'', Vector ''min'', Vector ''max'', QAngle ''direction'', Vector ''rgb'', int ''alpha'', float ''duration'')</code>
| Draw a debug oriented box (cent, min, max, angles(p,y,r), vRgb, a, duration).
| Draw a debug oriented box (cent, min, max, angles(p,y,r), vRgb, a, duration).
|-
|-
| <code>DebugDrawBoxDirection</code>
| <kbd>DebugDrawBoxDirection</kbd> || <kbd>void DebugDrawBoxDirection(Vector ''center'', Vector ''min'', Vector ''max'', Vector ''forward'', Vector ''rgb'', float ''alpha'', float ''duration'')</kbd>
| <code>void DebugDrawBoxDirection(Vector ''center'', Vector ''min'', Vector ''max'', Vector ''forward'', Vector ''rgb'', float ''alpha'', float ''duration'')</code>
| Draw a debug forward box.
| Draw a debug forward box.
|-
|-
| <code>DebugDrawCircle</code>
| <kbd>DebugDrawCircle</kbd> || <kbd>void DebugDrawCircle(Vector ''center'', Vector ''rgb'', float ''alpha'', float ''radius'', bool ''ztest'', float ''duration'')</kbd>
| <code>void DebugDrawCircle(Vector ''center'', Vector ''rgb'', float ''alpha'', float ''radius'', bool ''ztest'', float ''duration'')</code>
| Draw a debug circle.
| Draw a debug circle.
|-
|-
| <code>DebugDrawClear</code>
| <kbd>DebugDrawClear</kbd> || <kbd>void DebugDrawClear()</kbd>
| <code>void DebugDrawClear()</code>
| Try to clear all the debug overlay info.
| Try to clear all the debug overlay info.
|-
|-
| <code>DebugDrawLine</code>
| <kbd>DebugDrawLine</kbd> || <kbd>void DebugDrawLine(Vector ''start'', Vector ''end'', int ''red'', int ''green'', int ''blue', bool ''zTest'', float ''time'')</kbd>
| <code>void DebugDrawLine(Vector ''start'', Vector ''end'', int ''red'', int ''green'', int ''blue', bool ''zTest'', float ''time'')</code>
| Draw a debug overlay line.
| Draw a debug overlay line.
|-
|-
| <code>DebugDrawLine_vCol</code>
| <kbd>DebugDrawLine_vCol</kbd> || <kbd>void DebugDrawLine_vCol(Vector ''start'', vector ''end'', vector ''rgb'', bool ''ztest'', float ''duration'')</kbd>
| <code>void DebugDrawLine_vCol(Vector ''start'', vector ''end'', vector ''rgb'', bool ''ztest'', float ''duration'')</code>
| Draw a debug line using color vec.
| Draw a debug line using color vec.
|-
|-
| <code>DebugDrawScreenTextLine</code>
| <kbd>DebugDrawScreenTextLine</kbd> || <kbd>void DebugDrawScreenTextLine(float ''x'', float ''y'', int ''lineOffset'', string ''text'', int ''r'', int ''g'', int ''b'', int ''a'', float ''duration'')</kbd>
| <code>void DebugDrawScreenTextLine(float ''x'', float ''y'', int ''lineOffset'', string ''text'', int ''r'', int ''g'', int ''b'', int ''a'', float ''duration'')</code>
| Draw text with a line offset.
| Draw text with a line offset.
|-
|-
| <code>DebugDrawText</code>
| <kbd>DebugDrawText</kbd> || <kbd>void DebugDrawText(Vector ''origin'', string ''text'', bool ''useViewCheck'', float ''duration'')</kbd>
| <code>void DebugDrawText(Vector ''origin'', string ''text'', bool ''useViewCheck'', float ''duration'')</code>
| Draw text on the screen, starting on the position of ''origin''.
| Draw text on the screen, starting on the position of ''origin''.
|-
|-
| <code>__DumpScope</code>
| <kbd>DumpObject</kbd> || <kbd>void DumpObject(handle ''object'')</kbd>
| <code>void __DumpScope(int ''indentation'', handle ''scope'')</code>
| Dumps contents of everything in the scope.
|-
| <code>DumpObject</code>
| <code>void DumpObject(handle ''object'')</code>
| Dumps information about a class or instance.
| Dumps information about a class or instance.
|-
|-
| <code>HUDManageTimers</code>
| <kbd>HUDManageTimers</kbd> || <kbd>void HUDManageTimers(int ''timerID'', int ''command'', float ''value'')</kbd>
| <code>void HUDManageTimers(int ''timerID'', int ''command'', float ''value'')</code>
| Manages the HUD timers. Valid command enumerations are: TIMER_DISABLE, TIMER_COUNTUP, TIMER_COUNTDOWN, TIMER_STOP, TIMER_SET
| Manages the HUD timers. Valid command enumerations are: TIMER_DISABLE, TIMER_COUNTUP, TIMER_COUNTDOWN, TIMER_STOP, TIMER_SET
|-
|-
| <code>HUDPlace</code>
| <kbd>HUDPlace</kbd> || <kbd>void HUDPlace(int ''slot'', float ''x'', float ''y'', float ''width'', float ''height'')</kbd>
| <code>void HUDPlace(int ''slot'', float ''x'', float ''y'', float ''width'', float ''height'')</code>
| Sets the position of a HUD element. See [[L4D2_EMS/Appendix:_HUD]]
| Sets the position of a HUD element. See [[L4D2_EMS/Appendix:_HUD]]
|-
|-
| <code>HUDReadTimer</code>
| <kbd>HUDReadTimer</kbd> || <kbd>float HUDReadTimer(int ''timerID'')</kbd>
| <code>float HUDReadTimer(int ''timerID'')</code>
| Returns the value of a HUD timer. See [[L4D2_EMS/Appendix:_HUD]]
| Returns the value of a HUD timer. See [[L4D2_EMS/Appendix:_HUD]]
|-
|-
| <code>HUDSetLayout</code>
| <kbd>HUDSetLayout</kbd> || <kbd>void HUDSetLayout(table ''HUDTable'')</kbd>
| <code>void HUDSetLayout(table ''HUDTable'')</code>
| Applies a HUD to the screen. See [[L4D2_EMS/Appendix:_HUD]] {{important|Scriptedmode feature, usable properly in mutations only}}
| Applies a HUD to the screen. See [[L4D2_EMS/Appendix:_HUD]]
|-
|-
| <code>Msg</code>
| <kbd>Msg</kbd> || <kbd>void Msg(string ''message'')</kbd>
| <code>void Msg(string ''message'')</code>
| Prints message to console without any line feed after.
| Prints message to console without any line feed after.
|-
|-
| <code>print</code>
| <kbd>print</kbd> || <kbd>void print(string ''message'')</kbd>
| <code>void print(string ''message'')</code>
| Prints message to console without any line feed after. Identical to {{Code|Msg()}}.
| Prints message to console without any line feed after.
|-
|-
| <code>printl</code>
| <kbd>printl</kbd> || <kbd>void printl(string ''message'')</kbd>
| <code>void printl(string ''message'')</code>
| Prints message to console with a line feed after.
| Prints message to console with a line feed after.
|-
|-
| <code>realPrint</code>
| <kbd>realPrint</kbd> || <kbd>void realPrint(string ''message'')</kbd>
| <code>void realPrint(string ''message'')</code>
| Identical to print. print seems to be a wrapper for this.
| Identical to print. print seems to be a wrapper for this.
|-
|-
| <code>ShowMessage</code>
| <kbd>ShowMessage</kbd> || <kbd>void ShowMessage(string ''message'')</kbd>
| <code>void ShowMessage(string ''message'')</code>
| Print a HUD message on all clients. {{bug*|Non-functional.|only=l4d2}}
| Print a HUD message on all clients. {{bug|Non-functional.}}
|-
|-
| <code>Say</code>
| <kbd>Say</kbd> || <kbd>void Say(CTerrorPlayer ''player'', string ''message'', bool ''teamOnly'') </kbd>
| <code>void Say(CTerrorPlayer ''player'', string ''message'', bool ''teamOnly'') </code>
| Calling this will have the specified player send the message to chat, either to teamOnly (true) or to everyone.  
| Calling this will have the specified player send the message to chat, either to teamOnly (true) or to everyone.  
|-
|-
| <code>SendToConsole</code>
| <kbd>SendToConsole</kbd> || <kbd>void SendToConsole(string ''command'')</kbd>
| <code>void SendToConsole(string ''command'')</code>
| Send a string to the console as a command.
| Send a string to the console as a command.
|-
|-
| <code>SendToServerConsole</code>
| <kbd>SendToServerConsole</kbd> || <kbd>void SendToServerConsole(string ''command'')</kbd>
| <code>void SendToServerConsole(string ''command'')</code>
| Send a string to the server console as a command.
| Send a string to the server console as a command.
|-
|-
| <code>Ticker_AddToHud</code>
|}
| <code>void Ticker_AddToHud(table ''hudTable'', string ''strInit'', bool ''blink'')</code>
| Adds ticker data to a passed in HUDTable.
|-
| <code>Ticker_NewStr</code>
| <code>void Ticker_NewStr(string ''newStr'', float ''newTimeout'')</code>
| Sets the current Ticker string, w/an optional timeout value.
|-
|}


=== Hooks ===
=== Hooks ===
{{↑|toc}}
==== DebugTick ====
==== DebugTick ====


<code>void DebugTick()</code>: Called every tick, if a function with this name is in your script. {{note|The Mutation/Mode name needs to be prefixed with "'''debug_'''" in order for this function to be called.}}
<kbd>void DebugTick()</kbd>: Called every tick, if a function with this name is in your script. {{note|The Mutation/Mode name needs to be prefixed with "'''debug_'''" in order for this function to be called.}}


==== Update ====
==== Update ====
<kbd>void Update()</kbd>: Called every second, if a function with this name is defined in the following scopes. Gives easy control over the flow of a game.
===== DirectorScript.Update =====
When defined in this scope early for example inside <code>director_base(_addon).nut</code>. Should not be used outside mutations as it would create conflict with other addons that would try this approach. Ideally never using this scope for it as there is very little if any reason to do so.
===== DirectorScript.MapScript.Update =====
Update function in this scope is already defined by default in <code>scriptedmode.nut</code> and shouldn't be changed as it takes care of functionality of the following helper functions that are also defined in the same scope which means if they need to be accessed while running a script outside g_ModeScript, g_MapScript or g_MapScript.LocalScript they need to be accessed as <code>g_MapScript.ScriptedMode_...</code>.
{{warning|Defining Update function in a <code><mapname>_finale.nut</code> script ran by custom or scavenge finale type will break this functionality as it overwrites the initial Update function that takes care of it. This mistake was made in The Sacrifice finale (c7m3_port_finale.nut).}}
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>ScriptedMode_CallNextUpdate</kbd> || <kbd>void ScriptedMode_CallNextUpdate(function callnext)</kbd>
| Pass a function to this, it will get called once as part of next Update, for doing something 'soon but not now'
|-
| <kbd>ScriptedMode_AddUpdate</kbd> || <kbd>void ScriptedMode_AddUpdate(function updatefunc)</kbd>
| Register arbitrary function without parameters to run every second (single function cannot be registered twice).
|-
| <kbd>ScriptedMode_AddSlowPoll</kbd> || <kbd>void ScriptedMode_AddSlowPoll(function updatefunc)</kbd>
| Register arbitrary function without parameters to run every 3 seconds (single function cannot be registered twice).
|-
| <kbd>ScriptedMode_RemoveUpdate</kbd> || <kbd>void ScriptedMode_RemoveUpdate(function updatefunc)</kbd>
| Removes a function that was before added by ScriptedMode_AddUpdate
|-
| <kbd>ScriptedMode_RemoveSlowPoll</kbd> || <kbd>void ScriptedMode_RemoveSlowPoll(function updatefunc)</kbd>
| Removes a function that was before added by ScriptedMode_AddSlowPoll
|}
===== DirectorScript.MapScript.LocalScript.Update =====
Update function defined in scripts ran with <code>BeginScript</code>/<code>ScriptedPanicEvent</code> inputs of {{ent|info_director}} or in custom scripted stages is called here.
Gauntlet finale type uses Update function defined in <code>director_gauntlet.nut</code> to recalculate allowed common infected limits based on player's progress towards the goal.


<code>void Update()</code>: Called every second, including the first, if a function with this name is in your script when it runs for the first time. Gives easy control over the flow of a game.
===== DirectorScript.MapScript.ChallengeScript.Update =====
Update function defined inside a mutation script for example in <code>mymutation.nut</code>.


=== Entity Manipulation ===
=== Entity Manipulation ===
{{↑|toc}}
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>[[List_of_L4D2_Script_Functions/AddThinkToEnt| AddThinkToEnt]]</code>
| <kbd>[[/AddThinkToEnt|AddThinkToEnt]]</kbd> || <kbd>void AddThinkToEnt(handle ''entity'', string ''FuncName'')</kbd>
| <code>void AddThinkToEnt(handle ''entity'', string ''FuncName'')</code>
| Sets a function in the entity's script to rerun by itself constantly.
| Sets a function in the entity's script to rerun by itself constantly.
|-
|-
| <code>[[List_of_L4D2_Script_Functions/CommandABot| CommandABot]]</code>
| <kbd>[[/CommandABot|CommandABot]]</kbd> || <kbd>bool CommandABot(table ''commandTable'')</kbd>
| <code>bool CommandABot(table ''commandTable'')</code>
| Issues commands to bots based on a table configuration.  
| Issues commands to bots based on a table configuration.  
|-
|-
| <code>ConnectOutputs</code>
| <kbd>ConnectOutputs</kbd> || <kbd>void ConnectOutputs(table)</kbd>
| <code>void ConnectOutputs(table)</code>
| Expected to be used inside an entity's scope. Calling <code>ConnectOutputs(this)</code> inside entity script will search for functions named <code>[some output]Output</code> and connects respective output to them. Example: function named OnStartTouchOutput will have OnStartTouch output connected to it. (the output name needs to begin with <code>On</code> for this to work)
| sets output functions for entity by table {{todo}} 
|-
|-
| <code>DoEntFire</code>
| <kbd>DoEntFire</kbd> || <kbd>void DoEntFire(string ''target'', string ''action'', string ''value'', float ''delay'', handle ''activator'', handle ''caller'')</kbd>
| <code>void DoEntFire(string ''target'', string ''action'', string ''value'', float ''delay'', handle ''activator'', handle ''caller'')</code>
| Adds entity I/O event to the event queue to be processed at appropriate time based on specified delay. The ''caller'' and ''activator'' argument takes a ''CBaseEntity'' script handle, and entities assigned can receive inputs with ''target'' set to ''!self'', or ''!activator'' / ''!caller''.
| Generate an entity I/O event. The ''caller'' and ''activator'' argument takes a ''CBaseEntity'' script handle, and entities assigned can receive inputs with ''target'' set to ''!self'', or ''!activator'' / ''!caller''.
|-
|-
| <code>EntFire</code>
| <kbd>EntFire</kbd> || <kbd>void EntFire(string ''target'', string ''action'', string ''value = null'', float ''delay = 0'', handle ''activator = null'')</kbd>
| <code>void EntFire(string ''target'', string ''action'', string ''value = null'', float ''delay = 0'', handle ''activator = null'')</code>
| Wrapper for {{code|DoEntFire()}}. If called from an entity's script scope it sets caller to self. {{bug*|Using 0 for ''value'' parameter mistakenly converts it to empty string. Use "0" instead to prevent that}}
| Wrapper for DoEntFire() that sets<code>''activator''</code> to null, but has no<code>''caller''</code>param.  
|-
|-
| <code>DropFire</code>
| <kbd>DropFire</kbd> || <kbd>void DropFire(Vector ''location'')</kbd>
| <code>void DropFire(Vector ''location'')</code>
| Drop a fire pool from the specified Vector location.
| Drop a fire pool from the specified Vector location.
|-
|-
| <code>DropSpit</code>
| <kbd>DropSpit</kbd> || <kbd>void DropSpit(Vector ''location'')</kbd>
| <code>void DropSpit(Vector ''location'')</code>
| Drop a spit pool from the specified Vector location.
| Drop a spit pool from the specified Vector location.
|-
|-
| <code>EmitAmbientSoundOn</code>
| <kbd>EmitAmbientSoundOn</kbd> || <kbd>void EmitAmbientSoundOn(string ''soundName'', float ''volume'', int ''soundlevel'', int ''pitch'', handle ''entity'')</kbd>
| <code>void EmitAmbientSoundOn(string ''soundName'', float ''volume'', int ''soundlevel'', int ''pitch'', handle ''entity'')</code>
| Play named sound on an entity that has similar configurations to [[ambient_generic]].
| Play named sound on an entity that has similar configurations to [[ambient_generic]].
|-
|-
| <code>StopAmbientSoundOn</code>
| <kbd>EmitSoundOnClient</kbd> || <kbd>void EmitSoundOnClient(string ''soundScript'', handle ''player'')</kbd>
| <code>void StopAmbientSoundOn(string ''soundName'', handle ''entity'')</code>
| Stop named sound on an entity that has similar configurations to [[ambient_generic]].
|-
| <code>EmitSoundOnClient</code>
| <code>void EmitSoundOnClient(string ''soundScript'', handle ''player'')</code>
| Play named sound only on the client for the specified player.
| Play named sound only on the client for the specified player.
|-
|-
| <code>EmitSoundOn</code>
| <kbd>EmitSoundOn</kbd> || <kbd>void EmitSoundOn(string ''soundScript'', handle ''entity'')</kbd>
| <code>void EmitSoundOn(string ''soundScript'', handle ''entity'')</code>
| Play named sound on an entity.
| Play named sound on an entity.
|-
|-
| <code>StopSoundOn</code>
| <kbd>EntIndexToHScript</kbd> || <kbd>CBaseEntity EntIndexToHScript(int ''entIndex'')</kbd>
| <code>void StopSoundOn(string ''soundScript'', handle ''entity'')</code>
| Stop named sound on an entity.
|-
| <code>EntIndexToHScript</code>
| <code>CBaseEntity EntIndexToHScript(int ''entIndex'')</code>
| Returns the script handle for the given entity index.
| Returns the script handle for the given entity index.
|-
|-
| <code>FindRescueAreaTrigger</code>
| <kbd>FindRescueAreaTrigger</kbd> || <kbd>CBaseTrigger FindRescueAreaTrigger()</kbd>
| <code>CBaseTrigger FindRescueAreaTrigger()</code>
| Returns the trigger entity for the rescue area.
| Returns the trigger entity for the rescue area.
|-
|-
| <code>GetListenServerHost</code>
| <kbd>GetListenServerHost</kbd> || <kbd>handle GetListenServerHost()</kbd>
| <code>handle GetListenServerHost()</code>
| Get the host player on a listen server.
| Get the host player on a listen server.
|-
|-
| <code>GetFriction</code>
| <kbd>GetFriction</kbd> || <kbd>float GetFriction(CTerrorPlayer ''player'')</kbd>
| <code>float GetFriction(CTerrorPlayer ''player'')</code>
| Returns the Friction on a player entity, meaningless if not a player.
| Returns the Friction on a player entity, meaningless if not a player.
|-
|-
| <code>[[List_of_L4D2_Script_Functions/GetInvTable| GetInvTable]]</code>
| <kbd>[[/GetInvTable| GetInvTable]]</kbd> || <kbd>void GetInvTable(CTerrorPLayer ''player'',table ''invTable'')</kbd>
| <code>void GetInvTable(CTerrorPLayer ''player'',table ''invTable'')</code>
| Fills ''invTable'' with the specified player's inventory.
| Fills ''invTable'' with the specified player's inventory.
|-
|-
| <code>GetPhysVelocity</code>
| <kbd>GetPhysVelocity</kbd> || <kbd>Vector GetPhysVelocity(handle ''entity'')</kbd>
| <code>Vector GetPhysVelocity(handle ''entity'')</code>
| Returns the velocity of the entity.
| Returns the velocity of the entity.
|-
|-
| <code>GetPhysAngularVelocity</code>
| <kbd>GetPhysAngularVelocity</kbd> || <kbd>Vector GetPhysAngularVelocity(handle ''entity'')</kbd>
| <code>Vector GetPhysAngularVelocity(handle ''entity'')</code>
| Returns the Angular velocity of the entity.
| Returns the Angular velocity of the entity.
|-
|-
| <code>GetPlayerFromCharacter</code>
| <kbd>GetPlayerFromCharacter</kbd> || <kbd>handle GetPlayerFromCharacter(int ''characterType'')</kbd>
| <code>handle GetPlayerFromCharacter(int ''characterType'')</code>
| Given a character type, return the entity, or null.
| Given a character type, return the entity, or null.
|-
|-
| <code>GetPlayerFromUserID</code>
| <kbd>GetPlayerFromUserID</kbd> || <kbd>handle GetPlayerFromUserID(int ''ID'')</kbd>
| <code>handle GetPlayerFromUserID(int ''ID'')</code>
| Given a user id, return the entity, or null.
| Given a user id, return the entity, or null.
|-
|-
| <code>IsPlayerABot</code>
| <kbd>IsPlayerABot</kbd> || <kbd>bool IsPlayerABot(handle ''player'')</kbd>
| <code>bool IsPlayerABot(handle ''player'')</code>
| Is this player/entity a bot.
| Is this player/entity a bot.
|-
|-
| <code>PickupObject</code>
| <kbd>PickupObject</kbd> || <kbd>void PickupObject(handle ''player'', handle ''entity'')</kbd>
| <code>void PickupObject(handle ''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.  
| 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.  
|-
|-
| <code>PlayerInstanceFromIndex</code>
| <kbd>PlayerInstanceFromIndex</kbd> || <kbd>CTerrorPlayer PlayerInstanceFromIndex(int ''index'')</kbd>
| <code>CTerrorPlayer PlayerInstanceFromIndex(int ''index'')</code>
| Get a script handle of a player using the player index.
| Get a script handle of a player using the player index.
|-
|-
| <code>PrecacheEntityFromTable</code>
| <kbd>PrecacheEntityFromTable</kbd> || <kbd>bool PrecacheEntityFromTable(table ''keyvalues'')</kbd>
| <code>bool PrecacheEntityFromTable(table ''keyvalues'')</code>
| Precache an entity from [[KeyValues]] in a table.
| Precache an entity from [[KeyValues]] in a table.
|-
|-
| <code>RotateOrientation</code>
| <kbd>RotateOrientation</kbd> || <kbd>QAngle RotateOrientation(QAngle, QAngle)</kbd>
| <code>QAngle RotateOrientation(QAngle, QAngle)</code>
| Rotate a QAngle by another QAngle.
| Rotate a QAngle by another QAngle.
|-
|-
| <code>RotatePosition</code>
| <kbd>RotatePosition</kbd> || <kbd>Vector RotatePosition(Vector ''origin'', QAngle ''rotation'', Vector ''input'')</kbd>
| <code>Vector RotatePosition(Vector ''origin'', QAngle ''rotation'', Vector ''input'')</code>
| Rotate the input Vector around an origin.
| Rotate the input Vector around an origin.
|-
|-
| <code>SetFakeClientConVarValue</code>
| <kbd>SetFakeClientConVarValue</kbd> || <kbd>void SetFakeClientConVarValue(handle ''bot'', string ''cvar'', string ''value'')</kbd>
| <code>void SetFakeClientConVarValue(handle ''bot'', string ''cvar'', string ''value'')</code>
| Sets a USERINFO client ConVar for a fakeclient.
| Sets a USERINFO client ConVar for a fakeclient.
|-
|-
| <code>SpawnEntityFromTable</code>
| <kbd>SpawnEntityFromTable</kbd> || <kbd>handle SpawnEntityFromTable(string ''classname'', table ''keyvalues'')</kbd>
| <code>handle SpawnEntityFromTable(string ''name'', handle ''keyvalues'')</code>
| Native function for entity spawning. See [[L4D2_EMS/Appendix:_Spawning]].
| Native function for entity spawning. See [[L4D2_EMS/Appendix:_Spawning]].
|-
|-
| <code>SpawnEntityGroupFromTable</code>
| <kbd>SpawnEntityGroupFromTable</kbd> || <kbd>bool SpawnEntityGroupFromTable(table ''entityGroup'')</kbd>
| <code>bool SpawnEntityGroupFromTable(handle ''entityGroup'')</code>
| Native function for entity group spawning. See [[L4D2_EMS/Appendix:_Spawning]].
| Native function for entity group spawning. See [[L4D2_EMS/Appendix:_Spawning]].
|-
|-
| <code>SpawnStartBox</code>
| <kbd>StopAmbientSoundOn</kbd> || <kbd>void StopAmbientSoundOn(string ''soundName'', handle ''entity'')</kbd>
| <code>handle SpawnStartBox(''centerobjname'', ''useFloating'', ''width'', ''depth'', ''barriermodel'', ''min_gap'')</code>
| Stop named sound on an entity that has similar configurations to [[ambient_generic]].
| Auto-create a startbox that will give you a callback when the first player exits it.
|-
|-
| <code>TeleportPlayersToStartPoints</code>
| <kbd>StopSoundOn</kbd> || <kbd>void StopSoundOn(string ''soundScript'', handle ''entity'')</kbd>
| <code>void TeleportPlayersToStartPoints(string ''spawnpointName'')</code>
| Stop named sound on an entity.
| Teleport players to start entities named by the argument - must have 4 spawnpoints.
|-
|-
| <code>[[List_of_L4D2_Script_Functions/ZSpawn| ZSpawn]]</code>
| <kbd>[[/ZSpawn| ZSpawn]]</kbd> || <kbd>bool ZSpawn(table ''spawnTable'')</kbd>
| <code>bool ZSpawn(table ''spawnTable'')</code>
| Spawn an infected of liking, with a choice.
| Spawn an infected of liking, with a choice.
|}
|}


=== Other ===
=== Response Rules ===
{{↑|toc}}
<small>[[#Script_Scopes|Script Scopes ↑]]</small>
 
The<kbd>g_rr</kbd>table is used to create and/or override responses and their rules, allowing custom concepts to be dynamically made without altering existing talker files.<br>
{{todo|Test these functions and document them further.}}
 
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>AddToScriptHelp</code>
| <kbd>[[/rr_ProcessRules| rr_ProcessRules]]</kbd> || <kbd>void rr_ProcessRules(handle ''rulesArray'')</kbd>
|  
| Processes and adds the given ''rulesArray'' table to the talker system. This is an incomplete implementation of custom talker concepts for VScript, but it is mostly functional.
|-
| <kbd>rr_PlaySoundFile</kbd> || <kbd>unknown rr_PlaySoundFile(CTerrorPlayer ''speaker'', unknown ''query'', unknown ''soundfile'', unknown ''context'', unknown ''contextToWorld'', unknown ''volume'', unknown ''func'')</kbd>
|  
|  
|-
|-
| <code>Assert</code>
| <kbd>rrDebugPrint</kbd> || <kbd>void rrDebugPrint(string ''message'')</kbd>
| <code>void Assert(bool ''value'', string ''optional message'')</code>
| Print function that works similarly to {{Code|printl()}} but prepends ''RR_TESTBED: '' to the start of the message.
| Test value and if not true, throws exception, optionally with message.
|-
|-
| <code>CheckForSpecialStage</code>
| <kbd>rr_ProcessResponse</kbd> || <kbd>unknown rr_ProcessResponse(unknown ''resp'')</kbd>
| <code>void CheckForSpecialStage(''level'', ''stage_list'', ''stage_info'')</code>
|
|-
| <kbd>PrintTable</kbd> || <kbd>void PrintTable(handle ''table'')</kbd>
| Print a table without searching through subtables to the console. Works with classes as well (not instances).
|-
| <kbd>rr_ProcessCriterion</kbd> || <kbd>unknown rr_ProcessCriterion(unknown ''crit'')</kbd>
|
|-
| <kbd>rr_EmitSound</kbd> || <kbd>unknown rr_EmitSound(CTerrorPlayer ''speaker'', unknown ''query'', unknown ''soundName'', unknown ''context'', unknown ''contextToWorld'', unknown ''func'')</kbd>
|
|-
| <kbd>rr_CharacterSpeak</kbd> || <kbd>unknown rr_CharacterSpeak(CTerrorPlayer ''speaker'', unknown ''query'')</kbd>
|
|-
| <kbd>rr_ApplyContext</kbd> || <kbd>unknown rr_ApplyContext(CTerrorPlayer ''speaker'', unknown ''query'', unknown ''contextData'', unknown ''contextToWorld'', unknown ''func'')</kbd>
|
|-
| <kbd>rrPrintTable</kbd> || <kbd>void rrPrintTable(handle ''table'', ''prefix'' = "\t")</kbd>
| Prints a table (non-recursive)
|-
|}
 
=== Other ===
{{↑|toc}}
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>AddToScriptHelp</kbd> ||
|
|-
| <kbd>Assert</kbd> || <kbd>void Assert(bool ''value'', string ''msg'' = null)</kbd>
| Test value and if not true, throws an exception string "Assertion failed".
If ''msg'' parameter is set, then an exception string will be "Assertion failed: your message".
|-
| <kbd>CheckForSpecialStage</kbd> || <kbd>void CheckForSpecialStage(''level'', ''stage_list'', ''stage_info'')</kbd>
| Helper for picking a random special stage based on stage_info table.
| Helper for picking a random special stage based on stage_info table.
|-
|-
| <code>CheckOrSetMapCallback</code>
| <kbd>ClearGameEventCallbacks</kbd> || <kbd>void ClearGameEventCallbacks()</kbd>
| <code>void CheckOrSetMapCallback(''cb_name'', ''cb_default'')</code>
| Pass a callback and default @ for it, if it doesnt exist in current table, place it there.
|-
| <code>ClearGameEventCallbacks</code>
| <code>void ClearGameEventCallbacks()</code>
| Empties the tables of game event callback functions.
| Empties the tables of game event callback functions.
|-
|-
| <code>ClearSavedTables</code>
| <kbd>ClearSavedTables</kbd> || <kbd>void ClearSavedTables()</kbd>
| <code>void ClearSavedTables()</code>
| Removes any tables saved with {{Code|SaveTable()}}.
| Removes any tables saved with <code>SaveTable()</code>.
|-
|-
| <code>developer</code>
| <kbd>developer</kbd> || <kbd>int developer()</kbd>
| <code>int developer()</code>
| The current level of the <kbd>developer</kbd> console variable.
| The current level of the <code>developer</code> console variable.
|-
|-
| <code>Document</code>
| <kbd>Document</kbd> || <kbd>void Document(unknown ''symbolOrTable'', unknown ''itemIfSymbol'' = null, string ''descriptionIfSymbol'' = null)</kbd>
| <code>void Document(unknown ''symbolOrTable'', unknown ''itemIfSymbol'' = null, string ''descriptionIfSymbol'' = null)</code>
|  
|  
|-
|-
| <code>DoIncludeScript</code>
| <kbd>DoIncludeScript</kbd> || <kbd>bool DoIncludeScript(string ''file'', handle/table ''scope'')</kbd>
| <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}} parameter. (internal)
| Execute a script. and put all its content for the argument passed to the<code>''scope''</code>parameter. (internal)
|-
|-
| <code>IncludeScript</code>
| <kbd>IncludeScript</kbd> || <kbd>bool IncludeScript(string ''file'', handle ''scope'' = null)</kbd>
| <code>bool IncludeScript(string ''file'', handle ''scope'' = null)</code>
| Wrapper for DoIncludeScript.
| Wrapper for DoIncludeScript
|-
|-
| <code>DoUniqueString</code>
| <kbd>DoUniqueString</kbd> || <kbd>string DoUniqueString(string/null ''input'')</kbd>
| <code>string DoUniqueString(string ''input'')</code>
| Generate a string guaranteed to be unique across the life of the script VM. This function requires a string or a null value as an input, otherwise throws an error.
| Called by UniqueString, prob want to call that instead.
You should use {{Code|UniqueString}} function instead, as it is converting any input value to a string before calling this function, making generation process practically errorless.
|-
|-
| <code>Ent</code>
| <kbd>Ent</kbd> || <kbd>handle Ent(string/int ''idxorname'')</kbd>
| <code>handle Ent(string/integer ''idxorname'')</code>
| Wrapper function. If a string is provided, it'll find the entity by name using the string. But if an integer is provided, it'll be converted to a Script Handle before verifying the entity exists.
| Wrapper function. If a string is provided, it'll find the entity by name using the string. But if an integer is provided, it'll be converted to a Script Handle before verifying the entity exists.
|-
|-
| <code>FileToString</code>
| <kbd>FileToString</kbd> || <kbd>string FileToString(string ''path'')</kbd>
| <code>string FileToString(string ''file'')</code>
| Reads the file located in left4dead2/ems/''path'' and returns its contents as a string. ''path'' supports folders and special names "." and "..", which indicate "current folder" and "parent folder" respectfully.
| Reads a string from file. Returns the string from the file, null if no file or file is greater than 16384 bytes. The game will crash to desktop if the file is exactly 16384 bytes.  
If file does not exist, a null value will be returned.
 
If file is longer than 16384 bytes, it will return a null value and print an error "File ems/''path'' (from ''path'') is len [actual file length here] too long for a ScriptFileRead".
 
{{Warning|if ''path'' contains folders, these folders will be created, if missing. Check carefully what you are reading, since there is no way to remove files/folders using VScript.}}
|-
|-
| <code>FireGameEvent</code>
| <kbd>FireGameEvent</kbd> || <kbd>string FireGameEvent(string ''event'', table ''params'')</kbd>
| <code>string FireGameEvent(string ''event'', table ''params'')</code>
| Fire a game event to a listening callback function in script. Parameters are passed in a squirrel table.
| Fire a game event to a listening callback function in script. Parameters are passed in a squirrel table.
|-
|-
| <code>FireScriptEvent</code>
| <kbd>FireScriptEvent</kbd> || <kbd>void FireScriptEvent(event, params)</kbd>
| <code>void FireScriptEvent(event, params)</code>
| Wrapper for {{Code|__RunEventCallbacks()}}
| Wrapper for <code>__RunEventCallbacks()</code>
|-
|-
| <code>ForceScavengeStart</code>
| <kbd>ForceScavengeStart</kbd> || <kbd>void ForceScavengeStart()</kbd>
| <code>void ForceScavengeStart()</code>
| Starts the scavenge round, even if the setup timer hasn't elapsed.
| Starts the scavenge round, even if the setup timer hasn't elapsed.
|-
|-
| <code>ForceSurvivalStart</code>
| <kbd>ForceSurvivalStart</kbd> || <kbd>void ForceSurvivalStart()</kbd>
| <code>void ForceSurvivalStart()</code>
| Starts the survival round, even if the survivors haven't activated the radio.
| Starts the survival round, even if the survivors haven't activated the radio.
|-
|-
| <code>ForceVersusStart</code>
| <kbd>ForceVersusStart</kbd> || <kbd>void ForceVersusStart()</kbd>
| <code>void ForceVersusStart()</code>
| Starts the versus round, even if the survivors haven't left the safe room.
| Starts the versus round, even if the survivors haven't left the safe room.
|-
|-
| <code>GetCharacterDisplayName</code>
| <kbd>GetCharacterDisplayName</kbd> || <kbd>string GetCharacterDisplayName(CTerrorPlayer ''player'')</kbd>
| <code>string GetCharacterDisplayName(CTerrorPlayer ''player'')</code>
| Return {{Code|null}} if not a survivor, else the survivor's chosen character's name. This does not work with team 4 survivors.
| Return <code>null</code> if not a survivor, else the survivor characters name. {{note|For survivors created using [[info_l4d1_survivor_spawn]], this function will return an empty string for them.}}
|-
|-
| <code>GetCurrentFlowDistanceForPlayer</code>
| <kbd>GetCurrentFlowDistanceForPlayer</kbd> || <kbd>float GetCurrentFlowDistanceForPlayer(CTerrorPlayer ''player'')</kbd>
| <code>float GetCurrentFlowDistanceForPlayer(CTerrorPlayer ''player'')</code>
| Returns the navigation flow distance from the start to the specified player.
| Returns the navigation flow distance from the start to the specified player.
|-
|-
| <code>GetCurrentFlowPercentForPlayer</code>
| <kbd>GetCurrentFlowPercentForPlayer</kbd> || <kbd>float GetCurrentFlowPercentForPlayer(CTerrorPlayer ''player'')</kbd>
| <code>float GetCurrentFlowPercentForPlayer(CTerrorPlayer ''player'')</code>
| Returns how far in the navigation flow from the start to the end the player is.
| Returns how far in the navigation flow from the start to the end the player is.
|-
|-
| <code>GetFlowDistanceForPosition</code>
| <kbd>GetFlowDistanceForPosition</kbd> || <kbd>float GetFlowDistanceForPosition(Vector ''position'')</kbd>
| <code>float GetFlowDistanceForPosition(Vector ''position'')</code>
| Returns the navigation flow distance from the start to the specified point.
| Returns the navigation flow distance from the start to the specified point.
|-
|-
| <code>GetFlowPercentForPosition</code>
| <kbd>GetFlowPercentForPosition</kbd> || <kbd>float GetFlowPercentForPosition(Vector ''position'', bool ''unknown'')</kbd>
| <code>float GetCurrentFlowPercentForPosition(Vector ''position'', bool ''unknown'')</code>
| Returns how far in the navigation flow from the start to the end the position is.
| Returns how far in the navigation flow from the start to the end the position is.
|-
|-
| <code>GetMaxFlowDistance</code>
| <kbd>GetMaxFlowDistance</kbd> || <kbd>float GetMaxFlowDistance()</kbd>
| <code>float GetMaxFlowDistance()</code>
| Returns the navigation flow distance from the start to the end of the level.
| Returns the navigation flow distance from the start to the end of the level.
|-
|-
| <code>GetAverageSurvivorFlowDistance</code>
| <kbd>GetAverageSurvivorFlowDistance</kbd> || <kbd>float GetAverageSurvivorFlowDistance()</kbd>
| <code>float GetAverageSurvivorFlowDistance()</code>
| Returns the navigation flow distance from the start to the survivors position averaged.
| Returns the navigation flow distance from the start to the survivors position averaged.
|-
|-
| <code>GetDifficulty</code>
| <kbd>GetDifficulty</kbd> || <kbd>int GetDifficulty()</kbd>
| <code>int GetDifficulty()</code>
| Returns the current difficulty as a numeric value. Easy = 0, Normal = 1, Advanced = 2, Expert = 3.
| Returns the current difficulty as a numeric value.
|-
|-
| <code>GetDifficultyString</code>
| <kbd>GetDifficultyString</kbd> || <kbd>string GetDifficultyString()</kbd>
| <code>string GetDifficultyString()</code>
| Returns the current difficulty as a string. Difficulty names are in z_difficulty cvar style: Easy, Normal, Hard, Impossible.
| Returns the current difficulty as a string.
|-
|-
| <code>GetFrameCount</code>
| <kbd>GetFrameCount</kbd> || <kbd>void GetFrameCount()</kbd>
| <code>void GetFrameCount()</code>
| Returns the engine's current frame count.
| Returns the engine's current frame count.
|-
|-
| <code>GetFunctionSignature</code>
| <kbd>GetFunctionSignature</kbd> ||  
|  
|  
|  
|-
|-
| <code>GetInfectedStats</code>
| <kbd>GetInfectedStats</kbd> || <kbd>void GetInfectedStats(table ''statTable'') </kbd>
| <code>void GetInfectedStats(table ''statTable'') </code>
| Fills statTable with some infected counts/etc... Right now the list is Witches, Tanks, Specials, Commons, though we may add more as requested going forward.
| Fills statTable with some infected counts/etc... Right now the list is Witches, Tanks, Specials, Commons, though we may add more as requested going forward.
|-
|-
| <code>GetScavengeItemsGoal</code>
| <kbd>GetModelIndex</kbd> || <kbd>int GetModelIndex(string ''filename'')</kbd>
| <code>int GetScavengeItemsGoal()</code>
| Returns index of model by name.
|-
| <kbd>GetScavengeItemsGoal</kbd> || <kbd>int GetScavengeItemsGoal()</kbd>
| Returns number of Scavenge items needed.
| Returns number of Scavenge items needed.
|-
|-
| <code>GetScavengeItemsRemaining</code>
| <kbd>GetScavengeItemsRemaining</kbd> || <kbd>int GetScavengeItemsRemaining()</kbd>
| <code>int GetScavengeItemsRemaining()</code>
| Returns number of Scavenge items remaining.
| Returns number of Scavenge items remaining.
|-
|-
| <code>GetSoundDuration</code>
| <kbd>GetSoundDuration</kbd> || <kbd>float GetSoundDuration(string ''soundname'', string ''actormodel'')</kbd>
| <code>float GetSoundDuration(string ''soundname'', string ''actormodel'')</code>
| Returns float duration of the sound. Takes soundname and optional actormodelname.
| Returns float duration of the sound. Takes soundname and optional actormodelname.
|-
|-
| <code>HasConfigurableDifficultySetting</code>
| <kbd>HasConfigurableDifficultySetting</kbd> || <kbd>bool HasConfigurableDifficultySetting()</kbd>
| <code>bool HasConfigurableDifficultySetting()</code>
| Returns true if the mode has more than a single difficulty.
| Returns true if the mode has more than a single difficulty.
|-
|-
| <code>HasPlayerControlledZombies</code>
| <kbd>HasPlayerControlledZombies</kbd> || <kbd>bool HasPlayerControlledZombies()</kbd>
| <code>bool HasPlayerControlledZombies()</code>
| Returns true if the current mode supports player controlled zombies.
| Returns true if the current mode supports player controlled zombies.
|-
|-
| <code>IsMissionFinalMap</code>
| <kbd>IsMissionFinalMap</kbd> || <kbd>bool IsMissionFinalMap()</kbd>
| <code>bool IsMissionFinalMap()</code>
| True if the current map is the final map of the campaign. Independent of {{ent|trigger_finale}} existence.
| True if the current map is the final map of the campaign.
|-
|-
| <code>IsDedicatedServer</code>
| <kbd>IsDedicatedServer</kbd> || <kbd>bool IsDedicatedServer()</kbd>
| <code>bool IsDedicatedServer()</code>
| Returns true if this is a dedicated server.
| Returns true if this is a dedicated server.
|-
|-
| <code>IsModelPrecached</code>
| <kbd>IsModelPrecached</kbd> || <kbd>bool IsModelPrecached(string ''modelname'')</kbd>
| <code>bool IsModelPrecached(string ''modelname'')</code>
| Checks if the modelname is precached.
| Checks if the modelname is precached.
|-
|-
| <code>IsSoundPrecached</code>
| <kbd>IsSoundPrecached</kbd> || <kbd>bool IsSoundPrecached(string ''soundname'')</kbd>
| <code>bool IsSoundPrecached(string ''soundname'')</code>
| Checks if the soundname is precached.
| Checks if the soundname is precached.
|-
|-
| <code>IsWeakref</code>
| <kbd>IsWeakref</kbd> || <kbd>bool IsWeakref(table, key)</kbd>
|  
| Returns true/false based on whether table[key] is a weak reference
|  
|-
|-
| <code>LocalTime</code>
| <kbd>LocalTime</kbd> || <kbd>void LocalTime(table)</kbd>
| <code>void LocalTime(table)</code>
| Fills out a table with the local time (second, minute, hour, day, month, year, dayofweek, dayofyear, daylightsavings).
| Fills out a table with the local time (second, minute, hour, day, month, year, dayofweek, dayofyear, daylightsavings).
|-
|-
| <code>MakeNamespace</code>
| <kbd>MakeNamespace</kbd> ||  
|  
|  
|  
|-
|-
| <code>PrecacheModel</code>
| <kbd>PrecacheModel</kbd> || <kbd>int PrecacheModel(string ''filename'')</kbd>
| <code>void PrecacheModel(string ''filename'')</code>
| Precache a model and return index of the model.
| Precache a model.
|-
|-
| <code>PrecacheSound</code>
| <kbd>PrecacheSound</kbd> || <kbd>void PrecacheSound(string ''soundName'')</kbd>
| <code>void PrecacheSound(string ''soundName'')</code>
| Precache a sound.
| Precache a sound.
|-
|-
| <code>QueueSpeak</code>
| <kbd>QueueSpeak</kbd> || <kbd>void QueueSpeak(handle ''entity'', string ''concept'', float ''delay'', string ''criteria'')</kbd>
| <code>void QueueSpeak(handle ''entity'', string ''concept'', float ''delay'', string ''criteria'')</code>
| Queue a speech concept.
| Queue a speech concept.
|-
|-
| <code>RandomFloat</code>
| <kbd>RandomFloat</kbd> || <kbd>float RandomFloat(float ''min'', float ''max'')</kbd>
| <code>float RandomFloat()</code>
| Generate a random floating-point number.
|-
| <code>RandomFloat</code>
| <code>float RandomFloat(float ''min'', float ''max'')</code>
| Generate a random floating-point number within a range, inclusive.
| Generate a random floating-point number within a range, inclusive.
|-
|-
| <code>RandomInt</code>
| <kbd>RandomInt</kbd> || <kbd>int RandomInt(int ''min'', int ''max'')</kbd>
| <code>int RandomInt()</code>
| Generate a random integer.
|-
| <code>RandomInt</code>
| <code>int RandomInt(int ''min'', int ''max'')</code>
| Generate a random integer within a range, inclusive.
| Generate a random integer within a range, inclusive.
|-
|-
| <code>ReapplyInfectedFlags</code>
| <kbd>ReapplyInfectedFlags</kbd> || <kbd>ReapplyInfectedFlags(int ''flags'', handle ''infected'')</kbd>
| <code>ReapplyInfectedFlags(int ''flags'', handle ''infected'')</code>
| Apply Infected Flags from {{Code|DirectorOptions}}. Applies to all common (spawned and unspawned) unless a handle to a specific infected is specified.  
| Apply Infected Flags from DirectorOptions. Applies to all common (spawned and unspawned) unless a handle to a specific infected is specified.  
|-
|-
| <code>RegisterFunctionDocumentation</code>
| <kbd>RegisterFunctionDocumentation</kbd> || <kbd>void RegisterFunctionDocumentation(unknown ''func'', string ''name'', string ''signature'', string ''description'')</kbd>
| <code>void RegisterFunctionDocumentation(unknown ''func'', string ''name'', string ''signature'', string ''description'')</code>
|  
|  
|-
|-
| <code>RegisterScriptGameEventListener</code>
| <kbd>RegisterScriptGameEventListener</kbd> || <kbd>void RegisterScriptGameEventListener(string ''eventName'')</kbd>
| <code>void RegisterScriptGameEventListener(string ''eventName'')</code>
| Register as a listener for a game event from script. It's what {{Code|__CollectGameEventCallbacks()}} uses to register event callbacks to the C++ 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.
|-
|-
| <code>ReloadMOTD</code>
| <kbd>ReloadMOTD</kbd> || <kbd>void ReloadMOTD()</kbd>
| <code>void ReloadMOTD()</code>
| Reloads the MotD file.
| Reloads the MotD file.
|-
|-
| <code>RestoreTable</code>
| <kbd>RestoreTable</kbd> || <kbd>void RestoreTable(string ''identifier'', table)</kbd>
| <code>void RestoreTable(string ''identifier'', table)</code>
|Restores table data and '''deletes it'''. See [[L4D2_EMS/Appendix:_Table_Save_Restore]].
|Restores table data and '''deletes it'''. See [[L4D2_EMS/Appendix:_Table_Save_Restore]].
|-
|-
| <code>RetrieveNativeSignature</code>
| <kbd>RetrieveNativeSignature</kbd> || <kbd>unknown RetrieveNativeSignature(string ''nativeFunction'')</kbd>
| <code>unknown RetrieveNativeSignature(string ''nativeFunction'')</code>
|  
|  
|-
|-
| <code>rr_AddDecisionRule</code>
| <kbd>rr_AddDecisionRule</kbd> || <kbd>bool rr_AddDecisionRule(RRule ''rule'')</kbd>
| <code>bool rr_AddDecisionRule(RRule ''rule'')</code>
| Add a rule to the decision database. Takes a RRule object from rulescript_base.nut.
| Add a rule to the decision database. Takes a RRule object from rulescript_base.nut.
|-
|-
| <code>rr_CommitAIResponse</code>
| <kbd>rr_CommitAIResponse</kbd> || <kbd>bool rr_CommitAIResponse(handle ''entity'', table ''airesponse'')</kbd>
| <code>bool rr_CommitAIResponse(handle ''entity'', table ''airesponse'')</code>
| Supposed to commit the result of QueryBestResponse back to the given entity to play. Takes a table needing the keys ''response'' with a ResponseSingle object (defined in response_testbed.nut) and ''orig_query'' with an unknown content.
| Supposed to commit the result of QueryBestResponse back to the given entity to play. Takes a table needing the keys ''response'' with a ResponseSingle object (defined in response_testbed.nut) and ''orig_query'' with an unknown content.
|-
|-
| <code>rr_GetResponseTargets</code>
| <kbd>rr_GetResponseTargets</kbd> || <kbd>table rr_GetResponseTargets()</kbd>
| <code>table rr_GetResponseTargets()</code>
| Retrieve a table of all available expresser targets, in the form { name : handle, name: handle }.
| Retrieve a table of all available expresser targets, in the form { name : handle, name: handle }.
|-
|-
| <code>rr_QueryBestResponse</code>
| <kbd>rr_QueryBestResponse</kbd> || <kbd>unknown rr_QueryBestResponse(handle ''entity'', table ''query'')</kbd>
| <code>unknown rr_QueryBestResponse(handle ''entity'', table ''query'')</code>
| Tests ''query'' against entity's response system and returns the best response found (or null if none found). Returns a pointer with a null type, that is apparently not usable anywhere. Possibly supposed to return a AI_Response object.
| Tests ''query'' against entity's response system and returns the best response found (or null if none found). Returns a pointer with a null type, that is apparently not usable anywhere. Possibly supposed to return a AI_Response object.
|-
|-
| <code>RushVictim</code>
| <kbd>RushVictim</kbd> || <kbd>void RushVictim(handle ''hVictim'', float ''range'')</kbd>
| <code>void RushVictim(handle ''hVictim'', float ''range'')</code>
| Make all common zombies in range rush the victim. (If hVictim isn't set, a random survivor will be chosen.)
| Make all common zombies in range rush the victim. (If hVictim isn't set, a random survivor will be chosen.)
|-
|-
| <code>SaveTable</code>
| <kbd>SaveTable</kbd> || <kbd>void SaveTable(string ''identifier'', table)</kbd>
| <code>void SaveTable(string ''identifier'', table)</code>
| See [[L4D2_EMS/Appendix:_Table_Save_Restore]].
| See [[L4D2_EMS/Appendix:_Table_Save_Restore]].
|-
|-
| <code>ScreenFade</code>
| <kbd>ScreenFade</kbd> || <kbd>void ScreenFade(handle ''player'', int ''red'', int ''green'', int ''blue'', int ''alpha'', float ''fadeTime'', float ''fadeHold'', int ''flags'')</kbd>
| <code>void ScreenFade(handle ''player'', int ''red'', int ''green'', int ''blue'', int ''alpha'', float ''fadeTime'', float ''fadeHold'', int ''flags'')</code>
| Start a screenfade with the following parameters.
| Start a screenfade with the following parameters.
|-
|-
| <code>ScreenShake</code>
| <kbd>ScreenShake</kbd> || <kbd>void ScreenShake(Vector ''vecCenter'', float ''flAmplitude'', float ''flFrequency'', float ''flDuration'', float ''flRadius'', int ''eCommand'', bool ''bAirShake'')</kbd>
| <code>void ScreenShake(Vector ''vecCenter'', float ''flAmplitude'', float ''flFrequency'', float ''flDuration'', float ''flRadius'', int ''eCommand'', bool ''bAirShake'')</code>
| Start a screenshake with the following parameters.
| Start a screenshake with the following parameters.
|-
|-
| <code>SetScavengeItemsGoal</code>
| <kbd>SetScavengeItemsGoal</kbd> || <kbd>void SetScavengeItemsGoal(int ''count'')</kbd>
| <code>void SetScavengeItemsGoal(int ''count'')</code>
| Set the number of Scavenge items needed.
| Set the number of Scavenge items needed.
|-
|-
| <code>SetScavengeItemsRemaining</code>
| <kbd>SetScavengeItemsRemaining</kbd> || <kbd>void SetScavengeItemsRemaining(int ''count'')</kbd>
| <code>void SetScavengeItemsRemaining(int ''count'')</code>
| Set the number of Scavenge items remaining.
| Set the number of Scavenge items remaining.
|-
|-
| <code>StageInfo_Execute</code>
| <kbd>StageInfo_Execute</kbd> || <kbd>void StageInfo_Execute(''stageInfo'', ''stageDefaults'')</kbd>
| <code>void StageInfo_Execute(''stageInfo'', ''stageDefaults'')</code>
| Execute a stage table, i.e. move parameters to DirectorOptions, do callbacks and so on.
| Execute a stage table, i.e. move parameters to DirectorOptions, do callbacks and so on.
|-
|-
| <code>StartAssault</code>
| <kbd>StartAssault</kbd> || <kbd>void StartAssault()</kbd>
| <code>void StartAssault()</code>
| Tells all existing nextbots to swap into assault mode and not hide/dither/loiter.
| Tells all existing nextbots to swap into assault mode and not hide/dither/loiter.
|-
|-
| <code>StringToFile</code>
| <kbd>StringToFile</kbd> || <kbd>void StringToFile(string ''path'', string ''string'')</kbd>
| <code>void StringToFile(string ''file'', string ''string'')</code>
| Stores the ''string'' into the file located at left4dead2/ems/''path''. ''Path'' can contain folders -- in that case folders will be automatically created. Also ''path'' supports special names "." and "..", which indicate "current folder" and "parent folder" respectfully.
| Stores the string into the file.  
 
Things to consider:
* You can save much more than you can read with FileToString() -- you are limited only by script execution time. Check carefully what are you writing!
* Due to a bug, string is saved with zero byte at the end. Such file is still read back properly by FileToString(), but that means you can save only 16383 bytes of useful information if you plan to read the file back.
* There is no way to remove files using VScript.
|-
|-
| <code>Time</code>
| <kbd>Time</kbd> || <kbd>float Time()</kbd>
| <code>float Time()</code>
| Get the current server time.
| Get the current server time.
|-
|-
| <code>[[List_of_L4D2_Script_Functions/TraceLine| TraceLine]]</code>
| <kbd>[[/TraceLine| TraceLine]]</kbd> || <kbd>bool TraceLine(table ''traceTable'')</kbd>
| <code>bool TraceLine(table ''traceTable'')</code>
| Uses a configuration table to do a raytrace, puts return information into the table for return usage.
| Uses a configuration table to do a raytrace, puts return information into the table for return usage.
|-
|-
| <code>UniqueString</code>
| <kbd>UniqueString</kbd> || <kbd>string UniqueString(string ''input''="")</kbd>
| <code>string UniqueString(string ''input'')</code>
| Generate a string guaranteed to be unique across the life of the script VM, with an optional root string. Input will be converted to a string by calling {{Code|tostring()}} member function of that input, before passing it to {{Code|DoUniqueString}} function. Useful for adding data to tables when not sure what keys are already in use in that table. Throws error on null value.
| 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.
|-
|-
| <code>VSquirrel_OnCreateScope</code>
| <kbd>VSquirrel_OnCreateScope</kbd> || <kbd>table VSquirrel_OnCreateScope(value, table ''scope'')</kbd>
| <code>table VSquirrel_OnCreateScope(value, table ''scope'')</code>
| Creates a new scope with the name of value in the submitted table (includes unique params).
| Creates a new scope with the name of value in the submitted table (includes unique params).
|-
|-
| <code>VSquirrel_OnReleaseScope</code>
| <kbd>VSquirrel_OnReleaseScope</kbd> || <kbd>void VSquirrel_OnReleaseScope(table ''createdScope'')</kbd>
| <code>void VSquirrel_OnReleaseScope(table ''createdScope'')</code>
| Removes a scope created via VSquirrel_OnCreateScope.
| Removes a scope created via VSquirrel_OnCreateScope.
|-
|-
| <code>__CollectGameEventCallbacks</code>
| <kbd>__CollectGameEventCallbacks</kbd> || <kbd>void __CollectGameEventCallbacks(scope)</kbd>
| <code>void __CollectGameEventCallbacks(scope)</code>
| Wrapper that registers callbacks for both [[#OnGameEvent_x|OnGameEvent_''x'' ]] and {{Code|OnScriptEvent_}} functions. Done using the {{Code|__CollectEventCallbacks}} function.
| Wrapper that registers callbacks for both [[#OnGameEvent_x|OnGameEvent_''x'']] and <code>OnScriptEvent_</code> functions. Done using the <code>__CollectEventCallbacks</code> function.
|-
|-
| <code>__CollectEventCallbacks</code>
| <kbd>__CollectEventCallbacks</kbd> || <kbd>void __CollectEventCallbacks(scope, prefix, globalTableName, regFunc)</kbd>
| <code>void __CollectEventCallbacks(scope, prefix, globalTableName, regFunc)</code>
| Overloaded function, used by the above one like this: {{Code|__CollectEventCallbacks(scope, "OnGameEvent_", "GameEventCallbacks", ::RegisterScriptGameEventListener)}}
| Overloaded function, used by the above one like this: <code>__CollectEventCallbacks(scope, "OnGameEvent_", "GameEventCallbacks", ::RegisterScriptGameEventListener)</code>
|-
|-
| <code>__ExecutePreSpawn</code>
| <kbd>__ExecutePreSpawn</kbd> ||  
|  
|  
|  
|-
|-
| <code>__FinishSpawn</code>
| <kbd>__FinishSpawn</kbd> ||  
|  
|  
|  
|-
|-
| <code>__ReplaceClosures</code>
| <kbd>__ReplaceClosures</kbd> || <kbd>void __ReplaceClosures(script, scope)</kbd>
| <code>void __ReplaceClosures(script, scope)</code>
|  
|  
|-
|-
| <code>__RunEventCallbacks</code>
| <kbd>__RunEventCallbacks</kbd> || <kbd>void __RunEventCallbacks(event, params, prefix, globalTableName, bWarnIfMissing)</kbd>
| <code>void __RunEventCallbacks(event, params, prefix, globalTableName, bWarnIfMissing)</code>
| Call all functions in the callback array for the given game event.
| Call all functions in the callback array for the given game event.
|-
|-
| <code>__RunGameEventCallbacks</code>
| <kbd>__RunGameEventCallbacks</kbd> || <kbd>void __RunGameEventCallbacks(event, params </kbd>
| <code>void __RunGameEventCallbacks(event, params </code>
| Wrapper for {{Code|__RunEventCallbacks()}}
| Wrapper for <code>__RunEventCallbacks()</code>
|}
|}


=== Debugging functions ===
=== Squirrel Standard Library ===
Functions for interacting with the debugger. Some of them are documented [[L4D2_EMS/Appendix:_Debugging|here]].
{{↑|toc}}
 
*BeginScriptDebug
*EndScriptDebug
*ScriptDebugAddTextFilter
*ScriptDebugAddTrace
*ScriptDebugAddWatch
*ScriptDebugAddWatches
*ScriptDebugAddWatchPattern
*ScriptDebugClearTraces
*ScriptDebugClearWatches
*ScriptDebugDraw
*ScriptDebugDrawWatches
*ScriptDebugDumpKeys
*ScriptDebugHook
*ScriptDebugIterateKeys
*ScriptDebugIterateKeysRecursive
*ScriptDebugRemoveTextFilter
*ScriptDebugRemoveTrace
*ScriptDebugRemoveWatch
*ScriptDebugRemoveWatches
*ScriptDebugRemoveWatchPattern
*ScriptDebugTextDraw
*ScriptDebugTextPrint
*ScriptDebugTextTrace
*ScriptDebugTraceAll
*__VScriptServerDebugHook


=== Standard Squirrel library ===
{{sq}} List of functions that come from Squirrel's [https://web.archive.org/web/20230608131548if_/http://www.squirrel-lang.org/doc/squirrel3.pdf#%5B%7B%22num%22%3A392%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C115%2C490.402%2Cnull%5D built-in functions] and [https://web.archive.org/web/20131204090523if_/http://squirrel-lang.org:80/doc/sqstdlib3.pdf standard library]. Not all functions from the linked documentations are present in VScript, such as the {{Code|blob}} library.


{{sq}}Standard Squirrel library functions (consult official Squirrel language league for more details):
{| class = "standard-table" style = "width: 100%;"
{| class="standard-table"
|- style="position:sticky; z-index:10; top:0"
! Function
! Function !! Signature !! Description
|-
|-
|abs
| <kbd>array</kbd> || <kbd>array(int ''size'', any ''fill'' = null)</kbd>
| Create and returns array of a specified size where each element is set to {{Code|''fill''}}.
|-
|-
|acos
| <kbd>assert</kbd> || <kbd>assert(bool ''exp'')</kbd>
| Throws an exception if exp is evaluated to false.
|-
|-
|array
| <kbd>callee</kbd> || <kbd>function callee()</kbd>
| Returns the currently running closure.
|-
|-
|asin
| <kbd>collectgarbage</kbd> || <kbd>int collectgarbage()</kbd>
| Runs the garbage collector and returns the number of reference cycles found(and deleted) This function only works on garbage collector builds.
|-
|-
|assert
| <kbd>compilestring</kbd> || <kbd>function compilestring(string ''string'', string ''buffername'' = null)</kbd>
| Compiles a string containing a squirrel script into a function and returns it.
|-
|-
|atan
| <kbd>enabledebuginfo</kbd> || <kbd>void enabledebuginfo(any ''enable'')</kbd>
| Enable/disable the debug line information generation at compile time. enable != null enables . enable == null disables.
|-
|-
|atan2
| <kbd>error</kbd> || <kbd>void error(string ''x'')</kbd>
| Prints x in the standard error output.
|-
|-
|ceil
| <kbd>getconsttable</kbd> || <kbd>table getconsttable()</kbd>
| Returns the const table of the VM.
|-
|-
|collectgarbage
| <kbd>getroottable</kbd> || <kbd>table getroottable()</kbd>
| Returns the root table of the VM.
|-
|-
|compilestring
| <kbd>getstackinfos</kbd> || <kbd>table getstackinfos(int ''stacklevel'')</kbd>
| 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|<source>{
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"
}
}</source>
}}
|-
|-
|cos
| <kbd>newthread</kbd> || <kbd>coroutine newthread(function ''threadfunc'')</kbd>
| Creates a new cooperative thread object(coroutine) and returns it
|-
|-
|exp
| <kbd>print</kbd> || <kbd>void print(string ''message'')</kbd>
| Prints message to console without any line feed after.
|-
|-
|fabs
| <kbd>resurrectunreachable</kbd> || <kbd>array resurrectunreachable()</kbd>
| 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.
|-
|-
|floor
| <kbd>setconsttable</kbd> || <kbd>table setconsttable(table ''consttable'')</kbd>
| Sets the const table of the VM which also returns the previous const table. 
|-
|-
|format
| <kbd>seterrorhandler</kbd> || <kbd>void seterrorhandler(function ''func'')</kbd>
| Sets the runtime error handler .
|-
|-
|getconsttable
| <kbd>setroottable</kbd> || <kbd>table setroottable(table ''roottable'')</kbd>
| Sets the root table of the VM which also returns the previous root table.
|-
|-
|getroottable
| <kbd>suspend</kbd> || <kbd>void suspend(any ''ret'')</kbd>
| Suspends the coroutine that called this function.
|-
|-
|getstackinfos
| <kbd>type</kbd> || <kbd>string type(any ''obj'')</kbd>
| Return the 'raw' type of an object without invoking the metatmethod '_typeof'.
|}
 
==== Math ====
The built-in [https://web.archive.org/web/20131204090523if_/http://squirrel-lang.org:80/doc/sqstdlib3.pdf#%5B%7B%22num%22%3A111%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C115%2C725%2Cnull%5D Squirrel math library].
 
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
|-
|log
| <kbd>abs</kbd> || <kbd> int abs(float ''x'')</kbd>
| Returns the absolute value of <kbd>x</kbd> as an integer.
|-
|-
|log10
| <kbd>acos</kbd> || <kbd> float acos(float ''x'')</kbd>
| Returns the arccosine of <kbd>x</kbd>.
|-
|-
|lstrip
| <kbd>asin</kbd> || <kbd> float asin(float ''x'')</kbd>
| Returns the arcsine of <kbd>x</kbd>.
|-
|-
|pow
| <kbd>atan</kbd> || <kbd> float atan(float ''x'')</kbd>
| Returns the arctangent of <kbd>x</kbd>.
|-
|-
|print
| <kbd>atan2</kbd> || <kbd> float atan2(float ''x'', float ''y'')</kbd>
| Returns the arctangent of <kbd>x/y</kbd>.
|-
|-
|rand
| <kbd>ceil</kbd> || <kbd> float ceil(float ''x'')</kbd>
| Returns a float value representing the smallest integer that is greater than or equal to <kbd>x</kbd>.
|-
|-
|rstrip
| <kbd>cos</kbd> || <kbd> float cos(float ''x'')</kbd>
| Returns the cosine of <kbd>x</kbd>.
|-
|-
|setconsttable
| <kbd>exp</kbd> || <kbd> float exp(float ''x'')</kbd>
| Returns the exponential value (<kbd>e^x</kbd>) of the float parameter <kbd>x</kbd>.
|-
|-
|seterrorhandler
| <kbd>fabs</kbd> || <kbd> float fabs(float ''x'')</kbd>
| Returns the absolute value of <kbd>x</kbd> as a float.
|-
|-
|setroottable
| <kbd>floor</kbd> || <kbd> float floor(float ''x'')</kbd>
| Returns a float value representing the largest integer that is less than or equal to <kbd>x</kbd>.
|-
|-
|type
| <kbd>log</kbd> || <kbd> float log(float ''x'')</kbd>
| Returns the natural logarithm of <kbd>x</kbd>.
|-
|-
|sin
| <kbd>log10</kbd> || <kbd> float log10(float ''x'')</kbd>
| Returns the logarithm base-10 of <kbd>x</kbd>.
|-
|-
|split
| <kbd>pow</kbd> || <kbd> float pow(float ''x'', float ''y'')</kbd>
| Returns <kbd>x</kbd> raised to the power of <kbd>y</kbd>.
|-
|-
|sqrt
| <kbd>rand</kbd> || <kbd> int rand()</kbd>
| Returns a pseudorandom integer in the range 0 to <kbd>RAND_MAX</kbd>.
|-
|-
|srand
| <kbd>sin</kbd> || <kbd> float sin(float ''x'')</kbd>
| Returns the sine of <kbd>x</kbd>.
|-
|-
|strip
| <kbd>sqrt</kbd> || <kbd> float sqrt(float ''x'')</kbd>
| Returns the square root of <kbd>x</kbd>.
|-
|-
|suspend
| <kbd>srand</kbd> || <kbd> void srand(float ''seed'')</kbd>
| Sets the starting point for generating a series of pseudorandom integers.
|-
|-
|tan
| <kbd>tan</kbd> || <kbd> float tan(float ''x'')</kbd>
| Returns the tangent of <kbd>x</kbd>.
|}
|}


== See Also ==
==== Strings ====
=== Helpers ===
The built-in [https://web.archive.org/web/20131204090523if_/http://squirrel-lang.org:80/doc/sqstdlib3.pdf#%5B%7B%22num%22%3A119%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C115%2C725%2Cnull%5D Squirrel string library].
*[[L4D2_Vscript_Helpers|L4D2 VScript Helpers]]


=== Intros ===
{| class="standard-table" style="width:100%"
*[[VScript]]
! Function !! Signature !! Description
*[[L4D2 VScripts]]
|-
*[[Mutation Gametype (L4D2)]]
| <kbd>format</kbd> || <kbd>string format(string ''format'', args...)</kbd>
*[[L4D2 Gamemodes File]]
| Returns a [[w:printf format string|formatted string]]. Same rules as the standard C functions (except * is not supported).
=== Documentations ===
|-
*[[VSLib]]
| <kbd>lstrip</kbd> || <kbd>string lstrip(string ''str'')</kbd>
*[[L4D2 Vscript Examples]]
| Removes whitespace characters at the beginning of the given string.
*[[L4D2_Director_Scripts|L4D2 Director Scripts]]
|-
*[[L4D2_Decrypted_mutations|Decrypted Mutation Vscripts]]
| <kbd>rstrip</kbd> || <kbd>string rstrip(string ''str'')</kbd>
*[[L4D2_Level_Design/Boss_Prohibition|L4D2 Level Design/Boss Prohibition]]
| Removes whitespace characters at the end of the given string.
*[[L4D2_Level_Design/Custom_Finale|Custom Finales]] ''Contains all original finale scripts as reference.''
|-
*[[L4D2 EMS|Extended Mutation System]]
| <kbd>split</kbd> || <kbd>array split(string ''str'', string ''separator'')</kbd>
| 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.
|-
| <kbd>strip</kbd> || <kbd>string strip(string ''str'')</kbd>
| Removes whitespace characters at both the beginning and end of the given string.
|}


=== Miscellaneous ===
=== Script Debug ===
*{{ent||logic_script}}
{{|toc}}
*{{ent|trigger_finale}}
Functions for interacting with the debugger. Some of them are documented [[L4D2_EMS/Appendix:_Debugging|here]].
*{{ent|info_director}}
*[[List of L4D2 Cvars]]


{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>BeginScriptDebug</kbd> || <kbd>void BeginScriptDebug()</kbd>
|
|-
| <kbd>EndScriptDebug</kbd> || <kbd>void EndScriptDebug()</kbd>
|
|-
| <kbd>ScriptDebugAddTextFilter</kbd> || <kbd>void ScriptDebugAddTextFilter()</kbd>
|
|-
| <kbd>ScriptDebugAddTrace</kbd> || <kbd>void ScriptDebugAddTrace()</kbd>
|
|-
| <kbd>ScriptDebugAddWatch</kbd> || <kbd>void ScriptDebugAddWatch()</kbd>
|
|-
| <kbd>ScriptDebugAddWatches</kbd> || <kbd>void ScriptDebugAddWatches()</kbd>
|
|-
| <kbd>ScriptDebugAddWatchPattern</kbd> || <kbd>void ScriptDebugAddWatchPattern()</kbd>
|
|-
| <kbd>ScriptDebugClearTraces</kbd> || <kbd>void ScriptDebugClearTraces()</kbd>
|
|-
| <kbd>ScriptDebugClearWatches</kbd> || <kbd>void ScriptDebugClearWatches()</kbd>
|
|-
| <kbd>ScriptDebugDefaultWatchColor</kbd> || <kbd>void ScriptDebugDefaultWatchColor()</kbd>
|
|-
| <kbd>ScriptDebugDraw</kbd> || <kbd>void ScriptDebugDraw()</kbd>
|
|-
| <kbd>ScriptDebugDrawWatches</kbd> || <kbd>void ScriptDebugDrawWatches()</kbd>
|
|-
| <kbd>ScriptDebugDumpKeys</kbd> || <kbd>void ScriptDebugDumpKeys()</kbd>
|
|-
| <kbd>ScriptDebugHook</kbd> || <kbd>void ScriptDebugHook()</kbd>
|
|-
| <kbd>ScriptDebugIterateKeys</kbd> || <kbd>void ScriptDebugIterateKeys()</kbd>
|
|-
| <kbd>ScriptDebugIterateKeysRecursive</kbd> || <kbd>void ScriptDebugIterateKeysRecursive()</kbd>
|
|-
| <kbd>ScriptDebugRemoveTextFilter</kbd> || <kbd>void ScriptDebugRemoveTextFilter()</kbd>
|
|-
| <kbd>ScriptDebugRemoveTrace</kbd> || <kbd>void ScriptDebugRemoveTrace()</kbd>
|
|-
| <kbd>ScriptDebugRemoveWatch</kbd> || <kbd>void ScriptDebugRemoveWatch()</kbd>
|
|-
| <kbd>ScriptDebugRemoveWatches</kbd> || <kbd>void ScriptDebugRemoveWatches()</kbd>
|
|-
| <kbd>ScriptDebugRemoveWatchPattern</kbd> || <kbd>void ScriptDebugRemoveWatchPattern()</kbd>
|
|-
| <kbd>ScriptDebugText</kbd> || <kbd>void ScriptDebugText()</kbd>
|
|-
| <kbd>ScriptDebugTextDraw</kbd> || <kbd>void ScriptDebugTextDraw()</kbd>
|
|-
| <kbd>ScriptDebugTextPrint</kbd> || <kbd>void ScriptDebugTextPrint()</kbd>
|
|-
| <kbd>ScriptDebugTextTrace</kbd> || <kbd>void ScriptDebugTextTrace()</kbd>
|
|-
| <kbd>ScriptDebugTraceAll</kbd> || <kbd>void ScriptDebugTraceAll()</kbd>
|
|-
| <kbd>ScriptDebugWatches</kbd> || <kbd>void ScriptDebugWatches()</kbd>
|
|-
| <kbd>__VScriptServerDebugHook</kbd> || <kbd>__VScriptServerDebugHook()</kbd>
|
|}
== See also ==
{{↑|toc}}
* [[VScript]]
* [[VScript Fundamentals]]
* {{sq}} [[Squirrel]]
* {{l4d2}} [[L4D2 Vscript Examples|L4D2 VScripts Examples]]
* {{l4d2}} [[L4D2 Vscript Helpers|L4D2 VScript Helpers]]
* {{csgo}} [[List of CS:GO Script Functions]]
* {{tf2}} [[Team_Fortress_2/Scripting/Script_Functions|List of TF2 Script Functions]]
* {{portal2}} [[List of Portal 2 Script Functions]]
* {{asrd}} [[List of Reactive Drop Script Functions|List of AS:RD Script Functions]]
* [[List of Script Libraries]]
<!--
Move some of these to [[L4D2 VScripts]], [[L4D2 VScript Examples]] and [[Mutation Gametype (L4D2)]]. First one especially as it's supposed to be the hub for everything L4D2 VScripting.
For some of these pages, it might be better to make use of Github and its file viewer?
* {{l4d2}} [[L4D2_Vscript_Helpers|L4D2 VScript Helpers]]
=== [[L4D2 EMS|EMS]] === <-- This page can't be edited :/
*[[L4D2_Decrypted_mutations|Decrypted Mutation VScripts]]
*[[Mutation Gametype (L4D2)]]
*[[L4D2 Gamemodes File]]
-->
[[Category:Left 4 Dead 2]]
[[Category:Left 4 Dead 2]]
[[Category:Scripting]]
[[Category:Scripting]]

Latest revision as of 20:51, 26 July 2025

English (en)中文 (zh)Translate (Translate)

Squirrel This list contains engine-related Squirrel variables, functions, and constants available for Left 4 Dead 2 Left 4 Dead 2 VScripts. Some can be printed in-game with the script_help command when the game is run in developer mode with the -dev or -allowdebug parameters. Others have been found from data mining, for example with script g_ModeScript.DeepPrintTable(getroottable()), and from the Expanded Mutation System documentation.

For functions and parameters related to theDirectorOptionstable, see the L4D2 Director Scripts page.

Instances

Name Type Description
Convars Convars ↓ Provides an interface to read and change the values of console variables.
Director CDirector ↓ Provides a limited interface to the Director.
Entities CEntities ↓ Allows searching of currently-spawned entities.
EntityOutputs CScriptEntityOutputs ↓ Allows reading and changing of entities' output data.
NavMesh CNavMesh ↓ An interface to the Navigation Mesh.
NetProps CNetPropManager ↓ Allows reading and updating the network properties of an entity.
ResponseCriteria CScriptResponseCriteria ↓ Allows reading the response criteria of an entity.

Script Scopes

Name Type Description
DirectorScript table Script scope for Director scripts. Contains the active DirectorOptions table.
g_ClearoutTable table (null) NONE
g_MapScript table Script scope of map-specific vscripts, which also contains utilty functions.
g_ModeScript table Script scope of mode-specific vscripts like mutations. This scope also has the g_MapScript scope as its environment.
g_RoundState table Scope of the start box used in the Holdout or Dash mutation.
g_rr ↓ table An interface to the Response System.

Variables

Name Type Description
Documentation table Contains the printed strings from the script_help command.
GameEventCallbacks table Table of registered game event callbacks.
print_indent integer Spaces to indent prints by except ones from realPrint. Defaults to 0.
_PublishedHelp table NONE
ScriptEventCallbacks table Table of registered script event 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 to avoid magic numbers by giving them self-documenting names.

Instance Type Value
_charsize_ integer 1
_floatsize_ integer 4
_intsize_ integer 4
_version_ string "Squirrel 3.0.4 stable"
_versionnumber_ integer 304
RAND_MAX integer 32767
SPAWN_FLAGS table
SPAWN		= 1
NOSPAWN		= 2
TARGETSPAWN	= 4
PI float 3.14159













Classes

CBaseEntity

toc ↑ Extended by: CBaseAnimating ↓ CBaseTrigger ↓ CEnvEntityMaker ↓ CInfoItemPosition ↓ CPointTemplate ↓ CPointScriptTemplate ↓ CPointScriptUseTarget ↓

Note.pngNote:Entity vscript classes are created when script handle for an entity of such type is created for the first time (i.e. class CInfoItemPosition won't exist or have help strings shown by script_help until script handle for some info_item_position entity was made, for example by SpawnEntityFromTable, Entities.FindByClassname, etc.)

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
__KeyValueFromInt
__KeyValueFromString
__KeyValueFromVector
bool __KeyValueFromInt(string key, int value)
bool __KeyValueFromString(string key, string value)
bool __KeyValueFromVector(string key, Vector value)
Sets an entity keyvalue from a specific data type. Returns true if successfully set, false if it the key does not exist.

This simply changes the value without executing any other code that may be needed for the entity to fully process the keyvalue, such as code for updating the entity's internal network state. This can create unexpected side effects on already-spawned entities such as visual changes being delayed for clients.

Tip.pngTip:Use Netprops ↓ and update the keyvalue's corresponding prop instead, as this correctly updates the networking state and results in an immediate update.
Warning.pngWarning:__KeyValueFromFloat doesn't exist
ApplyAbsVelocityImpulse void ApplyAbsVelocityImpulse(Vector impulse) Apply a Velocity Impulse as a world space impulse vector.
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.
ConnectOutput void ConnectOutput(string output, string function) Adds an I/O connection that will call the named function when the specified output fires.
DisconnectOutput void DisconnectOutput(string output, string function) Removes a connected script function from an I/O event.
FirstMoveChild handle FirstMoveChild() Returns the first entity parented to this one. Needs to be used in combination with NextMovePeer to iterate over all children.
Tip.pngTip:Example usage:
for (local child = entity.FirstMoveChild(); child != null; child = child.NextMovePeer())
GetAngles QAngle GetAngles() Returns the orientation of the entity in the world.
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.
GetCenter Vector GetCenter() Get world space center of object - absolute coords.
GetClassname string GetClassname() Returns the entity class. This includesplayerandinfected.
GetContext variable GetContext(string name) Looks up a response context and returns it if available. May return string, float, or null (if the context isn't found).
Icon-Bug.pngBug*:Always returns null for contexts with numeric value
Icon-Bug.pngBug*:Can return value for expired contexts
GetEntityHandle unknown GetEntityHandle() Get a C++ EHANDLE reference of the entity. This is an opaque type not directly usable by Squirrel, not a normal script handle. Only necessary for CPointScriptUseTarget functions. ↓
GetEntityIndex int GetEntityIndex() Returns the entity index. This is the same type of index used in most game events.
GetForwardVector Vector GetForwardVector() Get the forward vector of the entity.
GetHealth int GetHealth() Returns the current health of the entity (does not include survivor temporary health).
GetLocalAngles QAngle GetLocalAngles() Returns the orientation of the entity relative to it's parent or attachment point.
GetLocalAngularVelocity QAngle GetLocalAngularVelocity() Maybe local angvel
GetLocalOrigin Vector GetLocalOrigin() Returns the origin of the entity relative to it's parent or attachment point.
GetLocalVelocity Vector GetLocalVelocity() Get Entity relative velocity
GetMaxHealth int GetMaxHealth() Returns the maximum health of the entity.
GetModelName string GetModelName() Returns the file name of the model used by the entity (if applicable).
GetMoveParent handle GetMoveParent() If in hierarchy, retrieves the entity's parent
GetName string GetName() Returns the targetname of the entity.
GetOrigin Vector GetOrigin() Returns the origin of the entity in the world.
GetOwnerEntity handle GetOwnerEntity() Get the owner entity, if there is one.
GetPreTemplateName string GetPreTemplateName() Get the entity name stripped of template unique decoration.
GetRootMoveParent handle GetRootMoveParent() If in hierarchy, walks up the hierarchy to find the root parent.
GetScriptId string GetScriptId() Returns the name of the entity's think function.
Tip.pngTip:Retrieve the actual script identifier with NetProps.GetPropString(ent, "m_iszScriptId")
GetScriptScope table GetScriptScope() Retrieve the table storing the Entity Script associated with this entity, null otherwise.
GetVelocity Vector GetVelocity() Returns a local velocity Vector.
IsPlayer bool IsPlayer() Does this entity belong to the player class.
IsValid bool IsValid() Whether the handle still belongs to an entity that's still valid, could become invalid in cases such as the entity, like a destroyed func_breakable.(?)
Kill void Kill() Removes the entity.
NextMovePeer handle NextMovePeer() Returns the next child of this entity's parent. Used to continue iteration from FirstMoveChild().
OverrideFriction void OverrideFriction(float duration, float friction) Takes duration, value for a temporary override
PrecacheModel int PrecacheModel(string filename) Precache a model after the map has loaded and return index of the model.
PrecacheScriptSound void PrecacheScriptSound(string soundscript) Precache a sound file, used by the specified soundscript.
SetAngles void SetAngles(QAngle direction) Sets the orientation of the entity.
SetContext void SetContext(string name, string value, float duration) Stores any key/value pair in this entity's dialog contexts. Value must be a string. Will last for duration (set -1 to mean 'forever').
SetContextNum void SetContextNum(string name, float value, float duration) Stores any key/value pair in this entity's dialog contexts. Value must be a number (int or float). Will last for duration (set -1 to mean 'forever').
SetForwardVector void SetForwardVector(Vector direction) Set the orientation of the entity to have this forward vector.
SetFriction void SetFriction(float friction) Set PLAYER friction, ignored for objects.
SetGravity void SetGravity(float gravity) Set PLAYER gravity, ignored for objects.
SetHealth void SetHealth(int health) Changes the health value of the entity. Does not check whether to kill players.
SetLocalAngles void SetLocalAngles(QAngle direction) Sets the entity orientation relative to it's parent or attachment point.
SetLocalOrigin void SetLocalOrigin(Vector position) Sets the entity position relative to it's parent or attachment point.
SetMaxHealth void SetMaxHealth(int health) Changes the maximum health value of the entity.
SetModel void SetModel(string modelName) Changes the model of the entity (if applicable).
SetOrigin void SetOrigin(Vector position) Sets the world entity position.
SetVelocity void SetVelocity(Vector velocity) Sets the entity velocity.
TakeDamage void TakeDamage(float damage, int damageType, CBaseEntity attacker) Damages the entity.
TakeDamageEx void TakeDamageEx(CBaseEntity inflictor, CBaseEntity attacker, CBaseEntity weapon, Vector vecDamageForce, Vector vecDamagePosition, float damage, int damageType) Damages the entity (extended).
ValidateScriptScope bool ValidateScriptScope() Ensures an entity has a script scope, if it doesn't have one then one is created. Returns true if created successfully.

Hooks

If one of these functions are declared in an Entity Script, the entity will run this function automatically in the appropriate situation.

Function Signature Description
Input[InputName] bool Input[InputName]() Called when the entity receives an I/O input that matches the function's name. The name that follows after Input must match the casing, i.e. InputFireUser1 will catch any "FireUser1" inputs but not "fireuser1" inputs from the ent_fire command.

Variables activator and caller are added to the scope when the function is called. The function also must return a boolean value which controls if the input is allowed to be processed, i.e. returning false cancels the input.

OnEntText string OnEntText() If ent_text is used on an entity and this function exists, it will be called every tick. Returns a string that gets displayed as part of the ent_text overlay. This is a handy feature for displaying script data on objects when you ent_text the object, or running arbitrary code (such as turning on additional debugging visualizations) is using ent_text. NOTE: ent_text_allow_script 1 must be set in order for this feature to be active.
OnPostSpawn void OnPostSpawn() Called after the entity spawns, which is after scripts and players have loaded. This could be used to have an entity register itself with a master script, or adjusting the entity parameters in a programmatic way.
Precache void Precache() Called after the script executes. Can be used to call precache functions for models and sounds on map load.

CBaseAnimating

toc ↑ Extends CBaseEntity ↑ Extended by: CBaseFlex ↓ CTerrorWeapon ↓

Script handle class for animating entities such as props.

Methods

Function Signature Description
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 the attachment ID's angles as a QAngle.
GetAttachmentBone int GetAttachmentBone(int ID) Get the attachment ID's parent bone index.
GetAttachmentOrigin Vector GetAttachmentOrigin(int ID) Get the attachment ID's origin as a Vector.
GetBodygroup int GetBodygroup(int ID) Get the bodygroup value by bodygroup ID.
GetBodygroupName string GetBodygroupName(int ID) Get the bodygroup ID's name.
GetBodygroupPartName string GetBodygroupPartName(int group, int part) Get name by group and part.
GetBoneAngles QAngle GetBoneAngles(int ID) Get the bone ID's angles as a QAngle.
GetBoneOrigin Vector GetBoneOrigin(int ID) Get the bone ID's origin Vector.
GetModelScale float GetModelScale() Get the model scale.
GetSequence int GetSequence() Get the currently playing sequence 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.
IsSequenceFinished bool IsSequenceFinished() Returns true if the current sequence has finished 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.
LookupSequence int LookupSequence(string name) Looks up a sequence by sequence name or activity name. 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.
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.
SetPoseParameter float SetPoseParameter(int ID, float value) Sets a pose parameter value. Returns the effective value after clamping or looping.
SetSequence void SetSequence(int ID) Plays a sequence by sequence ID.

CBaseFlex

toc ↑ Extends CBaseAnimating ↑

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

Methods

Function Signature Description
GetCurrentScene handle GetCurrentScene() Returns the instance of the oldest active scene entity (if any).
GetSceneByIndex handle GetSceneByIndex(int index) Returns the instance of the scene entity at the specified index.
PlayScene float PlayScene(string sceneFile, float delay) Play the specified .vcd file, causing the related characters to speak and subtitles to play.

CBaseCombatCharacter

toc ↑ Extends CBaseFlex ↑

Combat character. Common and uncommon infected and witches belong to this.

Methods

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

CTerrorPlayer

toc ↑ Extends CBaseCombatCharacter ↑

Script handle class for player entities. Both survivors and special infected belong to this.

Methods

Function Signature Description
DropItem void DropItem(string classname) Make the player drop an item/weapon from their inventory, by classname.
Extinguish void Extinguish() Extinguish a burning player.
EyeAngles QAngle EyeAngles() Returns the direction the player is looking.
EyePosition Vector EyePosition() Returns the players eye position in the world.
GetActiveWeapon handle GetActiveWeapon() Get the player's active weapon entity.
GetAliveDuration float GetAliveDuration() Returns the time the character has been alive (only valid when alive).
GetButtonMask int GetButtonMask() Returns a bitfield of currently pressed buttons. Test against each value to see which button is pressed. Recognized buttons are:
1 - IN_ATTACK
2 - IN_JUMP
4 - IN_DUCK
8 - IN_FORWARD
16 - IN_BACK
32 - IN_USE
2048 - IN_ATTACK2
8192 - IN_RELOAD
GetHealthBuffer float GetHealthBuffer() Returns the current temporary health of a survivor.
GetNetworkIDString string GetNetworkIDString() Get the player's network (i.e. Steam) ID.
GetPlayerName string GetPlayerName() Get the players name.
GetPlayerUserId int GetPlayerUserId() Get the players userID.
GetSenseFlags int GetSenseFlags() Get the current bot sense flags. Test against each value to see which flag is set. Values:
1 - BOT_CANT_SEE
2 - BOT_CANT_HEAR
4 - BOT_CANT_FEEL
GetSpecialInfectedDominatingMe CTerrorPlayer GetSpecialInfectedDominatingMe() Get the Special Infected dominating this Survivor.
GetSurvivorSlot int GetSurvivorSlot() Get the player's slot number.
GetZombieType int GetZombieType() If an infected, find out what type. Recognized ZombieTypes are: Smoker = 1, Boomer = 2, Hunter = 3, Spitter = 4, Jockey = 5, Charger = 6, Witch = 7, Tank = 8, Survivor = 9
Tip.pngTip:witch is not a CTerrorPlayer derived entity therefore trying to check her zombie type with this method would result in an error. Use check like ent.GetClassname() == "witch" instead.
GiveAmmo void GiveAmmo(int amount) Adds ammo for the player's primary weapon ammo pool.
GiveItem void GiveItem(string itemname) Give an item/weapon by name. Uses the same names as the give console command(health, katana, rifle_ak47, etc.).
Icon-Bug.pngBug*:Cannot give item to a player that is currently running a chainsaw (same applies to GiveItemWithSkin)
GiveItemWithSkin void GiveItemWithSkin(string classname, int skin) Gives the player a skinned weapon.
GiveUpgrade void GiveUpgrade(int upgradeType) Give a primary weapon upgrade. Possible values:
0 - UPGRADE_INCENDIARY_AMMO
1 - UPGRADE_EXPLOSIVE_AMMO
2 - UPGRADE_LASER_SIGHT
HasEverBeenInjured bool HasEverBeenInjured(int team) Returns true if the character has ever been injured by a member of the given team.
HitWithVomit void HitWithVomit() Cover the player with a boomer vomit attack.
IsAdrenalineActive bool IsAdrenalineActive() Return true if adrenaline is active.
IsDead bool IsDead() Returns true when a player is dead for more than 5 seconds. Note that taking over a dying bot immediately switches to the dead phase.
IsDominatedBySpecialInfected bool IsDominatedBySpecialInfected() Return true if being dominated by a Special Infected (i.e. held by smoker, charger, jockey or hunter)
IsDying bool IsDying() Returns true when a player has recently died for 5 seconds. Note that taking over a dying bot skips the dying phase.
IsFiringWeapon bool IsFiringWeapon() Return true if player is firing a weapon.
IsIncapacitated bool IsIncapacitated() Returns true if in incapacitated state.
IsHangingFromLedge bool IsHangingFromLedge() Returns true if in ledge hang state.
IsGettingUp bool IsGettingUp() Return true if player is currently getting up.
IsGhost bool IsGhost() Returns true if in ghost infected state.
IsImmobilized bool IsImmobilized() Return true if currently immobilized.
Tip.pngTip:Is true when in getting up animation, punched by tank, flung by charger, caught by charger, smoker or hunter, hanging, incapacitated, dead, being healed, using kit, defibrillator or unpacking an upgrade pack, using timed button, pouring gas can, handing in cola or using minigun (not true when staggering or caught by jockey)
IsInCombat bool IsInCombat() Return true if currently in combat.
IsIT bool IsIT() Return true if currently IT from bile.
IsOnFire bool IsOnFire() Returns true if a player is on fire, e.g. Standing in fireworks crate explosions.
IsOnThirdStrike bool IsOnThirdStrike() Return true if on third-strike.
IsStaggering bool IsStaggering() Return true if player is staggering.
IsSuppressingFallingDamage bool IsSuppressingFallingDamage() Returns true if falling damage is currently suppressed, which is if the entity received the IgnoreFallDamage or IgnoreFallDamageWithoutReset input, provided that it is still active.
IsSurvivor bool IsSurvivor() Returns true if entity is on the survivor or l4d1 survivor team (Otherwise, unknown, spectator or infected).
RemoveUpgrade void RemoveUpgrade(int upgradeType) Remove a primary weapon upgrade. Possible values:
0 - UPGRADE_INCENDIARY_AMMO
1 - UPGRADE_EXPLOSIVE_AMMO
2 - UPGRADE_LASER_SIGHT
ReviveByDefib void ReviveByDefib() Revive a dead player by defib.
ReviveFromIncap void ReviveFromIncap() Revive an incapacitated player.
SetFriction void SetFriction(int friction) Set player friction.
SetGravity void SetGravity(int gravity) Set player gravity.
SetHealthBuffer void SetHealthBuffer(float health) Sets the temporary health of a survivor; No effect for infecteds. Does not incapacitate or kill when set to zero.
SetReviveCount void SetReviveCount(int count) Sets the number of times a survivor has been revived, and updates third-strike state (B&W) and heartbeat sound.
Icon-Bug.pngBug*:Doesn't update the m_isGoingToDie netprop, which controls the dying quotes.
SetSenseFlags void SetSenseFlags(int flags) Set the set of bot sense flags. Combine values to set appropriate flags:
1 - BOT_CANT_SEE
2 - BOT_CANT_HEAR
4 - BOT_CANT_FEEL
SnapEyeAngles void SnapEyeAngles(QAngle angles) Sets the view angles. Supports rolling the view.
Stagger void Stagger(Vector position) Stagger a player away from a position. Use Vector(0,0,0) to just stagger forward.
SwitchToItem bool SwitchToItem(string classname) Make the player switch to an item/weapon by classname. Returns true if the switch was performed.
TryGetPathableLocationWithin Vector TryGetPathableLocationWithin(float radius) Get a location on the nav the player can path to within the desired radius.
UseAdrenaline void UseAdrenaline(float duration) Causes Adrenaline's speed and visual effect, no change to health.

CTerrorWeapon

toc ↑ Extends CBaseAnimating ↑.

All weapon entities that are part of a player's inventory, holstered or not, belongs to this. All Clip2 related functions have no gameplay effects (unless weapon scripts are modded), but can be used for your own custom weapon ammunition needs. E.g. A Hunting Rifle with 3 Oxygen Tank throwables.

Note.pngNote:weapon_chainsaw's fuel can be modified with the Clip1 related functions!
Note.pngNote:weapon_pistol's GetDefaultClip1 is always treated as a single pistol, but GetMaxClip1 will account for dual pistols as well!

Methods

Function Signature Description
Clip1 int Clip1() Current amount of ammo in a weapon's clip.
Clip2 int Clip2() Current 'secondary clip' ammo count. Always -1 in default game.
GetDefaultClip1 int GetDefaultClip1() Clip count of a weapon when its newly picked up.
GetDefaultClip2 int GetDefaultClip2() Default 'secondary clip' ammo count. Always -1 in default game; Only a positive value if a custom weapon script has clip2_size set.
GetMaxClip1 int GetMaxClip1() Max clip count a weapon can hold. Will always return the same value as the GetDefaultClip1 function.
GetMaxClip2 int GetMaxClip2() Max 'secondary clip' count. Always -1 in default game; Only a positive value if a custom weapon script has clip2_size set. Will always return the same value as the GetDefaultClip2 function.
GiveDefaultAmmo void GiveDefaultAmmo() Revert both weapons's clip to their default values.
Reload bool Reload() Forces the weapon to reload if it is not full. Returns true if it could start a weapon reload.
SetClip1 void SetClip1(int amount) Sets a weapon's clip count.
SetClip2 void SetClip2(int amount) Sets a weapon's 'secondary clip' count; Works just fine but has no gameplay effect in default game.

CBaseTrigger

toc ↑ Extends CBaseEntity ↑

Entity class for all entities inheriting CBaseTrigger

Methods

Function Signature Description
Disable void Disable() Disable the trigger. Identical to the Disable input.
Enable void Enable() Enable the trigger. Identical to the Enable input.
IsTouching bool IsTouching(handle entity) Checks whether the passed entity is touching the trigger.

AI_Response

toc ↑ Opaque type representing a return value from the old response system.

Methods

Function Signature Description
GetMatchScore Relative score of this match's quality (based on number of criteria matched)).

CDirector

toc ↑ Instances ↑ Game Instance: Director

Provides methods for reading information and forcing events in the AI Director. To influence the Director behavior, the DirectorOptions table is used instead.

Methods

Function Signature Description
AreAllSurvivorsInBattlefield bool AreAllSurvivorsInBattlefield() Returns true if all Survivors are in the battlefield.
AreAllSurvivorsInFinaleArea bool AreAllSurvivorsInFinaleArea() True when all survivors are within the finale area.
AreTeamsFlipped bool AreTeamsFlipped() True when teams are flipped in Versus modes.
ClearCachedBotQueries void ClearCachedBotQueries() Mark all cached bot query results as invalid.
ForceNextStage void ForceNextStage() Push the ScriptedMode to next stage - i.e. request GNSS be called.
GetAveragedSurvivorSpan float GetAveragedSurvivorSpan() Get the distance between the lead and trailing survivors, smoothed over time.
GetAveragedSurvivorSpeed float GetAveragedSurvivorSpeed() Get the rate at which the lead survivor is moving along the flow, smoothed over time.
GetClosestActivePipeBomb CBaseEntity GetClosestActivePipeBomb(Vector origin) Returns the closest active pipe bomb from this origin.
GetClosestCharacterWhoIsIT CBaseCombatCharacter GetClosestCharacterWhoIsIT(CBaseCombatCharacter character) Returns the closest character who is IT to the passed character.
GetClosestSurvivor CTerrorPlayer GetClosestSurvivor(Vector origin, bool bIncludeIncap, bool bIncludeOnRescueVehicle) Returns the closest Survivor from the passed origin, if incapped Survivors are included in search, or on rescue vehicle.
GetCommonInfectedCount int GetCommonInfectedCount() Returns number for infected currently spawned.
GetFurthestSurvivorFlow float GetFurthestSurvivorFlow() Get the maximum distance along the flow that the survivors have reached.
GetGameMode string GetGameMode() Get the current game mode. If called in a mutation, it returns the current mutation, not the base mode. Will only look for the specific game mode/mutation.
GetGameModeBase string GetGameModeBase() Get the current base game mode. Does not return the current mutation. Example, if looking for survival, it will also count for all game modes using survival as base. Such as Mutation 15 (Survival Versus)
GetHighestFlowSurvivor CTerrorPlayer GetHighestFlowSurvivor() Returns the Survivor with the highest flow.
GetHoldoutCooldownEndTime float GetHoldoutCooldownEndTime() Get the end time of the cooldown timer.
GetLowestFlowSurvivor CTerrorPlayer GetLowestFlowSurvivor() Returns the Survivor with the lowest flow.
GetMapName string GetMapName() Get the current map name.
GetMapNumber int GetMapNumber() Return the current map number.
GetMissionWipes int GetMissionWipes() Returns the current number of mission wipes.
GetPendingMobCount int GetPendingMobCount() Returns the number of infected waiting to spawn.
GetRandomSurvivor CTerrorPlayer GetRandomSurvivor() Returns a random alive Survivor.
GetSurvivorSet int GetSurvivorSet() Get the current survivor set. L4D1 Survivors = 1, L4D2 Survivors = 2.
Icon-Bug.pngBug*:Calling this inside mapspawn_addon or response_testbed_addon will give survivor set value of previous loaded map
GetTimeSinceSpecialZombieKilled float GetTimeSinceSpecialZombieKilled(int zombieType) Returns the time since the passed zombie type was killed.
GetTotalElapsedMissionTime float GetTotalElapsedMissionTime() Returns the total elapsed mission time.
HasAnySurvivorLeftSafeArea bool HasAnySurvivorLeftSafeArea() True when one or more survivors have left the starting safe area.
IsAnySurvivorBypassingTank bool IsAnySurvivorBypassingTank() True when one or more survivors are bypassing the Tank.
IsAnySurvivorInCombat bool IsAnySurvivorInCombat() Returns true if any survivor recently dealt or took damage.
IsAnySurvivorInExitCheckpoint bool IsAnySurvivorInExitCheckpoint() True when one or more survivors are in the exit checkpoint.
IsAnySurvivorInStartArea bool IsAnySurvivorInStartArea() True when one or more survivors are in the starting safe area.
IsFinale bool IsFinale() True when the finale has started.
IsFinaleEscapeInProgress bool IsFinaleEscapeInProgress() True when the finale escape is in progress.
IsFinaleVehicleReady bool IsFinaleVehicleReady() True when the finale vehicle is ready.
IsFinaleWon bool IsFinaleWon() Returns true if the finale has been won.
IsFirstMapInScenario bool IsFirstMapInScenario() True if the first map in a scenario.
IsL4D1Campaign bool IsL4D1Campaign() Return true if the current campaign is originally from L4D1.
IsLocationFoggedToSurvivors bool IsLocationFoggedToSurvivors(Vector origin) Returns true if the passed location is fogged to Survivors.
IsPlayingIntro bool IsPlayingIntro() True if the intro is currently playing.
IsPlayingOnConsole bool IsPlayingOnConsole() Return true if game is running on a console (such as Xbox 360).
IsSessionStartMap bool IsSessionStartMap() True if the map is the start of the session.
IsSinglePlayerGame bool IsSinglePlayerGame() Return true if game is in single player.
IsValid bool IsValid() WhetherDirectorbelongs to a valid entity. Seems futile to use.
IsTankInPlay bool IsTankInPlay() Returns true if any tanks are aggro on survivors.
L4D1SurvivorGiveItem void L4D1SurvivorGiveItem() Let the L4D1 survivors know that now is a good time to give the players an item.
PlayMegaMobWarningSounds void PlayMegaMobWarningSounds() Plays a horde scream sound and asks survivors to speak incoming horde lines.
RegisterForbiddenTarget void RegisterForbiddenTarget(CBaseEntity entity) Registers a target entity as forbidden.
ResetMobTimer void ResetMobTimer() Trigger a mob as soon as possible when in BUILD_UP.
ResetSpecialTimers void ResetSpecialTimers() Reset all special timers (by type and by slot) so that hopefully mobs will spawn asap.
SetHoldoutCooldownEndTime void SetHoldoutCooldownEndTime(float time)
UnregisterForbiddenTarget void UnregisterForbiddenTarget(CBaseEntity entity) Unregisters a target entity as forbidden.
UserDefinedEvent1
UserDefinedEvent2
UserDefinedEvent3
UserDefinedEvent4
void UserDefinedEvent1()
void UserDefinedEvent2()
void UserDefinedEvent3()
void UserDefinedEvent4()
When called, these trigger the appropriate output of the info_director entity.
WarpAllSurvivorsToBattlefield void WarpAllSurvivorsToBattlefield() Warp all Survivors to the battlefield.
WarpAllSurvivorsToCheckpoint void WarpAllSurvivorsToCheckpoint() Warp all Survivors to the exit checkpoint.
WarpAllSurvivorsToFinale void WarpAllSurvivorsToFinale() Warp all Survivors to the finale radio.

CEntities

toc ↑ Instances ↑ 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, "weapon_*") )
{
  // ...
}
for (local ent; ent = Entities.FindByClassname(ent, "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 "weapon_" or it returns null.


Methods

Function Signature Description
FindByClassname handle FindByClassname(handle previous, string class) Find entities by class name.
FindByClassnameNearest handle FindByClassnameNearest(string class, Vector origin, float radius) Find the entity with the given class name nearest to the specified point.
FindByClassnameWithin handle FindByClassnameWithin(handle previous, string class, Vector origin, float radius) Find entities by class name within a radius, while within a set radius.
FindByModel handle FindByModel(handle previous, string filename) Find entities by a model path name.
FindByName handle FindByName(handle previous, string name) Find entities by targetname. Special ones including !bill will work.
FindByNameNearest handle FindByNameNearest(string name, Vector origin, float radius) Find entities by targetname nearest to a point, while within a set radius. Special ones including !bill will work.
FindByNameWithin handle FindByNameWithin(handle previous, string name, Vector origin, float radius) Find entities by targetname within a radius. Special ones including !bill will work.
FindByTarget handle FindByTarget(handle previous, string targetname) Find entities by its target.
FindInSphere handle FindInSphere(handle previous, Vector origin, float radius) Returns entities within a set radius.
First handle First() The first entity that spawned (Always worldspawn). Can be used to begin an iteration for a list of entities.
Next handle Next(handle previous) At the given reference of a previously-found entity, returns the next one after it in the list.
IsValid bool IsValid() Whether the handle for Entities is a valid handle.

CEnvEntityMaker

toc ↑ 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(CBaseEntity entity) Create an entity at the location of a specified entity instance.
SpawnEntityAtLocation void SpawnEntityAtLocation(Vector origin, QAngle orientation) Create an entity at a specified location and orientation.
SpawnEntityAtNamedEntityOrigin void SpawnEntityAtNamedEntityOrigin(string name) Create an entity at the location of a named entity.


CInfoItemPosition

toc ↑ Extends CBaseEntity ↑

Script handle class for info_item_position.

Methods

Function Signature Description
GetGroup Get the group number for this item position
GetRarity Get the rarity for this item position.
GetReplaceParm Get a replacement parameter by index.
SetGroup Set the group number for this item position.
SetRarity Set the rarity for this item position.

CNavMesh

toc ↑ Instances ↑ Game Instance: NavMesh

An interface to the Navigation Mesh.

Methods

Function Signature Description
FindLadderAlongRay CNavLadder FindLadderAlongRay(Vector startpos, Vector endpos, TerrorNavArea ignoreArea) Get nav ladder from ray.
FindNavAreaAlongRay TerrorNavArea FindNavAreaAlongRay(Vector startpos, Vector endpos, TerrorNavArea ignoreArea) Get nav area from ray.
GetAllAreas void GetAllAreas(table) Fills a passed in table of all nav areas.
GetAllLadders void GetAllLadders(table) Fills a passed in table of all nav ladders.
GetAreasWithAttributes void GetAreasWithAttributes(int bits, table) Fills a passed in table of all nav areas that have the specified attributes.
GetLadderByID CNavLadder GetLadderByID(int id) Get nav ladder by ID.
GetLadderCount int GetLadderCount() Return total number of nav ladders.
GetNavArea TerrorNavArea GetNavArea(Vector origin, float flBeneath) Given a position in the world, return the nav area that is closest and at the same height, or beneath it.
GetNavAreaByID TerrorNavArea GetNavAreaByID(int id) Get nav area by ID.
GetNavAreaCount int GetNavAreaCount() Return total number of nav areas.
GetNavAreasFromBuildPath bool GetNavAreasFromBuildPath(TerrorNavArea startArea, TerrorNavArea endArea, Vector goalPos, float flMaxPathLength, int teamID, bool ignoreNavBlockers, table) Fills table with areas from a path. Returns whether a path was found. If 'endArea' is NULL, will compute a path as close as possible to 'goalPos'.
GetNavAreasInRadius void GetNavAreasInRadius(Vector origin, float radius, table) Fills a passed in table of nav areas within radius.
GetNavAreasOverlappingEntityExtent void GetNavAreasOverlappingEntityExtent(CBaseEntity entity, table) Fills passed in table with areas overlapping entity's extent.
GetNearestNavArea TerrorNavArea GetNearestNavArea(Vector origin, float maxDist, bool checkLOS, bool checkGround) Given a position in the world, return the nav area that is closest and at the same height, or beneath it.
GetObstructingEntities void GetObstructingEntities(table) Fills a passed in table of all obstructing entities.
IsValid bool IsValid() Whether the handle belongs to a valid entity. Redundant as navigation meshes are not entity related.
NavAreaBuildPath bool NavAreaBuildPath(TerrorNavArea startArea, TerrorNavArea endArea, Vector goalPos, float flMaxPathLength, int teamID, bool ignoreNavBlockers) Returns true if a path exists. If 'endArea' is NULL, will compute a path as close as possible to 'goalPos'.
NavAreaTravelDistance float NavAreaTravelDistance(TerrorNavArea startArea, TerrorNavArea endArea, float flMaxPathLength) Compute distance between two areas. Return -1 if can't reach 'endArea' from 'startArea'.
RegisterAvoidanceObstacle void RegisterAvoidanceObstacle(CBaseEntity entity) Registers an entity as an avoidance obstacle.
UnblockRescueVehicleNav void UnblockRescueVehicleNav() Unblock the rescue vehicle nav areas so bots can path through them.
UnregisterAvoidanceObstacle void UnregisterAvoidanceObstacle(CBaseEntity entity) Unregisters an entity as an avoidance obstacle.

TerrorNavArea

toc ↑ This is a script handle class for nav areas. Nav areas may also have attributes applied on them.

Methods

Function Signature Description
AddIncomingConnection void AddIncomingConnection(TerrorNavArea area, int dir) Add areas that connect TO this area by a ONE-WAY link.
ComputeDirection int ComputeDirection(Vector point) Return direction from this area to the given point.
ConnectTo void ConnectTo(TerrorNavArea area, int dir) Connect this area to given area in given direction. If you set direction to -1, it will be automatically applied.
ConnectToLadder void ConnectToLadder(CNavLadder ladder) Connect this area to given ladder.
Contains bool Contains(TerrorNavArea 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 noDepthTest) Draw area as a filled rectangle of the given color.
Disconnect void Disconnect(TerrorNavArea area) Disconnect this area from given area.
DisconnectLadder void DisconnectLadder(CNavLadder ladder) Disconnect this area from given ladder.
FindRandomSpot Vector FindRandomSpot() Get random origin within extent of area.
GetAdjacentArea TerrorNavArea GetAdjacentArea(int dir, int nAreas) Return the n'th adjacent area in the given direction.
GetAdjacentAreas void GetAdjacentAreas(int dir, table) Fills a passed in table with all adjacent areas in the given direction.
GetAdjacentCount int GetAdjacentCount(int dir) Get the number of adjacent areas in the given direction.
GetAttributes int GetAttributes() Get area attribute bits.
GetAvoidanceObstacleHeight float GetAvoidanceObstacleHeight() Returns the maximum height of the obstruction above the ground.
GetCenter Vector GetCenter() Get center origin of area.
GetCorner Vector GetCorner(int corner) Get corner origin of area.
GetDistanceSquaredToPoint float GetDistanceSquaredToPoint(Vector pos) Return shortest distance between point and this area.
GetDoor CBaseEntity GetDoor() Returns the door entity above the area.
GetElevator CBaseEntity GetElevator() Returns the elevator if in an elevator's path.
GetElevatorAreas void GetElevatorAreas(table) Fills a passed in table with a collection of areas reachable via elevator from this area.
GetID int GetID() Get area ID.
GetIncomingConnections void GetIncomingConnections(int dir, table) Fills a passed in table with areas connected TO this area by a ONE-WAY link (ie: we have no connection back to them).
GetLadders void GetLadders(int dir, table) Fills a passed in table of ladders in direction.
GetParent TerrorNavArea 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, null if no name.
GetPlayerCount int GetPlayerCount(int team) Return number of players of given team currently within this area (team of zero means any/all).
GetRandomAdjacentArea TerrorNavArea GetRandomAdjacentArea(int 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.
GetSpawnAttributes int GetSpawnAttributes() Get spawn attribute bits.
GetTimeSinceCleared float GetTimeSinceCleared() Returns the time since the area was cleared.
GetZ float GetZ(Vector pos) Returns the height of the area at the specified point.
HasAttributes bool HasAttributes(int bits) Has area attribute bits.
HasAvoidanceObstacle bool HasAvoidanceObstacle(float maxHeight) Returns true if there's a large, immobile object obstructing this area.
HasSpawnAttributes bool HasSpawnAttributes(int bits) Has spawn attribute bits.
IsBlocked bool IsBlocked(int team, bool affectsFlow) Return true if team is blocked in this area.
IsBottleneck bool IsBottleneck() Returns true if area is a bottleneck.
IsCleared bool IsCleared(CTerrorPlayer player) Returns true if this area has been cleared for the player.
IsCompletelyVisibleToTeam bool IsCompletelyVisibleToTeam(int team) Return true if given area is completely visible from somewhere in this area by someone on the team.
IsConnected bool IsConnected(TerrorNavArea area, int 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)
IsConnectedLadder bool IsConnectedLadder(CNavLadder ladder, int dir) Return true if this area is connected to ladder in given direction.
IsCoplanar bool IsCoplanar(TerrorNavArea area) Return true if this area and given area are approximately co-planar.
IsDamaging bool IsDamaging() Return true if continuous damage (ie: fire) is in this area.
IsDegenerate bool IsDegenerate() Return true if this area is badly formed.
IsEdge bool IsEdge(int 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(TerrorNavArea 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(int team) Return true if any portion of this area is visible to anyone on the given team.
IsRoughlySquare bool IsRoughlySquare() Return true if this area is approximately square.
IsSpawningAllowed bool IsSpawningAllowed() Returns true if spawning is allowed in this area.
IsUnderwater bool IsUnderwater() Return true if area is underwater.
IsValid bool IsValid() Whether the handle belongs to a valid area.
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 point.
MarkAreaCleared void MarkAreaCleared(CTerrorPlayer player) Mark this area as cleared for the player.
MarkAreaNotCleared void MarkAreaNotCleared() Mark this area as not cleared.
MarkAsBlocked void MarkAsBlocked(int 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(int bits) Removes area attribute bits.
RemoveOrthogonalConnections void RemoveOrthogonalConnections(int dir) Removes all connections in directions to left and right of specified direction.
RemoveSpawnAttributes void RemoveSpawnAttributes(int bits) Remove spawn attribute bits.
SetAttributes void SetAttributes(int 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.
SetSpawnAttributes void SetSpawnAttributes(int bits) Set spawn attribute bits.
UnblockArea void UnblockArea() Unblocks this area.

CNavLadder

toc ↑ This is a script handle class for nav ladders.

Methods

Function Signature Description
ConnectTo void ConnectTo(TerrorNavArea area) Connect this ladder to given area.
Disconnect void Disconnect(TerrorNavArea area) Disconnect this ladder from given area.
GetBottomArea TerrorNavArea GetBottomArea() Area of the bottom of the ladder.
GetBottomOrigin Vector GetBottomOrigin() World coords of the bottom of the ladder.
GetDir int GetDir() Return the way the ladder faces (ie: surface normal of climbable side).
GetID int GetID() Get ladder ID.
GetLadderEntity CBaseEntity GetLadderEntity() Returns the ladder entity.
GetLength float GetLength() Return the length of the ladder.
GetPosAtHeight Vector GetPosAtHeight(float height) Return x,y coordinate of the ladder at a given height.
GetTopArea TerrorNavArea GetTopArea() Area of the top of the ladder.
GetTopOrigin Vector GetTopOrigin() World coords of the top of the ladder.
GetWidth float GetWidth() Return the width of the ladder.
IsConnected bool IsConnected(TerrorNavArea area, int dir) Return true if given ladder is connected in given direction.
IsInUse bool IsInUse(CBaseEntity ignore) Return true if someone is on this ladder (other than 'ignore').
IsUsableByTeam bool IsUsableByTeam(int teamID) Returns true if ladder is usable for team.
IsValid bool IsValid() Whether the handle belongs to a valid ladder.

CNetPropManager

toc ↑

Instances ↑ Game Instance: NetProps

Allows reading and updating the network properties 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. i.e. m_itTimer.m_timestamp.

Warning.pngWarning:Each netprop has a set size in bits, exceeding the size may desync the clients from the server causing unpredictable behavior.

Methods

Function Signature Description
GetPropArraySize int GetPropArraySize(CBaseEntity entity, string propertyName) Returns the size of an netprop array, or -1.
GetPropEntity CBaseEntity GetPropEntity(CBaseEntity entity, string propertyName) Reads an EHANDLE-valued netprop (21 bit integer). Returns the script handle of the entity.
GetPropEntityArray CBaseEntity GetPropEntityArray(CBaseEntity entity, string propertyName, int arrayElement) Reads an EHANDLE-valued netprop (21 bit integer) from an array. Returns the script handle of the entity.
GetPropFloat float GetPropFloat(CBaseEntity entity, string propertyName) Reads a float-valued netprop.
GetPropFloatArray float GetPropFloatArray(CBaseEntity entity, string propertyName, int arrayElement) Reads a float-valued netprop from an array.
GetPropInt int GetPropInt(CBaseEntity entity, string propertyName) Reads an integer-valued netprop.
GetPropIntArray int GetPropIntArray(CBaseEntity entity, string propertyName, int arrayElement) Reads an integer-valued netprop from an array.
GetPropString string GetPropString(CBaseEntity entity, string propertyName) Reads an string-valued netprop.
GetPropStringArray string GetPropStringArray(CBaseEntity entity, string propertyName, int arrayElement) Reads an string-valued netprop from an array.
GetPropType string GetPropType(CBaseEntity entity, string propertyName) Returns the name of the netprop type as a string.
GetPropVector Vector GetPropVector(CBaseEntity entity, string propertyName) Reads a 3D vector-valued netprop.
Todo:  Does it work for other dimensions too?
GetPropVectorArray Vector GetPropVectorArray(CBaseEntity entity, string propertyName, int arrayElement) Reads a 3D vector-valued netprop from an array.
HasProp bool HasProp(CBaseEntity entity, string propertyName) Checks if a netprop exists.
SetPropEntity void SetPropEntity(CBaseEntity entity, string propertyName, CBaseEntity value) Sets an EHANDLE-valued netprop (21 bit integer) to reference the specified entity.
SetPropEntityArray void SetPropEntityArray(CBaseEntity entity, string propertyName, CBaseEntity value, int arrayElement) Sets an EHANDLE-valued netprop (21 bit integer) from an array to reference the specified entity.
SetPropFloat void SetPropFloat(CBaseEntity entity, string propertyName, float value) Sets a netprop to the specified float.
SetPropFloatArray void SetPropFloatArray(CBaseEntity entity, string propertyName, float value, int arrayElement) Sets a netprop from an array to the specified float.
SetPropInt void SetPropInt(CBaseEntity entity, string propertyName, int value) Sets a netprop to the specified integer.
SetPropIntArray void SetPropIntArray(CBaseEntity entity, string propertyName, int value, int arrayElement) Sets a netprop from an array to the specified integer.
SetPropString void SetPropString(CBaseEntity entity, string propertyName, string value) Sets a netprop to the specified string.
SetPropStringArray void SetPropStringArray(CBaseEntity entity, string propertyName, string value, int arrayElement) Sets a netprop from an array to the specified string.
SetPropVector void SetPropVector(CBaseEntity entity, string propertyName, Vector value) Sets a netprop to the specified vector.
SetPropVectorArray void SetPropVectorArray(CBaseEntity entity, string propertyName, Vector value, int arrayElement) Sets a netprop from an array to the specified vector.

CScriptEntityOutputs

toc ↑ Instances ↑ Game Instance: EntityOutputs

Allows reading and changing of entities' output data.

Methods

Function Signature Description
AddOutput void AddOutput(CBaseEntity entity, string outputName, string targetName, string inputName, string parameter, float delay, int timesToFire) Adds a new output to the entity.
GetNumElements int GetNumElements(CBaseEntity entity, string outputName) Returns the number of array elements.
GetOutputTable void GetOutputTable(CBaseEntity entity, string outputName, table, int arrayElement) Fills the passed table with output information.
HasAction bool HasAction(CBaseEntity entity, string outputName) Returns true if an action exists for the output.
HasOutput bool HasOutput(CBaseEntity entity, string outputName) Returns true if the output exists.
RemoveOutput void RemoveOutput(CBaseEntity entity, string outputName, string targetName, string inputName, string parameter) Removes an output from the entity.

CScriptResponseCriteria

toc ↑

Instances ↑ Game Instance: ResponseCriteria

Allows reading the response rules of an entity.

Methods

Function Signature Description
GetTable void GetTable(CBaseEntity entity, table) Fills the passed table with all criteria.
GetValue string GetValue(CBaseEntity entity, string criteriaName) Returns a string.
HasCriterion bool HasCriterion(CBaseEntity entity, string criteriaName) Returns true if the criterion exists.

Convars

toc ↑ Instances ↑ Game Instance: Convars

An interface to manipulate the convars on the server.

Methods

Function Signature Description
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. Convars without FCVAR_USERINFO or non-existent ones return empty string
GetStr string GetStr(string name) Returns the convar as a string. Returns null if no such convar.
GetFloat float GetFloat(string name) Returns the convar as a float. Returns null if no such convar.
SetValue void SetValue(string name, value) Sets the value of the convar. Supported types are bool, int, float, string.

CPointTemplate

toc ↑ Extends CBaseEntity ↑

Script handle class for point_template.

Hooks

table PreSpawnInstance(string entityClass, string entityName)
If this is defined, it will be called right before the entity is created, and any KeyValues returned will be assigned to the entity.
This could be used to dynamically assign target names, colors, even models. Unfortunately, models don't work like one would think. Yes, it is possible to change that gas tank into a football model, will even keep the weapon_gascan class, but it won't behave like one.
function PreSpawnInstance( entityClass, entityName )
{
	return 
	{ 
   		rendercolor = "0 255 0"
   		targetname = "mySpawnedEntity"
	}
}
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.
function PostSpawn( entities )
{
	foreach( name, handle in entities )
	{
		printl( name + ": " + handle )
	}
}

CPointScriptTemplate

toc ↑ Extends CBaseEntity ↑

Script handle class for point_script_template.

Methods

Function Signature Description
AddTemplate void AddTemplate(string, handle) Add an entity to the template spawner.
SetGroupSpawnTables void SetGroupSpawnTables(handle, handle) Cache the group spawn tables.


CPointScriptUseTarget

toc ↑ Extends CBaseEntity ↑

Script handle class for the point_script_use_target entity.

Methods

Function Signature Description
CanShowBuildPanel void CanShowBuildPanel(bool showPanel) Sets if the UI panel for the button is shown.
GetUseModelName string GetUseModelName() Get the entity name of the prop bound to this button.
SetProgressBarText void SetProgressBarText(string text) Sets the use text for the button UI.
SetProgressBarSubText void SetProgressBarText(string text) Sets the subtext below the progress bar for the button UI.
SetProgressBarFinishTime void SetProgressBarFinishTime(float time) Sets the total time the button takes to use. If '0', no progress bar will be displayed.
SetProgressBarCurrentProgress void SetProgressBarCurrentProgress(float time) Sets the current use progress. It can be used to save the use progress when the user releases the use key.
StopUse void StopUse() Stop the current use action.


Members

These variables are only available in the Entity Script after the entity has spawned. They're a custom C++ class, CHandles which also is sometimes referred as EHANDLEs (Entity Handles). These can't be used or modified like the usual script handles, and really is only meant for verifications with comparing the output of theCBaseEntity ↑::GetEntityHandle()method.

Instance Type Description
UseModelEntity [C++] CHandle<CBaseEntity> The Use Model prop associated with this entity.
PlayerUsingMe [C++] CHandle<CBaseEntity> The current using player.
Todo: Recheck on this old info: Is it not 0 / null if not being used?
.

Hooks

These VScript methods are called on the script set in the Entity Scripts keyvalue for the point_script_use_target.

Function Signature Description
OnUseFinished void OnUseFinished() Called when the player has used this button for at least 'FinishTime' seconds.
OnUseStart bool OnUseStart() This breaks point_script_use_target when declared. Use ConnectOutput() and hook a function to the OnUseStarted output instead.
OnUseStop void OnUseStop(float timeUsed) Called when the player stops using this button. Passes the time this button has been used (time between StartUse and now).
Precache void Precache() Called by the game engine when the entity first spawns, immediately after this script is run.

Decider

toc ↑ An isolated instance of a rulescript database.

Methods

Function Signature Description
constructor
AddRule bool AddRule(handle CRule) Add a CRule object (defined in rulescript_base.nut)
FindAllMatches handle FindAllMatches(handle query, float leeway) Returns an array of all matching responses. If leeway is nonzero, all results scoring within 'leeway' of the best score return.
FindBestMatch handle FindBestMatch(handle query) Query the database and return the best result found. If multiple of equal score found, an arbitrary one returns.
IsValid bool IsValid() Whether the object belongs to a valid entity(?).


regexp

toc ↑ The built-in Squirrel class for regular expressions.

Methods

Function Signature Description
constructor regexp()
capture [table] capture(str, [start]) 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(str) Returns a true if the regular expression matches the string str, otherwise returns false.
search table search(str, [start]) 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


CCallChainer

toc ↑ 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 functionPrefix, 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

toc ↑ 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 functionPrefix, 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.


LateBinder

toc ↑

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

toc ↑

Vector

toc ↑ Squirrel equivalent of the C++ Vector class. It is a three-dimensional vector with overloaded arithmetic operations for both Vectors and scalar values.

Methods

Function Signature Description
constructor Vector(float x = 0, float y = 0, float z = 0) Creates a new vector with the specified Cartesian coordiantes.
Cross float 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. Faster than the above method.
Length2D float Length2D() Returns the magnitude of the vector on the x-y plane. Meant to be used when working with the client's HUD.
Length2DSqr float Length2DSqr() Returns the square of the magnitude of the vector on the x-y plane. Faster than the above method.
Norm float Norm() Seems to also return the vector length.
Scale Vector Scale(float factor) Scales the vector magnitude.
ToKVString string ToKVString() Returns a string without separations commas.
Note.pngNote:Not required for the SpawnEntityWithTable function, as it understands the Vector data type.
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 (XYZ).
Vector - Vector Vector Returns the subtraction of both classes's members (XYZ).
Vector * int Vector Returns the multiplication of a Vector against a scalar.
Vector * float

QAngle

toc ↑ 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, float yaw = 0, float roll = 0) Creates a new QAngle.
Forward Vector Forward() Returns the Forward Vector of the angles.
Left Vector Left() Returns the left Vector of the angles.
Icon-Bug.pngBug*:Returns right Vector instead
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.
Tip.pngTip:Use this with the angles key when using the SpawnEntityWithTable function.
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).
QAngle - QAngle QAngle Subtraction of both classes's members (XYZ).
QAngle * int QAngle QAngle multiplied by a number.
QAngle * float

Vector2D, Vector4D

toc ↑ Two and four-dimensional equivalents of the Vector data type. Has the same overloaded operators.

Methods

Function Signature Description
constructor Vector2D(float x = 0, float y = 0) Creates a new 2D vector with the specified Cartesian coordinates.
constructor Vector4D(float x = 0, float y = 0, float z = 0, float w = 0) Creates a new 4D vector with the given coordinate numbers.
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. Faster than the above method.
Norm float Norm() Seems to also return the vector length.
ToKVString string ToKVString() Returns a string without separations commas.

Members

Instance Type Description
x float Cartesian X axis.
y float Cartesian Y axis.
z float Cartesian Z axis. Vector4D only.
w float Component for possibly creating homogeneous coordinates? Vector4D only.

Operations

Operation Return Type Description
Vector2D + Vector2D
Vector4D + Vector4D
Vector2D
Vector4D
Returns the sum of both classes's members (XYZ).
Vector2D - Vector2D
Vector4D - Vector4D
Vector2D
Vector4D
Returns the subtraction of both classes's members (XYZ).
Vector2D * int
Vector4D * int
Vector2D
Vector4D
Returns the multiplication of the given Vector variant against a scalar.
Vector2D * float
Vector4D * float

Quaternion

toc ↑ A Quaternion represents rotations in three-dimensional space.

Methods

Function Signature Description
constructor Quaternion() Creates a new identity quaternion.
constructor Quaternion(float x = 0,float y = 0,float z = 0,float w = 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 Quaternion Norm() Normalizes the 4D vector length.
Todo: What effect does this have in quaternions?
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

Operation Return Type Description
Quaternion + Quaternion Quaternion Sum of the two Quaternions.
Quaternion - Quaternion Quaternion Subtraction of the two Quaternions.
Quaternion * int Quaternion Quaternion multiplied by a number.
Quaternion * float

Scripted Mode

toc ↑ Enabling Scripted Mode makes a large amount of features like cm_ director options and various hooks available. Scripted Mode is enabled if a script (<current_mode_name>.nut) is present.

Warning.pngWarning:Only one addon is able to actively use these functions so using scripted mode features outside of mutations is conflict prone and discouraged

Scripted Mode data are stored under the g_ModeScript scope.

sm_utilities.nut

toc ↑ sm_utilities contains many wrapper functions for manipulating different features. Only a few of them are listed here, see the EMS tutorial for more examples. These functions are inside g_MapScript scope.

Function Signature Description
CheckOrSetMapCallback void CheckOrSetMapCallback(cb_name, cb_default) Pass a callback and default @ for it, if it doesnt exist in current table, place it there.
DeepPrintTable void DeepPrintTable(handle table, string prefix = "") Print out a table (and subtables) to the console. This works with classes as well (not instances).
DuplicateTable table DuplicateTable(table source) This returns a deep copy of the passed in table.
InjectTable void InjectTable(table override, table base) Inject the override data into the base table - i.e. add any new ones, overwrite dupes.
SpawnStartBox handle SpawnStartBox(centerobjname, useFloating, width, depth, barriermodel, min_gap) Auto-create a startbox that will give you a callback when the first player exits it.
TeleportPlayersToStartPoints void TeleportPlayersToStartPoints(string spawnpointName) Teleport players to start entities named by the argument - must have 4 spawnpoints.
Ticker_AddToHud void Ticker_AddToHud(table hudTable, string strInit, bool blink) Adds ticker data to a passed in HUDTable.
Ticker_NewStr void Ticker_NewStr(string newStr, float newTimeout) Sets the current Ticker string, w/an optional timeout value.
TimeToDisplayString string TimeToDisplayString(float disp_time) Convert a # of seconds to a displayable time string form m:ss


Hooks

toc ↑ Scripted mode provides hook functions, used by simply adding a function with the same name and arguments to the script, and are called back by the C++ code at the appropriate moments.

Todo: Everything to know about OnGamePlayStart and OnActivate.

OnShutdown

void OnShutdown(): Called as the mutation is shutdown, happens for multiple scenarios, such as map change or a mission being lost. To retrieve the reason, use such a code:

function OnShutdown()
{
	local reason = SessionState.ShutdownReason
	local nextmap = SessionState.NextMap

	printl("Mutation shut down under reason " + reason.tostring() + ", next map is " + nextmap)
}

OnActivate

void OnActivate(): Called after OnGameplayStart. Unknown anything else about it, comes likely from EMS and pulled via console command "script g_ModeScript.DeepPrintTable(getroottable())"

OnGameplayStart

void OnGameplayStart(): Called whenever the gameplay starts.

AllowBash

int AllowBash(handle basher, handle bashee): called whenever melee bash is used. Returns these values:

  • ALLOW_BASH_ALL - normal melee behavior
  • ALLOW_BASH_NONE - do nothing at all
  • ALLOW_BASH_PUSHONLY - applies physics push but deals no damage (including prevention of insta-kill ambush behavior)

AllowTakeDamage

bool AllowTakeDamage(table damageTable): Adding a function with this name in the script causes C++ to call it on all damage events. The damageTable is actually defined in scriptedmode.nut and filled in as appropriate before each call.

ScriptedDamageInfo <-
{
	Attacker = null				// hscript of the entity that attacked
	Victim = null				// hscript of the entity that was hit
	Inflictor = null			// hscript of the entity that was the inflictor
	DamageDone = 0				// copyback variable for how much damage done
	DamageType = -1				// copyback variable for what type of damage
	Location = Vector(0,0,0)	// where
	Weapon = null				// by what - often Null (say if attacker was a common)
}

Returning "false" causes the damage will be stopped and nothing will be done to the target (though animation/bloodstains/decals will probably still happen, sorry about that). The only fields read back by the C++ is DamageDone, so it can be used to change the damage value before it is applied, and DamageType, so it can be used to change the type of damage. The Type field is a bitfield, of which several key #def's are exported to script (DMG_HEADSHOT, DMG_BULLET, DMG_BUCKSHOT, DMG_MELEE, DMG_STUMBLE, DMG_BLAST, DMG_BLAST_SURFACE, DMG_BURN ). Some situations will trigger this event still and deal zero damage while reporting a normal damage value: 1. Falling from a slope that gives immunity to fall damage ( Dark Carnival First Chapter )

2. A tank rock hits you after a smoker grabbed you.

BotQuery

bool BotQuery(int queryflag, handle entity, bool defaultvalue): Hook to control survivor bot behavior. Only one known flag is supported.

  • BOT_QUERY_NOTARGET - Fired when a bot wants to bash a prop. Returning false disallows the bashing.

CanPickupObject

bool CanPickupObject(handle object): Hook function for deciding whether a given prop should be pickupable (HL2 style). Returning true makes the players able to pick up the object. Only functional for server side props. If this is defined it must return true in order the PickupObject() function to work.

InterceptChat

void InterceptChat(string message, CTerrorPlayer speaker): If you put a function with this name in your script, C++ will call it on all chat messages. Passing in the (annotated) chat string and the handle of the speaker. If the function returns false, it will prevent other players from seeing the chat message except for the player who entered it.

SetupModeHUD

[Todo]

UserConsoleCommand

void UserConsoleCommand(handle playerScript, arg): when a user does a scripted_user_func argument at console (or bound to a key) this function is called (if it exists). The playerscript is which players console it came from. You can pass strings or whatever, of course. So could do a switch statement off arg to give players special controls, etc.

OnGameEvent_x

void OnGameEvent_x(table params): A callback that is called when the game event x is fired. See resource\gameevents.res, resource\serverevents.res and resource\modevents.res for valid events. The callback functions can be registered independently from Scripted Mode, using: __CollectGameEventCallbacks(this) See EMS Appendix - Game Events for more information.

Global Functions

Printing and Drawing

toc ↑ 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
__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 testTable =
{
	integer = 20,
	string = "hello",
	array = [1, 2, 3]
};

printl("{");
__DumpScope(1, testTable);
printl("}");

Will print the following in console:

{
   string = "hello"
   array(ARRAY)
   [
      0 = 1
      1 = 2
      2 = 3
   ]
   integer = 20
}
ClientPrint void ClientPrint(CTerrorPlayer player, int destination, string message) Print a client message. If you pass null instead of a valid player, the message will be sent to all clients.
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 (cent, min, max, angles(p,y,r), vRgb, a, duration).
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 zTest, 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 lineOffset, 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 useViewCheck, float duration) Draw text on the screen, starting on the position of origin.
DumpObject void DumpObject(handle object) Dumps information about a class or instance.
HUDManageTimers void HUDManageTimers(int timerID, int command, float value) Manages the HUD timers. Valid command enumerations are: TIMER_DISABLE, TIMER_COUNTUP, TIMER_COUNTDOWN, TIMER_STOP, TIMER_SET
HUDPlace void HUDPlace(int slot, float x, float y, float width, float height) Sets the position of a HUD element. See L4D2_EMS/Appendix:_HUD
HUDReadTimer float HUDReadTimer(int timerID) Returns the value of a HUD timer. See L4D2_EMS/Appendix:_HUD
HUDSetLayout void HUDSetLayout(table HUDTable) Applies a HUD to the screen. See L4D2_EMS/Appendix:_HUD
Icon-Important.pngImportant:Scriptedmode feature, usable properly in mutations only
Msg void Msg(string message) Prints message to console without any line feed after.
print void print(string message) Prints message to console without any line feed after. Identical to Msg().
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.
ShowMessage void ShowMessage(string message) Print a HUD message on all clients.
Icon-Bug.pngBug*:Non-functional.
Say void Say(CTerrorPlayer player, string message, bool teamOnly) Calling this will have the specified player send the message to chat, either to teamOnly (true) or to everyone.
SendToConsole void SendToConsole(string command) Send a string to the console as a command.
SendToServerConsole void SendToServerConsole(string command) Send a string to the server console as a command.

Hooks

toc ↑

DebugTick

void DebugTick(): Called every tick, if a function with this name is in your script.

Note.pngNote:The Mutation/Mode name needs to be prefixed with "debug_" in order for this function to be called.

Update

void Update(): Called every second, if a function with this name is defined in the following scopes. Gives easy control over the flow of a game.

DirectorScript.Update

When defined in this scope early for example inside director_base(_addon).nut. Should not be used outside mutations as it would create conflict with other addons that would try this approach. Ideally never using this scope for it as there is very little if any reason to do so.

DirectorScript.MapScript.Update

Update function in this scope is already defined by default in scriptedmode.nut and shouldn't be changed as it takes care of functionality of the following helper functions that are also defined in the same scope which means if they need to be accessed while running a script outside g_ModeScript, g_MapScript or g_MapScript.LocalScript they need to be accessed as g_MapScript.ScriptedMode_....

Warning.pngWarning:Defining Update function in a <mapname>_finale.nut script ran by custom or scavenge finale type will break this functionality as it overwrites the initial Update function that takes care of it. This mistake was made in The Sacrifice finale (c7m3_port_finale.nut).
Function Signature Description
ScriptedMode_CallNextUpdate void ScriptedMode_CallNextUpdate(function callnext) Pass a function to this, it will get called once as part of next Update, for doing something 'soon but not now'
ScriptedMode_AddUpdate void ScriptedMode_AddUpdate(function updatefunc) Register arbitrary function without parameters to run every second (single function cannot be registered twice).
ScriptedMode_AddSlowPoll void ScriptedMode_AddSlowPoll(function updatefunc) Register arbitrary function without parameters to run every 3 seconds (single function cannot be registered twice).
ScriptedMode_RemoveUpdate void ScriptedMode_RemoveUpdate(function updatefunc) Removes a function that was before added by ScriptedMode_AddUpdate
ScriptedMode_RemoveSlowPoll void ScriptedMode_RemoveSlowPoll(function updatefunc) Removes a function that was before added by ScriptedMode_AddSlowPoll
DirectorScript.MapScript.LocalScript.Update

Update function defined in scripts ran with BeginScript/ScriptedPanicEvent inputs of info_director or in custom scripted stages is called here. Gauntlet finale type uses Update function defined in director_gauntlet.nut to recalculate allowed common infected limits based on player's progress towards the goal.

DirectorScript.MapScript.ChallengeScript.Update

Update function defined inside a mutation script for example in mymutation.nut.

Entity Manipulation

toc ↑

Function Signature Description
AddThinkToEnt void AddThinkToEnt(handle entity, string FuncName) Sets a function in the entity's script to rerun by itself constantly.
CommandABot bool CommandABot(table commandTable) Issues commands to bots based on a table configuration.
ConnectOutputs void ConnectOutputs(table) Expected to be used inside an entity's scope. Calling ConnectOutputs(this) inside entity script will search for functions named [some output]Output and connects respective output to them. Example: function named OnStartTouchOutput will have OnStartTouch output connected to it. (the output name needs to begin with On for this to work)
DoEntFire void DoEntFire(string target, string action, string value, float delay, handle activator, handle caller) Adds entity I/O event to the event queue to be processed at appropriate time based on specified delay. The caller and activator argument takes a CBaseEntity script handle, and entities assigned can receive inputs with target set to !self, or !activator / !caller.
EntFire void EntFire(string target, string action, string value = null, float delay = 0, handle activator = null) Wrapper for DoEntFire(). If called from an entity's script scope it sets caller to self.
Icon-Bug.pngBug*:Using 0 for value parameter mistakenly converts it to empty string. Use "0" instead to prevent that
DropFire void DropFire(Vector location) Drop a fire pool from the specified Vector location.
DropSpit void DropSpit(Vector location) Drop a spit pool from the specified Vector location.
EmitAmbientSoundOn void EmitAmbientSoundOn(string soundName, float volume, int soundlevel, int pitch, handle entity) Play named sound on an entity that has similar configurations to ambient_generic.
EmitSoundOnClient void EmitSoundOnClient(string soundScript, handle player) Play named sound only on the client for the specified player.
EmitSoundOn void EmitSoundOn(string soundScript, handle entity) Play named sound on an entity.
EntIndexToHScript CBaseEntity EntIndexToHScript(int entIndex) Returns the script handle for the given entity index.
FindRescueAreaTrigger CBaseTrigger FindRescueAreaTrigger() Returns the trigger entity for the rescue area.
GetListenServerHost handle GetListenServerHost() Get the host player on a listen server.
GetFriction float GetFriction(CTerrorPlayer player) Returns the Friction on a player entity, meaningless if not a player.
GetInvTable void GetInvTable(CTerrorPLayer player,table invTable) Fills invTable with the specified player's inventory.
GetPhysVelocity Vector GetPhysVelocity(handle entity) Returns the velocity of the entity.
GetPhysAngularVelocity Vector GetPhysAngularVelocity(handle entity) Returns the Angular velocity of the entity.
GetPlayerFromCharacter handle GetPlayerFromCharacter(int characterType) Given a character type, return the entity, or null.
GetPlayerFromUserID handle GetPlayerFromUserID(int ID) Given a user id, return the entity, or null.
IsPlayerABot bool IsPlayerABot(handle player) Is this player/entity a bot.
PickupObject void PickupObject(handle 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.
PlayerInstanceFromIndex CTerrorPlayer PlayerInstanceFromIndex(int index) Get a script handle of a player using the player index.
PrecacheEntityFromTable bool PrecacheEntityFromTable(table keyvalues) Precache an entity from KeyValues in a table.
RotateOrientation QAngle RotateOrientation(QAngle, QAngle) Rotate a QAngle by another QAngle.
RotatePosition Vector RotatePosition(Vector origin, QAngle rotation, Vector input) Rotate the input Vector around an origin.
SetFakeClientConVarValue void SetFakeClientConVarValue(handle bot, string cvar, string value) Sets a USERINFO client ConVar for a fakeclient.
SpawnEntityFromTable handle SpawnEntityFromTable(string classname, table keyvalues) Native function for entity spawning. See L4D2_EMS/Appendix:_Spawning.
SpawnEntityGroupFromTable bool SpawnEntityGroupFromTable(table entityGroup) Native function for entity group spawning. See L4D2_EMS/Appendix:_Spawning.
StopAmbientSoundOn void StopAmbientSoundOn(string soundName, handle entity) Stop named sound on an entity that has similar configurations to ambient_generic.
StopSoundOn void StopSoundOn(string soundScript, handle entity) Stop named sound on an entity.
ZSpawn bool ZSpawn(table spawnTable) Spawn an infected of liking, with a choice.

Response Rules

toc ↑ Script Scopes ↑

Theg_rrtable is used to create and/or override responses and their rules, allowing custom concepts to be dynamically made without altering existing talker files.

Todo: Test these functions and document them further.
Function Signature Description
rr_ProcessRules void rr_ProcessRules(handle rulesArray) Processes and adds the given rulesArray table to the talker system. This is an incomplete implementation of custom talker concepts for VScript, but it is mostly functional.
rr_PlaySoundFile unknown rr_PlaySoundFile(CTerrorPlayer speaker, unknown query, unknown soundfile, unknown context, unknown contextToWorld, unknown volume, unknown func)
rrDebugPrint void rrDebugPrint(string message) Print function that works similarly to printl() but prepends RR_TESTBED: to the start of the message.
rr_ProcessResponse unknown rr_ProcessResponse(unknown resp)
PrintTable void PrintTable(handle table) Print a table without searching through subtables to the console. Works with classes as well (not instances).
rr_ProcessCriterion unknown rr_ProcessCriterion(unknown crit)
rr_EmitSound unknown rr_EmitSound(CTerrorPlayer speaker, unknown query, unknown soundName, unknown context, unknown contextToWorld, unknown func)
rr_CharacterSpeak unknown rr_CharacterSpeak(CTerrorPlayer speaker, unknown query)
rr_ApplyContext unknown rr_ApplyContext(CTerrorPlayer speaker, unknown query, unknown contextData, unknown contextToWorld, unknown func)
rrPrintTable void rrPrintTable(handle table, prefix = "\t") Prints a table (non-recursive)

Other

toc ↑

Function Signature Description
AddToScriptHelp
Assert void Assert(bool value, string msg = null) Test value and if not true, throws an exception string "Assertion failed".

If msg parameter is set, then an exception string will be "Assertion failed: your message".

CheckForSpecialStage void CheckForSpecialStage(level, stage_list, stage_info) Helper for picking a random special stage based on stage_info table.
ClearGameEventCallbacks void ClearGameEventCallbacks() Empties the tables of game event callback functions.
ClearSavedTables void ClearSavedTables() Removes any tables saved with SaveTable().
developer int developer() The current level of the developer console variable.
Document void Document(unknown symbolOrTable, unknown itemIfSymbol = null, string descriptionIfSymbol = null)
DoIncludeScript bool DoIncludeScript(string file, handle/table scope) Execute a script. and put all its content for the argument passed to the scope parameter. (internal)
IncludeScript bool IncludeScript(string file, handle scope = null) Wrapper for DoIncludeScript.
DoUniqueString string DoUniqueString(string/null input) Generate a string guaranteed to be unique across the life of the script VM. This function requires a string or a null value as an input, otherwise throws an error.

You should use UniqueString function instead, as it is converting any input value to a string before calling this function, making generation process practically errorless.

Ent handle Ent(string/int idxorname) Wrapper function. If a string is provided, it'll find the entity by name using the string. But if an integer is provided, it'll be converted to a Script Handle before verifying the entity exists.
FileToString string FileToString(string path) Reads the file located in left4dead2/ems/path and returns its contents as a string. path supports folders and special names "." and "..", which indicate "current folder" and "parent folder" respectfully.

If file does not exist, a null value will be returned.

If file is longer than 16384 bytes, it will return a null value and print an error "File ems/path (from path) is len [actual file length here] too long for a ScriptFileRead".

Warning.pngWarning:if path contains folders, these folders will be created, if missing. Check carefully what you are reading, since there is no way to remove files/folders using VScript.
FireGameEvent string FireGameEvent(string event, table params) Fire a game event to a listening callback function in script. Parameters are passed in a squirrel table.
FireScriptEvent void FireScriptEvent(event, params) Wrapper for __RunEventCallbacks()
ForceScavengeStart void ForceScavengeStart() Starts the scavenge round, even if the setup timer hasn't elapsed.
ForceSurvivalStart void ForceSurvivalStart() Starts the survival round, even if the survivors haven't activated the radio.
ForceVersusStart void ForceVersusStart() Starts the versus round, even if the survivors haven't left the safe room.
GetCharacterDisplayName string GetCharacterDisplayName(CTerrorPlayer player) Return null if not a survivor, else the survivor's chosen character's name. This does not work with team 4 survivors.
GetCurrentFlowDistanceForPlayer float GetCurrentFlowDistanceForPlayer(CTerrorPlayer player) Returns the navigation flow distance from the start to the specified player.
GetCurrentFlowPercentForPlayer float GetCurrentFlowPercentForPlayer(CTerrorPlayer player) Returns how far in the navigation flow from the start to the end the player is.
GetFlowDistanceForPosition float GetFlowDistanceForPosition(Vector position) Returns the navigation flow distance from the start to the specified point.
GetFlowPercentForPosition float GetFlowPercentForPosition(Vector position, bool unknown) Returns how far in the navigation flow from the start to the end the position is.
GetMaxFlowDistance float GetMaxFlowDistance() Returns the navigation flow distance from the start to the end of the level.
GetAverageSurvivorFlowDistance float GetAverageSurvivorFlowDistance() Returns the navigation flow distance from the start to the survivors position averaged.
GetDifficulty int GetDifficulty() Returns the current difficulty as a numeric value. Easy = 0, Normal = 1, Advanced = 2, Expert = 3.
GetDifficultyString string GetDifficultyString() Returns the current difficulty as a string. Difficulty names are in z_difficulty cvar style: Easy, Normal, Hard, Impossible.
GetFrameCount void GetFrameCount() Returns the engine's current frame count.
GetFunctionSignature
GetInfectedStats void GetInfectedStats(table statTable) Fills statTable with some infected counts/etc... Right now the list is Witches, Tanks, Specials, Commons, though we may add more as requested going forward.
GetModelIndex int GetModelIndex(string filename) Returns index of model by name.
GetScavengeItemsGoal int GetScavengeItemsGoal() Returns number of Scavenge items needed.
GetScavengeItemsRemaining int GetScavengeItemsRemaining() Returns number of Scavenge items remaining.
GetSoundDuration float GetSoundDuration(string soundname, string actormodel) Returns float duration of the sound. Takes soundname and optional actormodelname.
HasConfigurableDifficultySetting bool HasConfigurableDifficultySetting() Returns true if the mode has more than a single difficulty.
HasPlayerControlledZombies bool HasPlayerControlledZombies() Returns true if the current mode supports player controlled zombies.
IsMissionFinalMap bool IsMissionFinalMap() True if the current map is the final map of the campaign. Independent of trigger_finale existence.
IsDedicatedServer bool IsDedicatedServer() Returns true if this is a dedicated server.
IsModelPrecached bool IsModelPrecached(string modelname) Checks if the modelname is precached.
IsSoundPrecached bool IsSoundPrecached(string soundname) Checks if the soundname is precached.
IsWeakref bool IsWeakref(table, key) Returns true/false based on whether table[key] is a weak reference
LocalTime void LocalTime(table) Fills out a table with the local time (second, minute, hour, day, month, year, dayofweek, dayofyear, daylightsavings).
MakeNamespace
PrecacheModel int PrecacheModel(string filename) Precache a model and return index of the model.
PrecacheSound void PrecacheSound(string soundName) Precache a sound.
QueueSpeak void QueueSpeak(handle entity, string concept, float delay, string criteria) Queue a speech concept.
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.
ReapplyInfectedFlags ReapplyInfectedFlags(int flags, handle infected) Apply Infected Flags from DirectorOptions. Applies to all common (spawned and unspawned) unless a handle to a specific infected is specified.
RegisterFunctionDocumentation void RegisterFunctionDocumentation(unknown func, string name, string signature, string description)
RegisterScriptGameEventListener void RegisterScriptGameEventListener(string eventName) Register as a listener for a game event from script. It's what __CollectGameEventCallbacks() uses to register event callbacks to the C++ code.
ReloadMOTD void ReloadMOTD() Reloads the MotD file.
RestoreTable void RestoreTable(string identifier, table) Restores table data and deletes it. See L4D2_EMS/Appendix:_Table_Save_Restore.
RetrieveNativeSignature unknown RetrieveNativeSignature(string nativeFunction)
rr_AddDecisionRule bool rr_AddDecisionRule(RRule rule) Add a rule to the decision database. Takes a RRule object from rulescript_base.nut.
rr_CommitAIResponse bool rr_CommitAIResponse(handle entity, table airesponse) Supposed to commit the result of QueryBestResponse back to the given entity to play. Takes a table needing the keys response with a ResponseSingle object (defined in response_testbed.nut) and orig_query with an unknown content.
rr_GetResponseTargets table rr_GetResponseTargets() Retrieve a table of all available expresser targets, in the form { name : handle, name: handle }.
rr_QueryBestResponse unknown rr_QueryBestResponse(handle entity, table query) Tests query against entity's response system and returns the best response found (or null if none found). Returns a pointer with a null type, that is apparently not usable anywhere. Possibly supposed to return a AI_Response object.
RushVictim void RushVictim(handle hVictim, float range) Make all common zombies in range rush the victim. (If hVictim isn't set, a random survivor will be chosen.)
SaveTable void SaveTable(string identifier, table) See L4D2_EMS/Appendix:_Table_Save_Restore.
ScreenFade void ScreenFade(handle player, int red, int green, int blue, int alpha, float fadeTime, float fadeHold, int flags) Start a screenfade with the following parameters.
ScreenShake void ScreenShake(Vector vecCenter, float flAmplitude, float flFrequency, float flDuration, float flRadius, int eCommand, bool bAirShake) Start a screenshake with the following parameters.
SetScavengeItemsGoal void SetScavengeItemsGoal(int count) Set the number of Scavenge items needed.
SetScavengeItemsRemaining void SetScavengeItemsRemaining(int count) Set the number of Scavenge items remaining.
StageInfo_Execute void StageInfo_Execute(stageInfo, stageDefaults) Execute a stage table, i.e. move parameters to DirectorOptions, do callbacks and so on.
StartAssault void StartAssault() Tells all existing nextbots to swap into assault mode and not hide/dither/loiter.
StringToFile void StringToFile(string path, string string) Stores the string into the file located at left4dead2/ems/path. Path can contain folders -- in that case folders will be automatically created. Also path supports special names "." and "..", which indicate "current folder" and "parent folder" respectfully.

Things to consider:

  • You can save much more than you can read with FileToString() -- you are limited only by script execution time. Check carefully what are you writing!
  • Due to a bug, string is saved with zero byte at the end. Such file is still read back properly by FileToString(), but that means you can save only 16383 bytes of useful information if you plan to read the file back.
  • There is no way to remove files using VScript.
Time float Time() Get the current server time.
TraceLine bool TraceLine(table traceTable) Uses a configuration table to do a raytrace, puts return information into the table for return usage.
UniqueString string UniqueString(string input="") Generate a string guaranteed to be unique across the life of the script VM, with an optional root string. Input will be converted to a string by calling tostring() member function of that input, before passing it to DoUniqueString function. Useful for adding data to tables when not sure what keys are already in use in that table. Throws error on null value.
VSquirrel_OnCreateScope table VSquirrel_OnCreateScope(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 createdScope) Removes a scope created via VSquirrel_OnCreateScope.
__CollectGameEventCallbacks void __CollectGameEventCallbacks(scope) Wrapper that registers callbacks for both OnGameEvent_x and OnScriptEvent_ functions. Done using the __CollectEventCallbacks function.
__CollectEventCallbacks void __CollectEventCallbacks(scope, prefix, globalTableName, regFunc) Overloaded function, used by the above one like this: __CollectEventCallbacks(scope, "OnGameEvent_", "GameEventCallbacks", ::RegisterScriptGameEventListener)
__ExecutePreSpawn
__FinishSpawn
__ReplaceClosures void __ReplaceClosures(script, scope)
__RunEventCallbacks void __RunEventCallbacks(event, params, prefix, globalTableName, bWarnIfMissing) Call all functions in the callback array for the given game event.
__RunGameEventCallbacks void __RunGameEventCallbacks(event, params Wrapper for __RunEventCallbacks()

Squirrel Standard Library

toc ↑

Squirrel List of functions that come from Squirrel's built-in functions and standard library. Not all functions from the linked documentations are present in VScript, such as the blob library.

Function Signature Description
array array(int size, any fill = null) Create and returns array of a specified size where each element is set to fill.
assert assert(bool exp) Throws an exception if exp is evaluated to false.
callee function callee() Returns the currently running closure.
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 function compilestring(string string, string buffername = null) Compiles a string containing a squirrel script into a function and returns it.
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 stacklevel) 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"
	}
}
newthread coroutine newthread(function threadfunc) Creates a new cooperative thread object(coroutine) and returns it
print void print(string message) Prints message to console without any line feed after.
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 consttable) Sets the const table of the VM which also returns the previous const table.
seterrorhandler void seterrorhandler(function func) Sets the runtime error handler .
setroottable table setroottable(table roottable) Sets the root table of the VM which also returns the previous root table.
suspend void suspend(any ret) Suspends the coroutine that called this function.
type string type(any obj) Return the 'raw' type of an object without invoking the metatmethod '_typeof'.

Math

The built-in Squirrel math library.

Function Signature Description
abs int abs(float x) Returns the absolute value of x as an integer.
acos float acos(float x) Returns the arccosine of x.
asin float asin(float x) Returns the arcsine of x.
atan float atan(float x) Returns the arctangent of x.
atan2 float atan2(float x, float y) Returns the arctangent of x/y.
ceil float ceil(float x) Returns a float value representing the smallest integer that is greater than or equal to x.
cos float cos(float x) Returns the cosine of x.
exp float exp(float x) Returns the exponential value (e^x) of the float parameter x.
fabs float fabs(float x) Returns the absolute value of x as a float.
floor float floor(float x) Returns a float value representing the largest integer that is less than or equal to x.
log float log(float x) Returns the natural logarithm of x.
log10 float log10(float x) Returns the logarithm base-10 of x.
pow float pow(float x, float y) Returns x raised to the power of y.
rand int rand() Returns a pseudorandom integer in the range 0 to RAND_MAX.
sin float sin(float x) Returns the sine of x.
sqrt float sqrt(float x) Returns the square root of x.
srand void srand(float seed) Sets the starting point for generating a series of pseudorandom integers.
tan float tan(float x) Returns the tangent of x.

Strings

The built-in Squirrel string library.

Function Signature Description
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 characters at the beginning of the given string.
rstrip string rstrip(string str) Removes whitespace characters at the end of the given string.
split array split(string str, string separator) 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.
strip string strip(string str) Removes whitespace characters at both the beginning and end of the given string.

Script Debug

toc ↑ 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

toc ↑