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

From Valve Developer Community
Jump to navigation Jump to search
(→‎Variables: Added EntityOutputs class)
m (→‎Methods: __KeyValueFromFloat warning should be enough)
 
(184 intermediate revisions by 25 users not shown)
Line 1: Line 1:
{{otherlang2
{{LanguageBar}}
|zh-cn=L4D2脚本函数清单
{{toc-right}}
}}
 
{{toc-right}}{{sq}} This list contains engine-related Squirrel variables, functions, and constants available for {{l4d2}} [[L4D2_Vscripts| Left 4 Dead 2 VScripts]].  
{{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>scipt_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]].
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
|-
|-
|<code>Convars</code>
| <kbd>Convars</kbd> || <kbd>{{↓|Convars}}</kbd>
|<code>[[#Convars|Convars]]</code>
| Provides an interface to read and change the values of console variables.
|Provides an interface to read and change the values of console variables.
|-
|-
|<code>Director</code>
| <kbd>Director</kbd> || <kbd>{{↓|CDirector}}</kbd>
|<code>[[#CDirector|CDirector]]</code>
| Provides a limited interface to the Director.
|Provides a limited interface to the Director.
|-
|-
|<code>DirectorScript</code>
| <kbd>Entities</kbd> || <kbd>{{↓|CEntities}}</kbd>
|table
| Allows searching of currently-spawned entities.
| Script scope for [[L4D2_Director_Scripts|Director scripts]]. Contains the active [[L4D2_Director_Scripts#DirectorOptions|DirectorOptions]] table.
|-
|-
|<code>Documentation</code>
| <kbd>EntityOutputs</kbd> || <kbd>{{↓|CScriptEntityOutputs}}</kbd>
|table
| Allows reading and changing of entities' output data.
| Contains the printed strings from the <code>script_help</code> command.
|-
|-
|<code>Entities</code>
| <kbd>NavMesh</kbd> || <kbd>{{↓|CNavMesh}}</kbd>
|<code>[[#CEntities|CEntities]]</code>
| An interface to the Navigation Mesh.
|Provides access to currently spawned entities.
|-
|-
|<code>EntityOutputs</code>
| <kbd>NetProps</kbd> || <kbd>{{↓|CNetPropManager}}</kbd>
|<code>[[#CScriptEntityOutputs|CScriptEntityOutputs]]</code>
| Allows reading and updating the network properties of an entity.
|Allows manipulation of entity output data.
|-
|-
|<code>g_ClearoutTable</code>
| <kbd>ResponseCriteria</kbd> || <kbd>{{↓|CScriptResponseCriteria}}</kbd>
|table (<code>null</code>)
| Allows reading the response criteria of an entity.
|  
|}
 
== Script Scopes ==
{| class="standard-table"
! Name !! Type !! Description
|-
|-
|<code>g_MapScript</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 map specific vscripts. It also contains a lot of utility functions.
|-
|-
|<code>g_ModeScript</code>
| <kbd>g_ClearoutTable</kbd> || table (<kbd>null</kbd>)
|table
| NONE
| Script scope for mode specific vscripts. Only fully available in Scripted Mode.
|-
|-
|<code>g_RoundState</code>
| <kbd>g_MapScript</kbd> || table
|table
| Script scope of map-specific vscripts, which also contains utilty functions.
|  
|-
|-
|<code>g_rr</code>
| <kbd>g_ModeScript</kbd> || table
|table
| Script scope of mode-specific vscripts like mutations. This scope also has the {{Code|g_MapScript}} scope as its environment.
|  
|-
|-
|<code>NavMesh</code>
| <kbd>g_RoundState</kbd> || table
|<code>[[#CNavMesh|CNavMesh]]</code>
| Scope of the start box used in the Holdout or Dash mutation.
|Provides a method to unblock the rescue vehicle.
|-
|-
|<code>NetProps</code>
| <kbd>[[#Response Rules|g_rr ↓]]</kbd> || table
|<code>[[#CNetPropManager|CNetPropManager]]</code>
| An interface to the Response System.
|Allows reading and updating the network properties of an entity.
|}
 
== Variables ==
{| class="standard-table"
! Name !! Type !! Description
|-
|-
|<code>print_indent</code>
| <kbd>Documentation</kbd> || table
|integer
| Contains the printed strings from the <kbd>script_help</kbd> command.
|  
|-
|-
|<code>_PublishedHelp</code>
| <kbd>GameEventCallbacks</kbd> || table
|table
| Table of registered game event callbacks.
|  
|-
|-
|<code>ResponseCriteria</code>
| <kbd>print_indent</kbd> || integer
|<code>[[#CScriptResponseCriteria|CScriptResponseCriteria]]</code>
| Spaces to indent prints by except ones from {{Code|realPrint}}. Defaults to 0.
|Allows reading the response criteria of an entity.
|-
|-
|<code>ScriptDebugTraceAllOn</code>
| <kbd>_PublishedHelp</kbd> || table
|bool
| NONE
|  
|-
|-
|<code>ScriptDebugTraces</code>
| <kbd>ScriptEventCallbacks</kbd> || table
|table
| Table of registered script event callbacks.
|  
|-
|-
|<code>ScriptDebugText</code>
|}
|array
 
|
=== Script Debug ===
{| class = "standard-table"
! Name !! Type !! Value
|-
|-
|<code>ScriptDebugTextFilters</code>
| <kbd>ScriptDebugDefaultWatchColor</kbd> || array
|table
| [0, 192, 0]
|  
|-
|-
|<code>ScriptDebugTextIndent</code>
| <kbd>ScriptDebugDrawTextEnabled</kbd> || bool
|integer
| true
|  
|-
|-
|<code>ScriptDebugWatches</code>
| <kbd>ScriptDebugDrawWatchesEnabled</kbd> || bool
|array
| true
|  
|-
|-
|<code>ScriptEventCallbacks</code>
| <kbd>ScriptDebugInDebugDraw</kbd> || bool
|table
| false
|  
|-
|-
| <kbd>ScriptDebugText</kbd> || array
| NONE
|-
| <kbd>ScriptDebugTextIndent</kbd> || integer
| 0
|-
| <kbd>ScriptDebugTextFilters</kbd> || table
| NONE
|-
| <kbd>ScriptDebugTraces</kbd> || table
| NONE
|-
| <kbd>ScriptDebugTraceAllOn</kbd> || bool
| 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
!Description
|-
|-
|<code>_charsize_</code>
| <kbd>_charsize_</kbd> || integer
|integer
| 1
|  
|-
|-
|<code>_floatsize_</code>
| <kbd>_floatsize_</kbd> || integer
|integer
| 4
|  
|-
|-
|<code>_intsize_</code>
| <kbd>_intsize_</kbd> || integer
|integer
| 4
|  
|-
|-
|<code>_version_</code>
| <kbd>_version_</kbd> || string
|string
| "Squirrel 3.0.4 stable"
| The version of squirrel.
|-
|-
|<code>_versionnumber_</code>
| <kbd>_versionnumber_</kbd> || integer
|integer
| 304
| The version of squirrel as an integer.
|-
|-
|<code>RAND_MAX</code>
| <kbd>RAND_MAX</kbd> || integer
|integer
| 32767
|  
|-
|-
|<code>SPAWN_FLAGS</code>
| <kbd>SPAWN_FLAGS</kbd> || table
|table
|<syntaxhighlight lang=js>
|  
SPAWN = 1
NOSPAWN = 2
TARGETSPAWN = 4</syntaxhighlight>
|-
|-
| <kbd>PI</kbd> || float
| 3.14159
|}
|}


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


== 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.)}}


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:
* <kbd>[[#CEntities|Entities ↓]]</kbd> instance.
* [[Entity Scripts]] only - The <kbd>self</kbd> keyword.


==== Methods ====
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <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>
| 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|Use [[#CNetPropManager|Netprops ↓]] and update the keyvalue's corresponding prop instead, as this correctly updates the networking state and results in an immediate update.}}
 
{{warning|__KeyValueFromFloat doesn't exist}}
 
|-
 
| <kbd>ApplyAbsVelocityImpulse</kbd> || <kbd>void ApplyAbsVelocityImpulse(Vector ''impulse'')</kbd>
 
| Apply a Velocity Impulse as a world space impulse vector.
 
|-
 
| <kbd>ApplyLocalAngularVelocityImpulse</kbd> || <kbd>void ApplyLocalAngularVelocityImpulse(Vector ''impulse'')</kbd>
 
| 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.
 
|-
 
| <kbd>ConnectOutput</kbd> || <kbd>void ConnectOutput(string ''output'', string ''function'')</kbd>
 
| Adds an I/O connection that will call the named function when the specified output fires.
 
|-
 
| <kbd>DisconnectOutput</kbd> || <kbd>void DisconnectOutput(string ''output'', string ''function'')</kbd>
 
| Removes a connected script function from an I/O event.
 
|-
 
| <kbd>FirstMoveChild</kbd> || <kbd>handle FirstMoveChild()</kbd>
 
| Returns the first entity parented to this one. Needs to be used in combination with NextMovePeer to iterate over all children.
 
{{tip|Example usage: <source lang=js>for (local child = entity.FirstMoveChild(); child != null; child = child.NextMovePeer())</source>}}
 
|-
 
| <kbd>GetAngles</kbd> || <kbd>QAngle GetAngles()</kbd>
 
| Returns the orientation of the entity in the world.
 
|-
 
| <kbd>GetBaseVelocity</kbd> || <kbd>Vector GetBaseVelocity()</kbd>
 
| 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! -->
== Classes ==
|-
 
| <kbd>GetCenter</kbd> || <kbd>Vector GetCenter()</kbd>
=== CBaseEntity ===
| Get world space center of object - absolute coords.
This is a script handle class for entities. All entities spawned have a script handle using this or one of its subclasses.  
|-
 
| <kbd>GetClassname</kbd> || <kbd>string GetClassname()</kbd>
All script handles in-game are accessible from [[#CEntities|Entities]]. Entity Scripts can use <code>self</code> to access their own script handle.
| Returns the entity class. This includes<kbd>player</kbd>and<kbd>infected</kbd>.
 
|-
==== Methods ====
| <kbd>GetContext</kbd> || <kbd>''variable'' GetContext(string ''name'')</kbd>
{| class="standard-table" style="width: 100%;"
| 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 -->
! Function
|-
! Signature
| <kbd>GetEntityHandle</kbd> || <kbd>''unknown'' GetEntityHandle()</kbd>
! Description
| 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. ↓]]
|-
| <kbd>GetEntityIndex</kbd> || <kbd>int GetEntityIndex()</kbd>
| Returns the entity index. This is the same type of index used in most game events.
|-
|-
| <code>__KeyValueFromInt</code>
| <kbd>GetForwardVector</kbd> || <kbd>Vector GetForwardVector()</kbd>
| <code>bool __KeyValueFromInt(string ''key'', int ''value'')</code>
| Get the forward vector of the entity.
| 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.
|-
|-
| <code>__KeyValueFromFloat</code>
| <kbd>GetHealth</kbd> || <kbd>int GetHealth()</kbd>
| <code>bool __KeyValueFromFloat(string ''key'', float ''value'')</code>
| Returns the current health of the entity (does not include survivor temporary health).
| 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>
| <kbd>GetLocalAngles</kbd> || <kbd>QAngle GetLocalAngles()</kbd>
| <code>bool __KeyValueFromString(string ''key'', string ''value'')</code>
| Returns the orientation of the entity relative to it's parent or attachment point.
| 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>
| <kbd>GetLocalAngularVelocity</kbd> || <kbd>QAngle GetLocalAngularVelocity()</kbd>
| <code>bool __KeyValueFromVector(string ''key'', Vector ''value'')</code>
| Maybe local angvel
| 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>GetLocalOrigin</kbd> || <kbd>Vector GetLocalOrigin()</kbd>
| <code>void ApplyAbsVelocityImpulse(Vector ''impulse'')</code>
| Returns the origin of the entity relative to it's parent or attachment point.
| Apply a Velocity Impulse as a world space impulse vector.
|-
|-
| <code>ApplyLocalAngularVelocityImpulse</code>
| <kbd>GetLocalVelocity</kbd> || <kbd>Vector GetLocalVelocity()</kbd>
| <code>void ApplyLocalAngularVelocityImpulse(Vector ''impulse'')</code>
| Get Entity relative velocity
| 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>GetMaxHealth</kbd> || <kbd>int GetMaxHealth()</kbd>
| <code>void ConnectOutput(string ''output'', string ''function'')</code>
| Returns the maximum health of the entity.
| Adds an I/O connection that will call the named function when the specified output fires.
|-
|-
| <code>DisconnectOutput</code>
| <kbd>GetModelName</kbd> || <kbd>string GetModelName()</kbd>
| <code>void DisconnectOutput(string ''output'', string ''function'')</code>
| Returns the file name of the model used by the entity (if applicable).
| Removes a connected script function from an I/O event.
|-
|-
| <code>FirstMoveChild</code>
| <kbd>GetMoveParent</kbd> || <kbd>handle GetMoveParent()</kbd>
| <code>handle FirstMoveChild()</code>
| Returns the first entity parented to this one.
|-
| <code>GetAngles</code>
| <code>QAngle GetAngles()</code>
| Returns the orientation of the entity in the world.
|-
| <code>GetBaseVelocity</code>
| <code>Vector GetBaseVelocity()</code>
| Get Base? velocity {{todo}}
|-
| <code>GetClassname</code>
| <code>string GetClassname()</code>
| Returns the entity class. This includes <code>player</code> and <code>infected</code>.
|-
| <code>GetContext</code>
| <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).
|-
| <code>GetEntityHandle</code>
| <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.
|-
| <code>GetEntityIndex</code>
| <code>int GetEntityIndex()</code>
| Returns the entity index. This is the same type of index used in most game events.
|-
| <code>GetForwardVector</code>
| <code>Vector GetForwardVector()</code>
| Get the forward vector of the entity.
|-
| <code>GetHealth</code>
| <code>int GetHealth()</code>
| Returns the current health of the entity (does not include survivor temporary health).
|-
| <code>GetLocalAngles</code>
| <code>QAngle GetLocalAngles()</code>
| Returns the orientation of the entity relative to it's parent or attachment point.
|-
| <code>GetLocalAngularVelocity</code>
| <code>QAngle GetLocalAngularVelocity()</code>
| Maybe local angvel
|-
| <code>GetLocalOrigin</code>
| <code>Vector GetLocalOrigin()</code>
| Returns the origin of the entity relative to it's parent or attachment point.
|-
| <code>GetLocalVelocity</code>
| <code>Vector GetLocalVelocity()</code>
| Get Entity relative velocity
|-
| <code>GetMaxHealth</code>
| <code>int GetMaxHealth()</code>
| Returns the maximum health of the entity.
|-
| <code>GetModelName</code>
| <code>string GetModelName()</code>
| Returns the file name of the model used by the entity (if applicable).
|-
| <code>GetMoveParent</code>
| <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")}}}}
| Retrieve the unique identifier used to refer to the entity within the scripting system.
|-
|-
| <code>GetScriptScope</code>
| <kbd>GetScriptScope</kbd> || <kbd>table GetScriptScope()</kbd>
| <code>handle 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 belongs to a valid entity.
|-
|-
| <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').
|-
|-
| <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>ValidateScriptScope</code>
| <kbd>TakeDamageEx</kbd> || <kbd>void TakeDamageEx(CBaseEntity ''inflictor'', CBaseEntity ''attacker'', CBaseEntity ''weapon'', Vector ''vecDamageForce'', Vector ''vecDamagePosition'', float ''damage'', int ''damageType'')</kbd>
| <code>bool ValidateScriptScope()</code>
| Damages the entity (extended).
| Ensure that an entity's script scope has been created.
|-
| <kbd>ValidateScriptScope</kbd> || <kbd>bool ValidateScriptScope()</kbd>
| Ensures an entity has a script scope, if it doesn't have one then one is created. Returns true if created successfully.
|}
|}


Line 407: 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. The name of the function needs to be <code>Input</code> followed by the name of the input in CamelCase, for example <code>InputFireUser1</code> for the FireUser1 input. When the function is called, the activating and calling entities Script Handles are written to the receiving entitys Script Scope in the <code>activator</code> and <code>caller</code> variables. The function needs to return a boolean value. Setting it to <code>true</code> allows the entity to process 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 immediately after the entity spawns. 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 435: 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 547: 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.
|}
 
=== CBaseCombatCharacter ===
{{↑|toc}}
Extends {{↑|CBaseFlex}}
 
Combat character. Common and uncommon infected and witches belong to this.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function !! Signature !! Description
|-
| <kbd>GetLastKnownArea</kbd> || <kbd>TerrorNavArea GetLastKnownArea()</kbd>
| Return the last nav area occupied - NULL if unknown.
|}
|}


=== CTerrorPlayer ===
=== CTerrorPlayer ===
Extends [[#CBaseFlex|CBaseFlex]]
{{↑|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 572: 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 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>GetButtonMask</code>
| <kbd>GetAliveDuration</kbd> || <kbd>float GetAliveDuration()</kbd>
| <code>int GetButtonMask()</code>
| Returns the time the character has been alive (only valid when alive).
| 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>GetButtonMask</kbd> || <kbd>int GetButtonMask()</kbd>
| <code>int GetHealthBuffer()</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 the current temporary health of a survivor. {{TODO|Does temp health work on SI?}}
|-
|-
| <code>GetNetworkIDString</code>
| <kbd>GetHealthBuffer</kbd> || <kbd>float GetHealthBuffer()</kbd>
| <code>string GetNetworkIDString()</code>
| Returns the current temporary health of a survivor.
|-
| <kbd>GetNetworkIDString</kbd> || <kbd>string GetNetworkIDString()</kbd>
| 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>
|-
| <kbd>GetSpecialInfectedDominatingMe</kbd> || <kbd>CTerrorPlayer GetSpecialInfectedDominatingMe()</kbd>
| 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>
|-
| <kbd>HasEverBeenInjured</kbd> || <kbd>bool HasEverBeenInjured(int ''team'')</kbd>
| Returns true if the character has ever been injured by a member of the given team.
|-
| <kbd>HitWithVomit</kbd> || <kbd>void HitWithVomit()</kbd>
| Cover the player with a boomer vomit attack.
|-
| <kbd>IsAdrenalineActive</kbd> || <kbd>bool IsAdrenalineActive()</kbd>
| Return true if adrenaline is active.
|-
|-
| <code>HitWithVomit</code>
| <kbd>IsDead</kbd> || <kbd>bool IsDead()</kbd>
| <code>void HitWithVomit()</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.
| Target a player with a boomer vomit attack.  
|-
|-
| <code>IsDead</code>
| <kbd>IsDominatedBySpecialInfected</kbd> || <kbd>bool IsDominatedBySpecialInfected()</kbd>
| <code>bool IsDead()</code>
| Return true if being dominated by a Special Infected (i.e. held by smoker, charger, jockey or hunter)
| Returns a bool indicating dead state.
|-
|-
| <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 a bool indicating dying state.
|-
|-
| <code>IsIncapacitated</code>
| <kbd>IsFiringWeapon</kbd> || <kbd>bool IsFiringWeapon()</kbd>
| <code>bool IsIncapacitated()</code>
| Return true if player is firing a weapon.
| Returns a bool indicating incapacitated state.
|-
|-
| <code>IsHangingFromLedge</code>
| <kbd>IsIncapacitated</kbd> || <kbd>bool IsIncapacitated()</kbd>
| <code>bool IsHangingFromLedge()</code>
| Returns true if in incapacitated state.
| Returns a bool indicating ledge hang state.
|-
|-
| <code>IsGhost</code>
| <kbd>IsHangingFromLedge</kbd> || <kbd>bool IsHangingFromLedge()</kbd>
| <code>bool IsGhost()</code>
| Returns true if in ledge hang state.
| Returns a bool indicating ghost infected state.
|-
|-
| <code>IsOnFire</code>
| <kbd>IsGettingUp</kbd> || <kbd>bool IsGettingUp()</kbd>
| <code>bool IsOnFire()</code>
| Return true if player is currently getting up.
| Returns a bool indicating if a player is on fire.
|-
|-
| <code>IsSuppressingFallingDamage</code>
| <kbd>IsGhost</kbd> || <kbd>bool IsGhost()</kbd>
| <code>bool IsSuppressingFallingDamage()</code>
| Returns true if in ghost infected state.
| Returns a bool indicating if falling damage is currently suppressed.
|-
|-
| <code>IsSurvivor</code>
| <kbd>IsImmobilized</kbd> || <kbd>bool IsImmobilized()</kbd>
| <code>bool IsSurvivor()</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)}}
| On the survivor team (Otherwise, infected).
|-
|-
| <code>RemoveUpgrade</code>
| <kbd>IsInCombat</kbd> || <kbd>bool IsInCombat()</kbd>
| <code>void RemoveUpgrade(int ''upgradeType'')</code>
| Return true if currently in combat.
| Remove a primary weapon upgrade: <code>UPGRADE_INCENDIARY_AMMO, UPGRADE_EXPLOSIVE_AMMO, UPGRADE_LASER_SIGHT</code>
|-
|-
| <code>ReviveByDefib</code>
| <kbd>IsIT</kbd> || <kbd>bool IsIT()</kbd>
| <code>void ReviveByDefib()</code>
| Return true if currently IT from bile.
|-
| <kbd>IsOnFire</kbd> || <kbd>bool IsOnFire()</kbd>
| Returns true if a player is on fire, e.g. Standing in fireworks crate explosions.
|-
| <kbd>IsOnThirdStrike</kbd> || <kbd>bool IsOnThirdStrike()</kbd>
| Return true if on third-strike.
|-
| <kbd>IsStaggering</kbd> || <kbd>bool IsStaggering()</kbd>
| Return true if player is staggering.
|-
| <kbd>IsSuppressingFallingDamage</kbd> || <kbd>bool IsSuppressingFallingDamage()</kbd>
| 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.
|-
| <kbd>IsSurvivor</kbd> || <kbd>bool IsSurvivor()</kbd>
| Returns true if entity is on the survivor or l4d1 survivor team (Otherwise, unknown, spectator or infected).
|-
| <kbd>RemoveUpgrade</kbd> || <kbd>void RemoveUpgrade(int ''upgradeType'')</kbd>
| 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>
|-
| <kbd>ReviveByDefib</kbd> || <kbd>void ReviveByDefib()</kbd>
| 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. 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]]
{{↑|toc}}
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.
| Get the current amount of ammo in weapon's primary 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.
| Get the current amount of ammo in weapon's secondary clip.
|-
|-
| <code>GetDefaultClip1</code>
| <kbd>GetDefaultClip1</kbd> || <kbd>int GetDefaultClip1()</kbd>
| <code>int GetDefaultClip1()</code>
| Clip count of a weapon when its newly picked up.
| Get the default amount of ammo placed in the primary clip when a new weapon is picked up.
|-
|-
| <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.
| Get the default amount of ammo placed in the secondary clip when a new weapon is picked up.
|-
|-
| <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.
| Get the max amount of ammo the primary clip for weapon can hold.
|-
|-
| <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.
| Get the max amount of ammo the secondary clip for weapon can hold.
|-
|-
| <code>GiveDefaultAmmo</code>
| <kbd>GiveDefaultAmmo</kbd> || <kbd>void GiveDefaultAmmo()</kbd>
| <code>void GiveDefaultAmmo()</code>
| Revert both weapons's clip to their default values.
| Sets the current ammo count in the clips 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 the weapon had to be reloaded.
|-
|-
| <code>SetClip1</code>
| <kbd>SetClip1</kbd> || <kbd>void SetClip1(int ''amount'')</kbd>
| <code>void SetClip1(int ''amount'')</code>
| Sets a weapon's clip count.
| Set the current amount of ammo in weapon's primary clip.
|-
|-
| <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.
| Set the current amount of ammo in weapon's primary clip.
|}
|}


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


Entity class for triggers.
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
|-
|-
| <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
|-
|-
| <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>
| <code>{{todo}} constructor()</code>
|
|-
| <code>PostScriptExecute</code>
| <code>{{todo}} PostScriptExecute()</code>
|
|-
| <code>Call</code>
| <code>{{todo}} Call()</code>
|
|}
 
==== Members ====
{| class="standard-table" style="width: 100%;"
! Instance
! Type
! Description
|-
|-
| <code>chains</code>
| <kbd>AreAllSurvivorsInBattlefield</kbd> || <kbd>bool AreAllSurvivorsInBattlefield()</kbd>
| <code>null</code>
| Returns true if all Survivors are in the battlefield.
|  
|-
|-
| <code>prefix</code>
| <kbd>AreAllSurvivorsInFinaleArea</kbd> || <kbd>bool AreAllSurvivorsInFinaleArea()</kbd>
| <code>null</code>
| True when all survivors are within the finale area.
|  
|-
|-
| <code>scope</code>
| <kbd>AreTeamsFlipped</kbd> || <kbd>bool AreTeamsFlipped()</kbd>
| <code>null</code>
| True when teams are flipped in Versus modes.
|  
|}
 
 
=== 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>ClearCachedBotQueries</code>
| <kbd>ClearCachedBotQueries</kbd> || <kbd>void ClearCachedBotQueries()</kbd>
| <code>void ClearCachedBotQueries()</code>
| Mark all cached bot query results as invalid.
| Mark all cached bot query results as invalid.
|-
|-
| <code>ForceNextStage</code>
| <kbd>ForceNextStage</kbd> || <kbd>void ForceNextStage()</kbd>
| <code>void ForceNextStage()</code>
| Push the ScriptedMode to next stage - i.e. request GNSS be called.
| Push the ScriptedMode to next stage - i.e. request GNSS be called.
|-
|-
| <code>GetAveragedSurvivorSpan</code>
| <kbd>GetAveragedSurvivorSpan</kbd> || <kbd>float GetAveragedSurvivorSpan()</kbd>
| <code>float GetAveragedSurvivorSpan()</code>
| Get the distance between the lead and trailing survivors, smoothed over time.
| Get the distance between the lead and trailing survivors, smoothed over time.
|-
|-
| <code>GetAveragedSurvivorSpeed</code>
| <kbd>GetAveragedSurvivorSpeed</kbd> || <kbd>float GetAveragedSurvivorSpeed()</kbd>
| <code>float GetAveragedSurvivorSpeed()</code>
| Get the rate at which the lead survivor is moving along the flow, smoothed over time.
| Get the rate at which the lead survivor is moving along the flow, smoothed over time.
|-
|-
| <code>GetCommonInfectedCount</code>
| <kbd>GetClosestActivePipeBomb</kbd> || <kbd>CBaseEntity GetClosestActivePipeBomb(Vector ''origin'')</kbd>
| <code>int GetCommonInfectedCount()</code>
| Returns the closest active pipe bomb from this origin.
| Returns number for infected currently spawned.
|-
|-
| <code>GetFurthestSurvivorFlow</code>
| <kbd>GetClosestCharacterWhoIsIT</kbd> || <kbd>CBaseCombatCharacter GetClosestCharacterWhoIsIT(CBaseCombatCharacter ''character'')</kbd>
| <code>float GetFurthestSurvivorFlow()</code>
| Returns the closest character who is IT to the passed character.
| Get the maximum distance along the flow that the survivors have reached.
|-
|-
| <code>GetGameMode</code>
| <kbd>GetClosestSurvivor</kbd> || <kbd>CTerrorPlayer GetClosestSurvivor(Vector ''origin'', bool bIncludeIncap, bool bIncludeOnRescueVehicle)</kbd>
| <code>string GetGameMode()</code>
| Returns the closest Survivor from the passed origin, if incapped Survivors are included in search, or on rescue vehicle.
| Get the current game mode. If called in a mutation, it returns the current mutation, not the base mode.
|-
|-
| <code>GetGameModeBase</code>
| <kbd>GetCommonInfectedCount</kbd> || <kbd>int GetCommonInfectedCount()</kbd>
| <code>string GetGameModeBase()</code>
| Returns number for infected currently spawned.
| Get the current base game mode. Does not return the current mutation.
|-
| <kbd>GetFurthestSurvivorFlow</kbd> || <kbd>float GetFurthestSurvivorFlow()</kbd>
| Get the maximum distance along the flow that the survivors have reached.
|-
|-
| <code>GetHoldoutCooldownEndTime</code>
| <kbd>GetGameMode</kbd> || <kbd>string GetGameMode()</kbd>
| <code>{{todo}} float? GetHoldoutCooldownEndTime()</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.
|-
| <kbd>GetGameModeBase</kbd> || <kbd>string GetGameModeBase()</kbd>
| 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)
|-
| <kbd>GetHighestFlowSurvivor</kbd> || <kbd>CTerrorPlayer GetHighestFlowSurvivor()</kbd>
| 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>GetPendingMobCount</code>
| <kbd>GetMapNumber</kbd> || <kbd>int GetMapNumber()</kbd>
| <code>int GetPendingMobCount()</code>
| Return the current map number.
|-
| <kbd>GetMissionWipes</kbd> || <kbd>int GetMissionWipes()</kbd>
| Returns the current number of mission wipes.
|-
| <kbd>GetPendingMobCount</kbd> || <kbd>int GetPendingMobCount()</kbd>
| 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}}
|-
| <kbd>GetTimeSinceSpecialZombieKilled</kbd> || <kbd>float GetTimeSinceSpecialZombieKilled(int ''zombieType'')</kbd>
| Returns the time since the passed zombie type was killed.
|-
|-
| <code>HasAnySurvivorLeftSafeArea</code>
| <kbd>GetTotalElapsedMissionTime</kbd> || <kbd>float GetTotalElapsedMissionTime()</kbd>
| <code>bool HasAnySurvivorLeftSafeArea()</code>
| Returns the total elapsed mission time.
|-
| <kbd>HasAnySurvivorLeftSafeArea</kbd> || <kbd>bool HasAnySurvivorLeftSafeArea()</kbd>
| 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>IsAnySurvivorInCombat</code>
| <kbd>IsAnySurvivorBypassingTank</kbd> || <kbd>bool IsAnySurvivorBypassingTank()</kbd>
| <code>bool IsAnySurvivorInCombat()</code>
| True when one or more survivors are bypassing the Tank.
|-
| <kbd>IsAnySurvivorInCombat</kbd> || <kbd>bool IsAnySurvivorInCombat()</kbd>
| Returns true if any survivor recently dealt or took damage.
| Returns true if any survivor recently dealt or took damage.
|-
|-
| <code>IsPlayingOnConsole</code>
| <kbd>IsAnySurvivorInExitCheckpoint</kbd> || <kbd>bool IsAnySurvivorInExitCheckpoint()</kbd>
| <code>bool IsPlayingOnConsole()</code>
| True when one or more survivors are in the exit checkpoint.
|-
| <kbd>IsAnySurvivorInStartArea</kbd> || <kbd>bool IsAnySurvivorInStartArea()</kbd>
| True when one or more survivors are in the starting safe area.
|-
| <kbd>IsFinale</kbd> || <kbd>bool IsFinale()</kbd>
| True when the finale has started.
|-
| <kbd>IsFinaleEscapeInProgress</kbd> || <kbd>bool IsFinaleEscapeInProgress()</kbd>
| True when the finale escape is in progress.
|-
| <kbd>IsFinaleVehicleReady</kbd> || <kbd>bool IsFinaleVehicleReady()</kbd>
| True when the finale vehicle is ready.
|-
| <kbd>IsFinaleWon</kbd> || <kbd>bool IsFinaleWon()</kbd>
| Returns true if the finale has been won.
|-
| <kbd>IsFirstMapInScenario</kbd> || <kbd>bool IsFirstMapInScenario()</kbd>
| True if the first map in a scenario.
|-
| <kbd>IsL4D1Campaign</kbd> || <kbd>bool IsL4D1Campaign()</kbd>
| Return true if the current campaign is originally from L4D1.
|-
| <kbd>IsLocationFoggedToSurvivors</kbd> || <kbd>bool IsLocationFoggedToSurvivors(Vector ''origin'')</kbd>
| Returns true if the passed location is fogged to Survivors.
|-
| <kbd>IsPlayingIntro</kbd> || <kbd>bool IsPlayingIntro()</kbd>
| True if the intro is currently playing.
|-
| <kbd>IsPlayingOnConsole</kbd> || <kbd>bool IsPlayingOnConsole()</kbd>
| 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>IsSinglePlayerGame</code>
| <kbd>IsSessionStartMap</kbd> || <kbd>bool IsSessionStartMap()</kbd>
| <code>bool IsSinglePlayerGame()</code>
| True if the map is the start of the session.
|-
| <kbd>IsSinglePlayerGame</kbd> || <kbd>bool IsSinglePlayerGame()</kbd>
| 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 the handle belongs to a valid entity.
|-
|-
| <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>ResetMobTimer</code>
| <kbd>RegisterForbiddenTarget</kbd> || <kbd>void RegisterForbiddenTarget(CBaseEntity ''entity'')</kbd>
| <code>void ResetMobTimer()</code>
| Registers a target entity as forbidden.
| Trigger a mob as soon as possible when in <code>BUILD_UP</code>.
|-
|-
| <code>ResetSpecialTimers</code>
| <kbd>ResetMobTimer</kbd> || <kbd>void ResetMobTimer()</kbd>
| <code>void ResetSpecialTimers()</code>
| Trigger a mob as soon as possible when in {{Code|BUILD_UP}}.
|-
| <kbd>ResetSpecialTimers</kbd> || <kbd>void ResetSpecialTimers()</kbd>
| 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''? {{todo}})</code>
|  
|  
|-
|-
| <code>UserDefinedEvent1</code>
| <kbd>UnregisterForbiddenTarget</kbd> || <kbd>void UnregisterForbiddenTarget(CBaseEntity ''entity'')</kbd>
| <code>void UserDefinedEvent1()</code>
| Unregisters a target entity as forbidden.
| These trigger the appropriate output from the [[info_director]] entity when called.
|-
|-
| <code>UserDefinedEvent2</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 UserDefinedEvent2()</code>
| When called, these trigger the appropriate output of the {{Code|[[info_director]]}} entity.
|  
|  
|-
|-
| <code>UserDefinedEvent3</code>
| <kbd>WarpAllSurvivorsToBattlefield</kbd> || <kbd>void WarpAllSurvivorsToBattlefield()</kbd>
| <code>void UserDefinedEvent3()</code>
| Warp all Survivors to the battlefield.
|
|-
| <code>UserDefinedEvent4</code>
| <code>void UserDefinedEvent4()</code>
|  
|-
|-
| <code>WarpAllSurvivorsToBattlefield</code>
| <kbd>WarpAllSurvivorsToCheckpoint</kbd> || <kbd>void WarpAllSurvivorsToCheckpoint()</kbd>
| <code>void WarpAllSurvivorsToBattlefield()</code>
| Warp all Survivors to the battlefield.
|-
| <code>WarpAllSurvivorsToCheckpoint</code>
| <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. 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:
 
{| width=100%
|- style="vertical-align:top;"
|
<source lang=js>
local ent = null;
while ( ent = Entities.FindByClassname(ent, "weapon_*") )
{
  // ...
}
</source>
|
<source lang=js>
for (local ent; ent = Entities.FindByClassname(ent, "weapon_*"); )
{
  // ...
}
</source>
|}


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


To iterate over a set of entities, pass <code>null</code> to the ''previous'' argument in the appropriate method to start an iteration, or reference to a previously found entity to continue a search.


==== 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.  
|-
|-
| <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 model 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 name.  
|-
|-
| <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 name nearest to a point.
|-
|-
| <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 name within a radius.
|-
|-
| <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.
| Find entities within a 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.
| Begin an iteration over the 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 belongs to a valid entity.
|}
|}
<!--
==== Code Samples ====


Example:
<source lang=js>
</source>
-->


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


Script handle class for [[env_entity_maker]].  
Script handle class for [[env_entity_maker]].  
Line 1,065: 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,088: 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,094: 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>


=== CNavMesh ===
An interface to the Navigation Mesh.
Game Instance: <code>NavMesh</code>


==== 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>IsValid</code>
| <kbd>FindLadderAlongRay</kbd> || <kbd>CNavLadder FindLadderAlongRay(Vector ''startpos'', Vector ''endpos'', TerrorNavArea ''ignoreArea'')</kbd>
| <code>bool IsValid()</code>
| Get nav ladder from ray.
| Whether the handle belongs to a valid entity. {{todo|Does the nav mesh have an entity?}}
|-
|-
| <code>UnblockRescueVehicleNav</code>
| <kbd>FindNavAreaAlongRay</kbd> || <kbd>TerrorNavArea FindNavAreaAlongRay(Vector ''startpos'', Vector ''endpos'', TerrorNavArea ''ignoreArea'')</kbd>
| <code>void UnblockRescueVehicleNav()</code>
| Get nav area from ray.
| Unblock the rescue vehicle nav areas so bots can path through them.
|-
|}
| <kbd>GetAllAreas</kbd> || <kbd>void GetAllAreas(table)</kbd>
 
| Fills a passed in table of all nav areas.
 
=== CNetPropManager ===
 
Game Instance: <code>NetProps</code>
 
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").
 
{{warning|Each netprop has a set size in bits, exceeding the size may desync the clients from the server causing unpredictable behavior.}}
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function
! Signature
! Description
|-
|-
| <code>GetPropArraySize</code>
| <kbd>GetAllLadders</kbd> || <kbd>void GetAllLadders(table)</kbd>
| <code>int GetPropArraySize(CBaseEntity ''entity'', string ''propertyName'')</code>
| Fills a passed in table of all nav ladders.
| Returns the size of an netprop array, or -1.
|-
|-
| <code>GetPropEntity</code>
| <kbd>GetAreasWithAttributes</kbd> || <kbd>void GetAreasWithAttributes(int ''bits'', table)</kbd>
| <code>CBaseEntity GetPropEntity(CBaseEntity ''entity'', string ''propertyName'')</code>
| Fills a passed in table of all nav areas that have the specified attributes.
| Reads an EHANDLE valued netprop (21 bit integer). Returns the script handle of the entity.
|-
|-
| <code>GetPropEntityArray</code>
| <kbd>GetLadderByID</kbd> || <kbd>CNavLadder GetLadderByID(int ''id'')</kbd>
| <code>CBaseEntity GetPropEntityArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| Get nav ladder by ID.
| Reads an EHANDLE valued netprop (21 bit integer) from an array. Returns the script handle of the entity.
|-
|-
| <code>GetPropFloat</code>
| <kbd>GetLadderCount</kbd> || <kbd>int GetLadderCount()</kbd>
| <code>float GetPropFloat(CBaseEntity ''entity'', string ''propertyName'')</code>
| Return total number of nav ladders.
| Reads a float valued netprop.
|-
|-
| <code>GetPropFloatArray</code>
| <kbd>GetNavArea</kbd> || <kbd>TerrorNavArea GetNavArea(Vector ''origin'', float ''flBeneath'')</kbd>
| <code>float GetPropFloatArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| Given a position in the world, return the nav area that is closest and at the same height, or beneath it.
| Reads a float valued netprop from an array.
|-
|-
| <code>GetPropInt</code>
| <kbd>GetNavAreaByID</kbd> || <kbd>TerrorNavArea GetNavAreaByID(int ''id'')</kbd>
| <code>int GetPropInt(CBaseEntity ''entity'', string ''propertyName'')</code>
| Get nav area by ID.
| Reads an integer valued netprop.
|-
|-
| <code>GetPropIntArray</code>
| <kbd>GetNavAreaCount</kbd> || <kbd>int GetNavAreaCount()</kbd>
| <code>int GetPropIntArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| Return total number of nav areas.
| Reads an integer valued netprop from an array.
|-
|-
| <code>GetPropString</code>
| <kbd>GetNavAreasFromBuildPath</kbd> || <kbd>bool GetNavAreasFromBuildPath(TerrorNavArea ''startArea'', TerrorNavArea ''endArea'', Vector ''goalPos'', float ''flMaxPathLength'', int ''teamID'', bool ''ignoreNavBlockers'', table)</kbd>
| <code>string GetPropString(CBaseEntity ''entity'', string ''propertyName'')</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'.
| Reads an string valued netprop.
|-
|-
| <code>GetPropStringArray</code>
| <kbd>GetNavAreasInRadius</kbd> || <kbd>void GetNavAreasInRadius(Vector ''origin'', float ''radius'', table)</kbd>
| <code>string GetPropStringArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| Fills a passed in table of nav areas within radius.
| Reads an string valued netprop from an array.
|-
|-
| <code>GetPropType</code>
| <kbd>GetNavAreasOverlappingEntityExtent</kbd> || <kbd>void GetNavAreasOverlappingEntityExtent(CBaseEntity ''entity'', table)</kbd>
| <code>string GetPropType(CBaseEntity ''entity'', string ''propertyName'')</code>
| Fills passed in table with areas overlapping entity's extent.
| Returns the name of the netprop type as a string.
|-
|-
| <code>GetPropVector</code>
| <kbd>GetNearestNavArea</kbd> || <kbd>TerrorNavArea GetNearestNavArea(Vector ''origin'', float ''maxDist'', bool ''checkLOS'', bool ''checkGround'')</kbd>
| <code>Vector GetPropVector(CBaseEntity ''entity'', string ''propertyName'')</code>
| Given a position in the world, return the nav area that is closest and at the same height, or beneath it.
| Reads a 3D vector valued netprop. {{todo | Does it work for other dimensions too?}}
|-
|-
| <code>GetPropVectorArray</code>
| <kbd>GetObstructingEntities</kbd> || <kbd>void GetObstructingEntities(table)</kbd>
| <code>Vector GetPropVectorArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</code>
| Fills a passed in table of all obstructing entities.
| Reads a 3D vector valued netprop from an array.  
|-
|-
| <code>HasProp</code>
| <kbd>IsValid</kbd> || <kbd>bool IsValid()</kbd>
| <code>bool HasProp(CBaseEntity ''entity'', string ''propertyName'')</code>
| Whether the handle belongs to a valid entity. Redundant as navigation meshes are not entity related.
| Checks if a netprop exists.
|-
|-
| <code>SetPropEntity</code>
| <kbd>NavAreaBuildPath</kbd> || <kbd>bool NavAreaBuildPath(TerrorNavArea ''startArea'', TerrorNavArea ''endArea'', Vector ''goalPos'', float ''flMaxPathLength'', int ''teamID'', bool ''ignoreNavBlockers'')</kbd>
| <code>void SetPropEntity(CBaseEntity ''entity'', string ''propertyName'', CBaseEntity ''value'')</code>
| Returns true if a path exists. If 'endArea' is NULL, will compute a path as close as possible to 'goalPos'.
| Sets an EHANDLE valued netprop (21 bit integer) to reference the specified entity.
|-
|-
| <code>SetPropEntityArray</code>
| <kbd>NavAreaTravelDistance</kbd> || <kbd>float NavAreaTravelDistance(TerrorNavArea ''startArea'', TerrorNavArea ''endArea'', float ''flMaxPathLength'')</kbd>
| <code>void SetPropEntityArray(CBaseEntity ''entity'', string ''propertyName'', CBaseEntity ''value'', int ''arrayElement'')</code>
| Compute distance between two areas. Return -1 if can't reach 'endArea' from 'startArea'.
| Sets an EHANDLE valued netprop (21 bit integer) from an array to reference the specified entity.
|-
|-
| <code>SetPropFloat</code>
| <kbd>RegisterAvoidanceObstacle</kbd> || <kbd>void RegisterAvoidanceObstacle(CBaseEntity ''entity'')</kbd>
| <code>void SetPropFloat(CBaseEntity ''entity'', string ''propertyName'', float ''value'')</code>
| Registers an entity as an avoidance obstacle.
| Sets a netprop to the specified float.
|-
|-
| <code>SetPropFloatArray</code>
| <kbd>UnblockRescueVehicleNav</kbd> || <kbd>void UnblockRescueVehicleNav()</kbd>
| <code>void SetPropFloatArray(CBaseEntity ''entity'', string ''propertyName'', float ''value'', int ''arrayElement'')</code>
| Unblock the rescue vehicle nav areas so bots can path through them.
| Sets a netprop from an array to the specified float.
|-
|-
| <code>SetPropInt</code>
| <kbd>UnregisterAvoidanceObstacle</kbd> || <kbd>void UnregisterAvoidanceObstacle(CBaseEntity ''entity'')</kbd>
| <code>void SetPropInt(CBaseEntity ''entity'', string ''propertyName'', int ''value'')</code>
| Unregisters an entity as an avoidance obstacle.
| Sets a netprop to the specified integer.
|}
 
=== 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>SetPropIntArray</code>
| <kbd>AddIncomingConnection</kbd> || <kbd>void AddIncomingConnection(TerrorNavArea ''area'', int ''dir'')</kbd>
| <code>void SetPropInt(CBaseEntity ''entity'', string ''propertyName'', int ''value'', int ''arrayElement'')</code>
| Add areas that connect TO this area by a ONE-WAY link.
| Sets a netprop from an array to the specified integer.
|-
| <kbd>ComputeDirection</kbd> || <kbd>int ComputeDirection(Vector ''point'')</kbd>
| Return direction from this area to the given point.
|-
| <kbd>ConnectTo</kbd> || <kbd>void ConnectTo(TerrorNavArea ''area'', int ''dir'')</kbd>
| Connect this area to given area in given direction. If you set direction to -1, it will be automatically applied.
|-
| <kbd>ConnectToLadder</kbd> || <kbd>void ConnectToLadder(CNavLadder ''ladder'')</kbd>
| Connect this area to given ladder.
|-
| <kbd>Contains</kbd> || <kbd>bool Contains(TerrorNavArea ''area'')</kbd>
| Return true if other area is on or above this area, but no others.
|-
|-
| <code>SetPropString</code>
| <kbd>ContainsOrigin</kbd> || <kbd>bool ContainsOrigin(Vector ''point'')</kbd>
| <code>void SetPropString(CBaseEntity ''entity'', string ''propertyName'', string ''value'')</code>
| Return true if given point is on or above this area, but no others.
| Sets a netprop to the specified string.
|-
|-
| <code>SetPropStringArray</code>
| <kbd>DebugDrawFilled</kbd> || <kbd>void DebugDrawFilled(int ''r'', int ''g'', int ''b'', int ''a'', float ''duration'', bool ''noDepthTest'')</kbd>
| <code>void SetPropStringArray(CBaseEntity ''entity'', string ''propertyName'', string ''value'', int ''arrayElement'')</code>
| Draw area as a filled rectangle of the given color.
| Sets a netprop from an array to the specified string.
|-
|-
| <code>SetPropVector</code>
| <kbd>Disconnect</kbd> || <kbd>void Disconnect(TerrorNavArea ''area'')</kbd>
| <code>void SetPropVector(CBaseEntity ''entity'', string ''propertyName'', Vector ''value'')</code>
| Disconnect this area from given area.
| Sets a netprop to the specified vector.
|-
|-
| <code>SetPropVectorArray</code>
| <kbd>DisconnectLadder</kbd> || <kbd>void DisconnectLadder(CNavLadder ''ladder'')</kbd>
| <code>void SetPropVectorArray(CBaseEntity ''entity'', string ''propertyName'', Vector ''value'', int ''arrayElement'')</code>
| Disconnect this area from given ladder.
| Sets a netprop from an array to the specified vector.
|}
 
=== CScriptEntityOutputs ===
 
Game Instance: <code>EntityOutputs</code>
 
Allows manipulation of entity output data.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function
! Signature
! Description
|-
|-
| <code>AddOutput</code>
| <kbd>FindRandomSpot</kbd> || <kbd>Vector FindRandomSpot()</kbd>
| <code>void AddOutput(CBaseEntity ''entity'', string ''outputName'', string ''targetName'', string ''inputName'', string ''parameter'', float ''delay'', int ''timesToFire'')</code>
| Get random origin within extent of area.
| Adds a new output to the entity.
|-
|-
| <code>GetNumElements</code>
| <kbd>GetAdjacentArea</kbd> || <kbd>TerrorNavArea GetAdjacentArea(int ''dir'', int ''nAreas'')</kbd>
| <code>int GetNumElements(CBaseEntity ''entity'', string ''outputName'')</code>
| Return the n'th adjacent area in the given direction.
| Returns the number of array elements.
|-
|-
| <code>GetOutputTable</code>
| <kbd>GetAdjacentAreas</kbd> || <kbd>void GetAdjacentAreas(int ''dir'', table)</kbd>
| <code>void GetOutputTable(CBaseEntity ''entity'', string ''outputName'', table, int ''arrayElement'')</code>
| Fills a passed in table with all adjacent areas in the given direction.
| Fills the passed table with output information.
|-
|-
| <code>HasAction</code>
| <kbd>GetAdjacentCount</kbd> || <kbd>int GetAdjacentCount(int ''dir'')</kbd>
| <code>bool HasAction(CBaseEntity ''entity'', string ''outputName'')</code>
| Get the number of adjacent areas in the given direction.
| Returns true if an action exists for the output.
|-
|-
| <code>HasOutput</code>
| <kbd>GetAttributes</kbd> || <kbd>int GetAttributes()</kbd>
| <code>bool HasOutput(CBaseEntity ''entity'', string ''outputName'')</code>
| Get area attribute bits.
| Returns true if the output exists.
|-
|-
| <code>RemoveOutput</code>
| <kbd>GetAvoidanceObstacleHeight</kbd> || <kbd>float GetAvoidanceObstacleHeight()</kbd>
| <code>void RemoveOutput(CBaseEntity ''entity'', string ''outputName'', string ''targetName'', string ''inputName'', string ''parameter'')</code>
| Returns the maximum height of the obstruction above the ground.
| Removes an output from the entity.
|-
|}
| <kbd>GetCenter</kbd> || <kbd>Vector GetCenter()</kbd>
 
| Get center origin of area.
=== CScriptResponseCriteria ===
|-
 
| <kbd>GetCorner</kbd> || <kbd>Vector GetCorner(int ''corner'')</kbd>
Game Instance: <code>ResponseCriteria</code>
| Get corner origin of area.
 
|-
Allows reading the response rules of an entity.  
| <kbd>GetDistanceSquaredToPoint</kbd> || <kbd>float GetDistanceSquaredToPoint(Vector ''pos'')</kbd>
 
| Return shortest distance between point and this area.
==== Methods ====
|-
{| class="standard-table" style="width: 100%;"
| <kbd>GetDoor</kbd> || <kbd>CBaseEntity GetDoor()</kbd>
! Function
| Returns the door entity above the area.
! Signature
|-
! Description
| <kbd>GetElevator</kbd> || <kbd>CBaseEntity GetElevator()</kbd>
| Returns the elevator if in an elevator's path.
|-
|-
| <code>GetTable</code>
| <kbd>GetElevatorAreas</kbd> || <kbd>void GetElevatorAreas(table)</kbd>
| <code>void GetTable(CBaseEntity ''entity'', table)</code>
| Fills a passed in table with a collection of areas reachable via elevator from this area.
| Fills the passed table with all criteria.
|-
|-
| <code>GetValue</code>
| <kbd>GetID</kbd> || <kbd>int GetID()</kbd>
| <code>string GetValue(CBaseEntity ''entity'', string ''criteriaName'')</code>
| Get area ID.
| Returns a string.
|-
|-
| <code>HasCriterion</code>
| <kbd>GetIncomingConnections</kbd> || <kbd>void GetIncomingConnections(int ''dir'', table)</kbd>
| <code>bool HasCriterion(CBaseEntity ''entity'', string ''criteriaName'')</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).
| Returns true if the criterion exists.
|}
 
=== Convars ===
Game Instance: <code>Convars</code>
 
Provides an interface for getting and setting [[Convar|convars]] on the server.
 
{{todo|The class for this doesn't seem to be directly available.}}
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function
! Signature
! Description
|-
|-
| <code>GetClientConvarValue</code>
| <kbd>GetLadders</kbd> || <kbd>void GetLadders(int ''dir'', table)</kbd>
| <code>string GetClientConvarValue(string ''name'', int ''entindex'')</code>
| Fills a passed in table of ladders in direction.
| Returns the convar value for the entindex as a string. Only works with client convars with the FCVAR_USERINFO flag.  
|-
|-
| <code>GetStr</code>
| <kbd>GetParent</kbd> || <kbd>TerrorNavArea GetParent()</kbd>
| <code>string GetStr(string ''name'')</code>
| Returns the area just prior to this one in the search path.
| Returns the convar as a string. May return null if no such convar.  
|-
|-
| <code>GetFloat</code>
| <kbd>GetParentHow</kbd> || <kbd>int GetParentHow()</kbd>
| <code>float GetFloat(string ''name'')</code>
| Returns how we get from parent to us.
| Returns the convar as a float. May return null if no such convar.
|-
|-
| <code>SetValue</code>
| <kbd>GetPlaceName</kbd> || <kbd>string GetPlaceName()</kbd>
| <code>void SetValue(string ''name'', ''value'')</code>
| Get place name, null if no name.
| Sets the value of the convar. Supported types are bool, int, float, string.  
|-
|}
| <kbd>GetPlayerCount</kbd> || <kbd>int GetPlayerCount(int ''team'')</kbd>
 
| Return number of players of given team currently within this area (team of zero means any/all).
=== CPointTemplate ===
|-
Extends [[#CBaseEntity|CBaseEntity]]
| <kbd>GetRandomAdjacentArea</kbd> || <kbd>TerrorNavArea GetRandomAdjacentArea(int ''dir'')</kbd>
 
| Return a random adjacent area in the given direction.
Script handle class for [[point_template]].
|-
 
| <kbd>GetSizeX</kbd> || <kbd>float GetSizeX()</kbd>
==== Hooks ====
| Return the area size along the X axis.
 
|-
;<code>table PreSpawnInstance(string ''entityClass'', string ''entityName'')</code>
| <kbd>GetSizeY</kbd> || <kbd>float GetSizeY()</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.
| Return the area size along the Y axis.
 
|-
: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.
| <kbd>GetSpawnAttributes</kbd> || <kbd>int GetSpawnAttributes()</kbd>
 
| Get spawn attribute bits.
<source lang="cpp">function PreSpawnInstance( entityClass, entityName )
|-
{
| <kbd>GetTimeSinceCleared</kbd> || <kbd>float GetTimeSinceCleared()</kbd>
return
| Returns the time since the area was cleared.
{
|-
  rendercolor = "0 255 0"
| <kbd>GetZ</kbd> || <kbd>float GetZ(Vector ''pos'')</kbd>
  targetname = "mySpawnedEntity"
| Returns the height of the area at the specified point.
};
|-
}
| <kbd>HasAttributes</kbd> || <kbd>bool HasAttributes(int ''bits'')</kbd>
</source>
| Has area attribute bits.
 
|-
;<code>void PostSpawn(table ''entities'')</code>
| <kbd>HasAvoidanceObstacle</kbd> || <kbd>bool HasAvoidanceObstacle(float ''maxHeight'')</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.  
| Returns true if there's a large, immobile object obstructing this area.
 
|-
<source lang="cpp">function PostSpawn( entities )
| <kbd>HasSpawnAttributes</kbd> || <kbd>bool HasSpawnAttributes(int ''bits'')</kbd>
{
| Has spawn attribute bits.
foreach( name, handle in entities )
|-
{
| <kbd>IsBlocked</kbd> || <kbd>bool IsBlocked(int ''team'', bool ''affectsFlow'')</kbd>
printl( name + ": " + handle );
| Return true if team is blocked in this area.
}
|-
}
| <kbd>IsBottleneck</kbd> || <kbd>bool IsBottleneck()</kbd>
</source>
| Returns true if area is a bottleneck.
 
|-
 
| <kbd>IsCleared</kbd> || <kbd>bool IsCleared(CTerrorPlayer ''player'')</kbd>
=== CPointScriptTemplate ===
| Returns true if this area has been cleared for the player.
Extends [[#CBaseEntity|CBaseEntity]]
|-
 
| <kbd>IsCompletelyVisibleToTeam</kbd> || <kbd>bool IsCompletelyVisibleToTeam(int ''team'')</kbd>
Script handle class for [[point_script_template]].
| Return true if given area is completely visible from somewhere in this area by someone on the team.
 
|-
==== Methods ====
| <kbd>IsConnected</kbd> || <kbd>bool IsConnected(TerrorNavArea ''area'', int ''dir'')</kbd>
 
| 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)
{| class=standard-table style="width: 100%;"
! Function
! Signature
! Description
|-
|-
|<code>AddTemplate</code>
| <kbd>IsConnectedLadder</kbd> || <kbd>bool IsConnectedLadder(CNavLadder ''ladder'', int ''dir'')</kbd>
|<code>void AddTemplate(string, handle)</code>
| Return true if this area is connected to ladder in given direction.
|Add an entity to the template spawner.
|-
|-
|<code>SetGroupSpawnTables</code>
| <kbd>IsCoplanar</kbd> || <kbd>bool IsCoplanar(TerrorNavArea ''area'')</kbd>
|<code>void SetGroupSpawnTables(handle, handle)</code>
| Return true if this area and given area are approximately co-planar.
|Cache the group spawn tables.
|}
 
 
=== CSimpleCallChainer ===
Seems to have the same members as [[#CCallChainer|CCallChainer]].
{{todo}}
 
 
=== 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>
| <kbd>IsDamaging</kbd> || <kbd>bool IsDamaging()</kbd>
|<code>void CanShowBuildPanel(bool ''showPanel'')</code>
| Return true if continuous damage (ie: fire) is in this area.
|Sets if the UI panel for the button is shown.
|-
|-
|<code>GetUseModelName</code>
| <kbd>IsDegenerate</kbd> || <kbd>bool IsDegenerate()</kbd>
|<code>string GetUseModelName()</code>
| Return true if this area is badly formed.
|Get the entity name of the prop bound to this button.
|-
|-
|<code>SetProgressBarText</code>
| <kbd>IsEdge</kbd> || <kbd>bool IsEdge(int ''dir'')</kbd>
|<code>void SetProgressBarText(string ''text'')</code>
| Return true if there are no bi-directional links on the given side.
|Sets the use text for the button UI.
|-
|-
|<code>SetProgressBarSubText</code>
| <kbd>IsFlat</kbd> || <kbd>bool IsFlat()</kbd>
|<code>void SetProgressBarText(string ''text'')</code>
| Return true if this area is approximately flat.
|Sets the subtext below the progress bar for the button UI.
|-
|-
|<code>SetProgressBarFinishTime</code>
| <kbd>IsOverlapping</kbd> || <kbd>bool IsOverlapping(TerrorNavArea ''area'')</kbd>
|<code>void SetProgressBarFinishTime(float ''time'')</code>
| Return true if 'area' overlaps our 2D extents.
|Sets the total time the button takes to use. If '0', no progress bar will be displayed.
|-
|-
|<code>SetProgressBarCurrentProgress</code>
| <kbd>IsOverlappingOrigin</kbd> || <kbd>bool IsOverlappingOrigin(Vector ''pos'', float ''tolerance'')</kbd>
|<code>void SetProgressBarCurrentProgress(float ''time'')</code>
| Return true if 'pos' is within 2D extents of area.
|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>IsPotentiallyVisibleToTeam</kbd> || <kbd>bool IsPotentiallyVisibleToTeam(int ''team'')</kbd>
|<code>void StopUse()</code>
| Return true if any portion of this area is visible to anyone on the given team.
|Stop the current use action.
|-
|-
|}
| <kbd>IsRoughlySquare</kbd> || <kbd>bool IsRoughlySquare()</kbd>
 
| Return true if this area is approximately square.
 
==== Members ====
These variables are only available in the Entity Script after the entity has spawned. They contain entity handles, which differ from normal script handles, and can be compared with the output of the <code>[[#CBaseEntity|CBaseEntity]]::GetEntityHandle()</code> method.
 
{| class="standard-table" style="width: 100%;"
! Instance
! Type
! Description
|-
|-
| <code>UseModelEntity</code>
| <kbd>IsSpawningAllowed</kbd> || <kbd>bool IsSpawningAllowed()</kbd>
| <code>entity handle</code>
| Returns true if spawning is allowed in this area.
| The Use Model prop associated with this entity.
|-
| <kbd>IsUnderwater</kbd> || <kbd>bool IsUnderwater()</kbd>
| Return true if area is underwater.
|-
| <kbd>IsValid</kbd> || <kbd>bool IsValid()</kbd>
| Whether the handle belongs to a valid area.
|-
| <kbd>IsValidForWanderingPopulation</kbd> || <kbd>bool IsValidForWanderingPopulation()</kbd>
| Returns true if area is valid for wandering population.
|-
| <kbd>IsVisible</kbd> || <kbd>bool IsVisible(Vector ''point'')</kbd>
| Return true if area is visible from the given point.
|-
| <kbd>MarkAreaCleared</kbd> || <kbd>void MarkAreaCleared(CTerrorPlayer ''player'')</kbd>
| Mark this area as cleared for the player.
|-
| <kbd>MarkAreaNotCleared</kbd> || <kbd>void MarkAreaNotCleared()</kbd>
| Mark this area as not cleared.
|-
| <kbd>MarkAsBlocked</kbd> || <kbd>void MarkAsBlocked(int ''team'')</kbd>
| Mark this area as blocked for team.
|-
| <kbd>MarkAsDamaging</kbd> || <kbd>void MarkAsDamaging(float ''duration'')</kbd>
| Mark this area is damaging for the next 'duration' seconds.
|-
| <kbd>MarkObstacleToAvoid</kbd> || <kbd>void MarkObstacleToAvoid(float ''height'')</kbd>
| Marks the obstructed status of the nav area.
|-
| <kbd>RemoveAttributes</kbd> || <kbd>void RemoveAttributes(int ''bits'')</kbd>
| Removes area attribute bits.
|-
|-
| <code>PlayerUsingMe</code>
| <kbd>RemoveOrthogonalConnections</kbd> || <kbd>void RemoveOrthogonalConnections(int ''dir'')</kbd>
| <code>entity handle</code>
| Removes all connections in directions to left and right of specified direction.
| The current using player. Set to 0 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]].
{| class=standard-table
! Function
! Signature
! Description
|-
|-
|<code>OnUseFinished</code>
| <kbd>RemoveSpawnAttributes</kbd> || <kbd>void RemoveSpawnAttributes(int ''bits'')</kbd>
|<code>void OnUseFinished()</code>
| Remove spawn attribute bits.
|Called when the player has used this button for at least 'FinishTime' seconds.
|-
|-
|<code>OnUseStart</code>
| <kbd>SetAttributes</kbd> || <kbd>void SetAttributes(int ''bits'')</kbd>
|<code>bool OnUseStart()</code>
| Set area attribute bits.
|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>SetPlaceName</kbd> || <kbd>void SetPlaceName(string ''name'')</kbd>
|<code>void OnUseStop(float ''timeUsed'')</code>
| Set place name. If you pass null, the place name will be set to nothing.
|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>SetSpawnAttributes</kbd> || <kbd>void SetSpawnAttributes(int ''bits'')</kbd>
|<code>void Precache()</code>
| Set spawn attribute bits.
|Called by the game engine when the entity first spawns, immediately after this script is run.
|-
|-
| <kbd>UnblockArea</kbd> || <kbd>void UnblockArea()</kbd>
| Unblocks this area.
|}
|}


=== Decider ===
=== CNavLadder ===
''An isolated instance of a rulescript database.''
{{↑|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>constructor</code>
| <kbd>ConnectTo</kbd> || <kbd>void ConnectTo(TerrorNavArea ''area'')</kbd>
|  
| Connect this ladder to given area.
|  
|-
| <kbd>Disconnect</kbd> || <kbd>void Disconnect(TerrorNavArea ''area'')</kbd>
| Disconnect this ladder from given area.
|-
|-
| <code>AddRule</code>
| <kbd>GetBottomArea</kbd> || <kbd>TerrorNavArea GetBottomArea()</kbd>
| <code>bool AddRule(handle ''CRule'')</code>
| Area of the bottom of the ladder.
| Add a CRule object (defined in rulescript_base.nut)
|-
|-
| <code>FindAllMatches</code>
| <kbd>GetBottomOrigin</kbd> || <kbd>Vector GetBottomOrigin()</kbd>
| <code>handle FindAllMatches(handle ''query'', float ''leeway'')</code>
| World coords of the bottom of the ladder.
| 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>GetDir</kbd> || <kbd>int GetDir()</kbd>
| <code>handle FindBestMatch(handle ''query'')</code>
| Return the way the ladder faces (ie: surface normal of climbable side).
| Query the database and return the best result found. If multiple of equal score found, an arbitrary one returns.  
|-
|-
| <code>IsValid</code>
| <kbd>GetID</kbd> || <kbd>int GetID()</kbd>
| <code>bool IsValid()</code>
| Get ladder ID.
| Whether the object belongs to a valid entity(?).
|-
| <kbd>GetLadderEntity</kbd> || <kbd>CBaseEntity GetLadderEntity()</kbd>
| Returns the ladder entity.
|-
| <kbd>GetLength</kbd> || <kbd>float GetLength()</kbd>
| Return the length of the ladder.
|-
| <kbd>GetPosAtHeight</kbd> || <kbd>Vector GetPosAtHeight(float ''height'')</kbd>
| Return x,y coordinate of the ladder at a given height.
|-
| <kbd>GetTopArea</kbd> || <kbd>TerrorNavArea GetTopArea()</kbd>
| Area of the top of the ladder.
|-
| <kbd>GetTopOrigin</kbd> || <kbd>Vector GetTopOrigin()</kbd>
| World coords of the top of the ladder.
|-
| <kbd>GetWidth</kbd> || <kbd>float GetWidth()</kbd>
| Return the width of the ladder.
|-
| <kbd>IsConnected</kbd> || <kbd>bool IsConnected(TerrorNavArea ''area'', int ''dir'')</kbd>
| Return true if given ladder is connected in given direction.
|-
| <kbd>IsInUse</kbd> || <kbd>bool IsInUse(CBaseEntity ''ignore'')</kbd>
| Return true if someone is on this ladder (other than 'ignore').
|-
| <kbd>IsUsableByTeam</kbd> || <kbd>bool IsUsableByTeam(int ''teamID'')</kbd>
| Returns true if ladder is usable for team.
|-
| <kbd>IsValid</kbd> || <kbd>bool IsValid()</kbd>
| Whether the handle belongs to a valid ladder.
|}
|}


=== CNetPropManager ===
{{↑|toc}}
{{↑|Instances}} Game Instance: <kbd>NetProps</kbd>
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. i.e. {{Code|m_itTimer.m_timestamp}}.


=== regexp ===
{{warning|Each netprop has a set size in bits, exceeding the size may desync the clients from the server causing unpredictable behavior.}}
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
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>constructor</code>
| <kbd>GetPropArraySize</kbd> || <kbd>int GetPropArraySize(CBaseEntity ''entity'', string ''propertyName'')</kbd>
| <code>regexp()</code>
| Returns the size of an netprop array, or -1.
|  
|-
| <kbd>GetPropEntity</kbd> || <kbd>CBaseEntity GetPropEntity(CBaseEntity ''entity'', string ''propertyName'')</kbd>
| Reads an EHANDLE-valued netprop (21 bit integer). Returns the script handle of the entity.
|-
|-
| <code>capture</code>
| <kbd>GetPropEntityArray</kbd> || <kbd>CBaseEntity GetPropEntityArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</kbd>
| <code> [table] capture(''str'', [''start''])</code>
| Reads an EHANDLE-valued netprop (21 bit integer) from an array. Returns the script handle of the entity.
| 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>GetPropFloat</kbd> || <kbd>float GetPropFloat(CBaseEntity ''entity'', string ''propertyName'')</kbd>
| <code> bool match(''str'')</code>
| Reads a float-valued netprop.
| Returns a true if the regular expression matches the string str, otherwise returns false.  
|-
|-
| <code>search</code>
| <kbd>GetPropFloatArray</kbd> || <kbd>float GetPropFloatArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</kbd>
| <code>table search(''str'', [''start''])</code>
| Reads a float-valued netprop from an array.
| 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>GetPropInt</kbd> || <kbd>int GetPropInt(CBaseEntity ''entity'', string ''propertyName'')</kbd>
|  
| Reads an integer-valued netprop.
|  
|-
|}
| <kbd>GetPropIntArray</kbd> || <kbd>int GetPropIntArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</kbd>
 
| Reads an integer-valued netprop from an array.
 
|-
=== LateBinder ===
| <kbd>GetPropString</kbd> || <kbd>string GetPropString(CBaseEntity ''entity'', string ''propertyName'')</kbd>
 
| Reads an string-valued netprop.
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function
! Signature
! Description
|-
|-
| <code>Begin</code>
| <kbd>GetPropStringArray</kbd> || <kbd>string GetPropStringArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</kbd>
|  
| Reads an string-valued netprop from an array.
|  
|-
|-
| <code>End</code>
| <kbd>GetPropType</kbd> || <kbd>string GetPropType(CBaseEntity ''entity'', string ''propertyName'')</kbd>
|  
| Returns the name of the netprop type as a string.
|  
|-
|-
| <code>EstablishDelegation</code>
| <kbd>GetPropVector</kbd> || <kbd>Vector GetPropVector(CBaseEntity ''entity'', string ''propertyName'')</kbd>
|  
| Reads a 3D vector-valued netprop. {{todo | Does it work for other dimensions too?}}
|  
|-
|-
| <code>HookRootMetamethod</code>
| <kbd>GetPropVectorArray</kbd> || <kbd>Vector GetPropVectorArray(CBaseEntity ''entity'', string ''propertyName'', int ''arrayElement'')</kbd>
|  
| Reads a 3D vector-valued netprop from an array.
|  
|-
|-
| <code>UnhookRootMetamethod</code>
| <kbd>HasProp</kbd> || <kbd>bool HasProp(CBaseEntity ''entity'', string ''propertyName'')</kbd>
|  
| Checks if a netprop exists.
|  
|-
|-
| <code>RemoveDelegation</code>
| <kbd>SetPropEntity</kbd> || <kbd>void SetPropEntity(CBaseEntity ''entity'', string ''propertyName'', CBaseEntity ''value'')</kbd>
|  
| Sets an EHANDLE-valued netprop (21 bit integer) to reference the specified entity.
|  
|-
|-
| <code>Resolve</code>
| <kbd>SetPropEntityArray</kbd> || <kbd>void SetPropEntityArray(CBaseEntity ''entity'', string ''propertyName'', CBaseEntity ''value'', int ''arrayElement'')</kbd>
|  
| Sets an EHANDLE-valued netprop (21 bit integer) from an array to reference the specified entity.
|  
|-
|}
| <kbd>SetPropFloat</kbd> || <kbd>void SetPropFloat(CBaseEntity ''entity'', string ''propertyName'', float ''value'')</kbd>
 
| Sets a netprop to the specified float.
 
|-
==== Members ====
| <kbd>SetPropFloatArray</kbd> || <kbd>void SetPropFloatArray(CBaseEntity ''entity'', string ''propertyName'', float ''value'', int ''arrayElement'')</kbd>
{| class="standard-table" style="width: 100%;"
| Sets a netprop from an array to the specified float.
! Instance
! Type
! Description
|-
|-
| <code>m_bindNamesStack</code>
| <kbd>SetPropInt</kbd> || <kbd>void SetPropInt(CBaseEntity ''entity'', string ''propertyName'', int ''value'')</kbd>
| <code>array</code>
| Sets a netprop to the specified integer.
|  
|-
|-
| <code>m_fixupSet</code>
| <kbd>SetPropIntArray</kbd> || <kbd>void SetPropIntArray(CBaseEntity ''entity'', string ''propertyName'', int ''value'', int ''arrayElement'')</kbd>
| <code>array</code>
| Sets a netprop from an array to the specified integer.
|  
|-
|-
| <code>m_log</code>
| <kbd>SetPropString</kbd> || <kbd>void SetPropString(CBaseEntity ''entity'', string ''propertyName'', string ''value'')</kbd>
| <code>bool</code>
| Sets a netprop to the specified string.
|  
|-
|-
| <code>m_logIndent</code>
| <kbd>SetPropStringArray</kbd> || <kbd>void SetPropStringArray(CBaseEntity ''entity'', string ''propertyName'', string ''value'', int ''arrayElement'')</kbd>
| <code>int</code>
| Sets a netprop from an array to the specified string.
|  
|-
|-
| <code>m_targetTable</code>
| <kbd>SetPropVector</kbd> || <kbd>void SetPropVector(CBaseEntity ''entity'', string ''propertyName'', Vector ''value'')</kbd>
| <code>table?(null)</code>
| Sets a netprop to the specified vector.
|  
|-
|-
| <kbd>SetPropVectorArray</kbd> || <kbd>void SetPropVectorArray(CBaseEntity ''entity'', string ''propertyName'', Vector ''value'', int ''arrayElement'')</kbd>
| Sets a netprop from an array to the specified vector.
|}
|}


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


=== QAngle ===
Allows reading and changing of entities' output data.
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 ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>constructor</code>
| <kbd>AddOutput</kbd> || <kbd>void AddOutput(CBaseEntity ''entity'', string ''outputName'', string ''targetName'', string ''inputName'', string ''parameter'', float ''delay'', int ''timesToFire'')</kbd>
| <code>QAngle()</code>
| Adds a new output to the entity.
| Creates a new QAngle facing the positive x-axis.
|-
|-
| <code>constructor</code>
| <kbd>GetNumElements</kbd> || <kbd>int GetNumElements(CBaseEntity ''entity'', string ''outputName'')</kbd>
| <code>QAngle(float ''pitch'', float ''yaw'', float ''roll'')</code>
| Returns the number of array elements.
| Creates a new QAngle.
|-
|-
| <code>Forward </code>
| <kbd>GetOutputTable</kbd> || <kbd>void GetOutputTable(CBaseEntity ''entity'', string ''outputName'', table, int ''arrayElement'')</kbd>
| <code>Vector Forward()</code>
| Fills the passed table with output information.
| Returns the Forward Vector of the angles.  
|-
|-
| <code>Left</code>
| <kbd>HasAction</kbd> || <kbd>bool HasAction(CBaseEntity ''entity'', string ''outputName'')</kbd>
| <code>Vector Left()</code>
| Returns true if an action exists for the output.
| Returns the left Vector of the angles.
|-
|-
| <code>Pitch</code>
| <kbd>HasOutput</kbd> || <kbd>bool HasOutput(CBaseEntity ''entity'', string ''outputName'')</kbd>
| <code>float Pitch()</code>
| Returns true if the output exists.
| Returns the pitch angle in degrees.
|-
|-
| <code>Roll</code>
| <kbd>RemoveOutput</kbd> || <kbd>void RemoveOutput(CBaseEntity ''entity'', string ''outputName'', string ''targetName'', string ''inputName'', string ''parameter'')</kbd>
| <code>float Roll()</code>
| Removes an output from the entity.
| Returns the roll angle in degrees.
|-
| <code>ToKVString</code>
| <code>string ToKVString()</code>
| Returns a string with the values separated by one space.
|-
| <code>ToQuat</code>
| <code>Quaternion ToQuat()</code>
| Returns a quaternion representaion of the orientation.
|-
| <code>Up</code>
| <code>Vector Up()</code>
| Returns the Up Vector of the angles.
|-
| <code>Yaw</code>
| <code>float Yaw()</code>
| Returns the yaw angle in degrees.
|}
|}


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


==== Members ====
{{↑|Instances}} Game Instance: <kbd>ResponseCriteria</kbd>
 
Allows reading the response rules of an entity.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Instance
! Function !! Signature !! Description
! Type
! Description
|-
|-
| <code>x</code>
| <kbd>GetTable</kbd> || <kbd>void GetTable(CBaseEntity ''entity'', table)</kbd>
| <code>float</code>
| Fills the passed table with all criteria.
| Pitch in degrees.
|-
|-
| <code>y</code>
| <kbd>GetValue</kbd> || <kbd>string GetValue(CBaseEntity ''entity'', string ''criteriaName'')</kbd>
| <code>float</code>
| Returns a string.
| Yaw in degrees.
|-
|-
| <code>z</code>
| <kbd>HasCriterion</kbd> || <kbd>bool HasCriterion(CBaseEntity ''entity'', string ''criteriaName'')</kbd>
| <code>float</code>
| Returns true if the criterion exists.
| Roll in degrees.
|}
|}


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


=== Quaternion ===
An interface to manipulate the [[List of L4D2 Cvars|convars]] on the server.
Quarternions[http://en.wikipedia.org/wiki/Quaternion] represent rotations in three-dimensional space.
<!--
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>constructor</code>
| <kbd>GetClientConvarValue</kbd> || <kbd>string GetClientConvarValue(string ''name'', int ''entindex'')</kbd>
| <code>Quarternion()</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
| Creates a new identity quarternion.
|-
|-
| <code>constructor</code>
| <kbd>GetStr</kbd> || <kbd>string GetStr(string ''name'')</kbd>
| <code>Quarternion(float ''x'',float ''y'',float ''z'',float ''w'')</code>
| Returns the convar as a string. Returns null if no such convar.  
| Creates a new quarternion of the form <code>''w'' + ''x'''''i''' + ''y'''''j''' + ''z'''''k'''</code>.
|-
|-
| <code>Dot</code>
| <kbd>GetFloat</kbd> || <kbd>float GetFloat(string ''name'')</kbd>
| <code>float Dot(Quarternion ''factor'')</code>
| Returns the convar as a float. Returns null if no such convar.
| The 4D scalar product of two quaternions. represents the angle between the quaternions in the range [1, 0].
|-
|-
| <code>Invert</code>
| <kbd>SetValue</kbd> || <kbd>void SetValue(string ''name'', ''value'')</kbd>
| <code>Quarternion Invert()</code>
| Sets the value of the convar. Supported types are bool, int, float, string.  
| Returns a quaternion with the complimentary rotation.
|-
| <code>Norm</code>
| <code>Quarternion Norm()</code>
| Normalizes the 4D vector length. {{todo|What effect does this have in quaternions?}}
|-
| <code>SetPitchYawRoll</code>
| <code>void SetPitchYawRoll(float ''pitch'', float ''yaw'', float ''roll'')</code>
| Recomputes the quaternion from the supplied Euler angles.
|-
| <code>ToKVString</code>
| <code>string ToKVString()</code>
| Returns a string with the values separated by one space.
|-
| <code>ToQAngle</code>
| <code>QAngle ToQAngle()</code>
| Returns the angles resulting from the rotation.
|}
|}


=== CPointTemplate ===
{{↑|toc}}
Extends {{↑|CBaseEntity}}


==== Members ====
Script handle class for [[point_template]].
{| class="standard-table" style="width: 100%;"
 
! Instance
==== Hooks ====
! Type
 
! Description
;<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.
| <code>x</code>
| <code>float</code>
| Vector component along the '''i''' axis.
|-
| <code>y</code>
| <code>float</code>
| Vector component along the '''j''' axis.
|-
| <code>z</code>
| <code>float</code>
| Vector component along the '''k''' axis.
|-
| <code>w</code>
| <code>float</code>
| Scalar part.
|}


: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.


=== Vector ===
<source lang="lua">function PreSpawnInstance( entityClass, entityName )
Squirrel equivalent of the C++ [[Vector]] class.
{
return
{
  rendercolor = "0 255 0"
  targetname = "mySpawnedEntity"
}
}
</source>


Three-dimensional vector.
;<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.  


Has overloaded arithmetic operations with both Vectors and scalar values.
<source lang="lua">function PostSpawn( entities )
{
foreach( name, handle in entities )
{
printl( name + ": " + handle )
}
}
</source>


{{note|[http://www.leeland.net/hochsuch.html Example] declaration and manipulation of Vector}}
=== CPointScriptTemplate ===
{{|toc}}
Extends {{↑|CBaseEntity}}
 
Script handle class for [[point_script_template]].


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
 
! Function
{| class=standard-table style="width: 100%;"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>constructor</code>
| <kbd>AddTemplate</kbd> || <kbd>void AddTemplate(string, handle)</kbd>
| <code>Vector()</code>
|Add an entity to the template spawner.
| Creates a new null vector.
|-
|-
| <code>constructor</code>
| <kbd>SetGroupSpawnTables</kbd> || <kbd>void SetGroupSpawnTables(handle, handle)</kbd>
| <code>Vector(float ''x'', float ''y'', float ''z'')</code>
|Cache the group spawn tables.
| Creates a new vector with the specified Cartesian coordiantes.
|}
 
 
=== CPointScriptUseTarget ===
{{↑|toc}}
Extends {{↑|CBaseEntity}}
 
Script handle class for the [[point_script_use_target]] entity.
 
==== Methods ====
 
{| class=standard-table style="width: 100%;"
! Function  !! Signature !! Description
|-
|-
| <code>Cross</code>
| <kbd>CanShowBuildPanel</kbd> || <kbd>void CanShowBuildPanel(bool ''showPanel'')</kbd>
| <code>float Cross(Vector ''factor'')</code>
|Sets if the UI panel for the button is shown.
| The vector product of two vectors. Returns a vector orthogonal to the input vectors.
|-
|-
| <code>Dot</code>
| <kbd>GetUseModelName</kbd> || <kbd>string GetUseModelName()</kbd>
| <code>float Dot(Vector ''factor'')</code>
|Get the entity name of the prop bound to this button.
| The scalar product of two vectors.  
|-
|-
| <code>Length</code>
| <kbd>SetProgressBarText</kbd> || <kbd>void SetProgressBarText(string ''text'')</kbd>
| <code>float Length()</code>
|Sets the use text for the button UI.
| Magnitude of the vector.
|-
|-
| <code>LengthSqr</code>
| <kbd>SetProgressBarSubText</kbd> || <kbd>void SetProgressBarText(string ''text'')</kbd>
| <code>float LengthSqr()</code>
|Sets the subtext below the progress bar for the button UI.
| The magnitude of the vector squared. Faster than the above method.
|-
|-
| <code>Length2D</code>
| <kbd>SetProgressBarFinishTime</kbd> || <kbd>void SetProgressBarFinishTime(float ''time'')</kbd>
| <code>float Length2D()</code>
|Sets the total time the button takes to use. If '0', no progress bar will be displayed.
| Returns the magnitude of the vector on the x-y plane.
|-
|-
| <code>Length2DSqr</code>
| <kbd>SetProgressBarCurrentProgress</kbd> || <kbd>void SetProgressBarCurrentProgress(float ''time'')</kbd>
| <code>float Length2DSqr()</code>
|Sets the current use progress. It can be used to save the use progress when the user releases the use key.
| Returns the square of the magnitude of the vector on the x-y plane. Faster than the above method.
|-
|-
| <code>Norm</code>
| <kbd>StopUse</kbd> || <kbd>void StopUse()</kbd>
| <code>float Norm()</code>
|Stop the current use action.
| 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.
|-
| <code>tostring</code>
| <code>string tostring()</code>
| Returns a human readable string.
|}
|}




==== 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<kbd>{{↑|CBaseEntity}}::GetEntityHandle()</kbd>method.
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Instance
! Instance !! Type !! Description
! Type
! Description
|-
|-
| <code>x</code>
| <kbd>UseModelEntity</kbd> || <kbd><nowiki>[C++] CHandle<CBaseEntity></nowiki></kbd>
| <code>float</code>
| The Use Model prop associated with this entity.
| Cartesian X axis.
|-
| <code>y</code>
| <code>float</code>
| Cartesian Y axis.
|-
|-
| <code>z</code>
| <kbd>PlayerUsingMe</kbd> || <kbd><nowiki>[C++] CHandle<CBaseEntity></nowiki></kbd>
| <code>float</code>
| The current using player. {{todo|Recheck on this old info: Is it not 0 / null if not being used?}}.
| Cartesian Z axis.
|}
|}


 
==== Hooks ====
=== Vector2D, Vector4D ===
These VScript methods are called on the script set in the '''Entity Scripts''' keyvalue for the [[point_script_use_target]].
Two and four-dimensional equivalents to Vector.
{| class=standard-table
 
! Function !! Signature !! Description
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function
! Signature
! Description
|-
|-
| <code>constructor</code>
| <kbd>OnUseFinished</kbd> || <kbd>void OnUseFinished()</kbd>
| <code>Vector''X''D(float ''x'', float ''y'', ...)</code>
| Called when the player has used this button for at least 'FinishTime' seconds.
| Creates a new vector with the specified Cartesian coordiantes.
|-
|-
| <code>Dot</code>
| <kbd>OnUseStart</kbd> || <kbd>bool OnUseStart()</kbd>
| <code>float Dot(Vector''X''D ''factor'')</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.
| The scalar product of two vectors.
|-
|-
| <code>Length</code>
| <kbd>OnUseStop</kbd> || <kbd>void OnUseStop(float ''timeUsed'')</kbd>
| <code>float Length()</code>
|Called when the player stops using this button. Passes the time this button has been used (time between StartUse and now).
| Magnitude of the vector.
|-
|-
| <code>LengthSqr</code>
| <kbd>Precache</kbd> || <kbd>void Precache()</kbd>
| <code>float LengthSqr()</code>
|Called by the game engine when the entity first spawns, immediately after this script is run.
| The magnitude of the vector squared. Faster than the above method.
|-
|-
| <code>Norm</code>
| <code>float Norm()</code>
| Seems to also return the vector length.
|-
| <code>ToKVString</code>
| <code>string ToKVString()</code>
| Returns a string without separations commas.
|}
|}


== Scripted Mode ==
=== Decider ===
Enabling Scripted Mode makes a lot of features available in the <code>g_ModeScript</code> scope.
{{↑|toc}}
 
''An isolated instance of a rulescript database.''
=== sm_utilities.nut ===
Available in the <code>g_ModeScript</code> scope, always loaded in.
 
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.


==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
|-
! Description
| <kbd>constructor</kbd> ||
|
|-
|-
| <code>DeepPrintTable</code>
| <kbd>AddRule</kbd> || <kbd>bool AddRule(handle ''CRule'')</kbd>
| <code>void DeepPrintTable(handle ''table'', string ''prefix'' = "")</code>
| Add a CRule object (defined in rulescript_base.nut)  
| Print out a table (and subtables) to the console. This works with classes as well (not instances).
|-
|-
| <code>DuplicateTable</code>
| <kbd>FindAllMatches</kbd> || <kbd>handle FindAllMatches(handle ''query'', float ''leeway'')</kbd>
| <code>table DuplicateTable(table ''source'')</code>
| Returns an array of all matching responses. If leeway is nonzero, all results scoring within 'leeway' of the best score return.
| This returns a deep copy of the passed in table.
|-
|-
| <code>InjectTable</code>
| <kbd>FindBestMatch</kbd> || <kbd>handle FindBestMatch(handle ''query'')</kbd>
| <code>void InjectTable(table ''override'', table ''base'')</code>
| Query the database and return the best result found. If multiple of equal score found, an arbitrary one returns.  
| Inject the override data into the base table - i.e. add any new ones, overwrite dupes.
|-
|-
| <code>TimeToDisplayString</code>
| <kbd>IsValid</kbd> || <kbd>bool IsValid()</kbd>
| <code>string TimeToDisplayString(float ''disp_time'')</code>
| Whether the object belongs to a valid entity(?).
| Convert a # of seconds to a displayable time string form m:ss
|}
|}




=== Hooks ===
=== regexp ===
These hook functions are only available in the <code>g_ModeScript</code> scope, in Scripted Mode, which is enabled for a game mode by adding a mode specific VScript (<''mode_name''>.nut). They are 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.
{{↑|toc}}
The built-in [http://squirrel-lang.org/doc/sqstdlib3.html#d0e2591 Squirrel class] for regular expressions.


==== AllowBash ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function !! Signature !! Description
|-
| <kbd>constructor</kbd> || <kbd>regexp()</kbd>
|
|-
| <kbd>capture</kbd> || <kbd> [table] capture(''str'', [''start''])</kbd>
| 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.
|-
| <kbd>match</kbd> || <kbd> bool match(''str'')</kbd>
| Returns a true if the regular expression matches the string str, otherwise returns false.
|-
| <kbd>search</kbd> || <kbd>table search(''str'', [''start''])</kbd>
| 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.
|-
| <kbd>subexpcount</kbd> ||
|
|}


<code>int AllowBash(handle ''basher'', handle ''bashee'')</code>: called whenever melee bash is used. Returns these values:


*ALLOW_BASH_ALL - normal melee behavior
=== CCallChainer ===
*ALLOW_BASH_NONE - do nothing at all
{{↑|toc}}
*ALLOW_BASH_PUSHONLY - applies physics push but deals no damage (including prevention of insta-kill ambush behavior)  
'''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 ====
{| class="standard-table" style="width: 100%;"
! Function !! Signature !! Description
|-
| <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.
|-
| <kbd>PostScriptExecute</kbd> || <kbd>void PostScriptExecute()</kbd>
| Search for all non-native functions with matching prefixes, then push them into the {{Code|chains}} table.
|-
| <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.
|}


==== AllowTakeDamage ====
==== Members ====
{| class="standard-table" style="width: 100%;"
! Instance !! Type !! Description
|-
| <kbd>chains</kbd> || <kbd>table</kbd>
| Contains names of unprefixed functions, each with an array of functions to call.
|-
| <kbd>prefix</kbd> || <kbd>string</kbd>
| Prefix that functions should have to be added into the {{Code|chains}} table. Set by the constructor.
|-
| <kbd>scope</kbd> || <kbd>table</kbd>
| If set, seek functions in this scope instead. Set by the constructor.
|}


<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="cpp">
=== CSimpleCallChainer ===
ScriptedDamageInfo <-
{{↑|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.
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 // how much damage done
DamageType = -1 // of what type
Location = Vector(0,0,0) // where
Weapon = null // by what - often Null (say if attacker was a common)
}
</source>


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 ).
This class is also used internally by these {{↑|CBaseEntity}} hooks: {{Code|Precache()}} and {{Code|OnPostSpawn()}}.


==== BotQuery ====
==== Methods ====
 
{| class="standard-table" style="width: 100%;"
<code>bool BotQuery(int ''queryflag'', handle ''entity'', bool ''defaultvalue'')</code>: Hook to control survivor bot behavior. Only one known flag is supported.
! Function !! Signature !! Description
* <code>BOT_QUERY_NOTARGET</code> - Fired when a bot wants to bash a prop. Returning <code>false</code> disallows the bashing.
|-
| <kbd>constructor</kbd> || <kbd>CSimpleCallChainer(string ''functionPrefix'', table ''scope'' = null, exactMatch = false)</kbd>
| 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.
|-
| <kbd>PostScriptExecute</kbd> || <kbd>void PostScriptExecute()</kbd>
| Begin searching for all non-native functions with matching prefixes, then push them into the {{Code|chain}} array.
|-
| <kbd>Call</kbd> || <kbd>bool Call(any ...)</kbd>
| Call all functions inside the {{Code|chain}} array with the given arguments.
|}


==== Members ====
{| class="standard-table" style="width: 100%;"
! Instance !! Type !! Description
|-
| <kbd>chain</kbd> || <kbd>array</kbd>
| 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.
|-
| <kbd>prefix</kbd> || <kbd>string</kbd>
| 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.
|}




==== CanPickupObject ====
=== LateBinder ===
{{↑|toc}}


<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.
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function !! Signature !! Description
|-
| <kbd>Begin</kbd> ||
|
|-
| <kbd>End</kbd> ||
|
|-
| <kbd>EstablishDelegation</kbd> ||
|
|-
| <kbd>HookRootMetamethod</kbd> ||
|
|-
| <kbd>UnhookRootMetamethod</kbd> ||
|
|-
| <kbd>RemoveDelegation</kbd> ||
|
|-
| <kbd>Resolve</kbd> ||
|
|}




 
==== Members ====
==== InterceptChat ====
 
<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 &lt;scripted_user_func argument&gt; 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 &lt;arg&gt; 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]] for more information.'''
 
 
== Global Functions ==
 
=== Printing and Drawing ===
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Instance !! Type !! Description
! Signature
! Description
|-
|-
| <code>[[List_of_L4D2_Script_Functions/ClientPrint | ClientPrint]]</code>
| <kbd>m_bindNamesStack</kbd> || <kbd>array</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.
|-
|-
| <code>DebugDrawBox</code>
| <kbd>m_fixupSet</kbd> || <kbd>array</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.
|-
|-
| <code>DebugDrawBoxAngles</code>
| <kbd>m_log</kbd> || <kbd>bool</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).
|-
|-
| <code>DebugDrawBoxDirection</code>
| <kbd>m_logIndent</kbd> || <kbd>int</kbd>
| <code>void DebugDrawBoxDirection(Vector ''center'', Vector ''min'', Vector ''max'', Vector ''forward'', Vector ''rgb'', float ''alpha'', float ''duration'')</code>
|  
| Draw a debug forward box.
|-
|-
| <code>DebugDrawCircle</code>
| <kbd>m_targetTable</kbd> || <kbd>table?(null)</kbd>
| <code>void DebugDrawCircle(Vector ''center'', Vector ''rgb'', float ''alpha'', float ''radius'', bool ''ztest'', float ''duration'')</code>
|  
| Draw a debug circle.
|-
|-
| <code>DebugDrawClear</code>
|}
| <code>void DebugDrawClear()</code>
 
| Try to clear all the debug overlay info.
== 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 ====
{| class="standard-table" style="width: 100%;"
! Function !! Signature !! Description
|-
|-
| <code>DebugDrawLine</code>
| <kbd>constructor</kbd> || <kbd>Vector(float ''x'' = 0, float ''y'' = 0, float ''z'' = 0)</kbd>
| <code>void DebugDrawLine(Vector ''start'', Vector ''end'', int ''red'', int ''green'', int ''blue', bool ''zTest'', float ''time'')</code>
| Creates a new vector with the specified Cartesian coordiantes.
| Draw a debug overlay line.
|-
|-
| <code>DebugDrawLine_vCol</code>
| <kbd>Cross</kbd> || <kbd>float Cross(Vector ''factor'')</kbd>
| <code>void DebugDrawLine_vCol(Vector ''start'', vector ''end'', vector ''rgb'', bool ''ztest'', float ''duration'')</code>
| The vector product of two vectors. Returns a vector orthogonal to the input vectors.
| Draw a debug line using color vec.
|-
|-
| <code>DebugDrawScreenTextLine</code>
| <kbd>Dot</kbd> || <kbd>float Dot(Vector ''factor'')</kbd>
| <code>void DebugDrawScreenTextLine(float ''x'', float ''y'', int ''lineOffset'', string ''text'', int ''r'', int ''g'', int ''b'', int ''a'', float ''duration'')</code>
| The scalar product of two vectors.  
| Draw text with a line offset.
|-
|-
| <code>DebugDrawText</code>
| <kbd>Length</kbd> || <kbd>float Length()</kbd>
| <code>void DebugDrawText(Vector ''origin'', string ''text'', bool ''useViewCheck'', float ''duration'')</code>
| Magnitude of the vector.
| Draw text on the screen, starting on the position of ''origin''.
|-
|-
| <code>__DumpScope</code>
| <kbd>LengthSqr</kbd> || <kbd>float LengthSqr()</kbd>
| <code>void __DumpScope(int ''indentation'', handle ''scope'')</code>
| The magnitude of the vector squared. Faster than the above method.
| Dumps contents of everything in the scope.
|-
|-
| <code>DumpObject</code>
| <kbd>Length2D</kbd> || <kbd>float Length2D()</kbd>
| <code>void DumpObject(handle ''object'')</code>
| Returns the magnitude of the vector on the x-y plane. Meant to be used when working with the client's HUD.
| Dumps information about a class or instance.
|-
|-
| <code>HUDManageTimers</code>
| <kbd>Length2DSqr</kbd> || <kbd>float Length2DSqr()</kbd>
| <code>void HUDManageTimers(int ''timerID'', int ''command'', float ''value'')</code>
| Returns the square of the magnitude of the vector on the x-y plane. Faster than the above method.
| Manages the HUD timers. Valid command enumerations are: TIMER_DISABLE, TIMER_COUNTUP, TIMER_COUNTDOWN, TIMER_STOP, TIMER_SET
|-
|-
| <code>HUDPlace</code>
| <kbd>Norm</kbd> || <kbd>float Norm()</kbd>
| <code>void HUDPlace(int ''slot'', float ''x'', float ''y'', float ''width'', float ''height'')</code>
| Seems to also return the vector length.
| Sets the position of a HUD element. See [[L4D2_EMS/Appendix:_HUD]]
|-
|-
| <code>HUDReadTimer</code>
| <kbd>Scale</kbd> || <kbd>Vector Scale(float ''factor'')</kbd>
| <code>float HUDReadTimer(int ''timerID'')</code>
| Scales the vector magnitude.
| Returns the value of a HUD timer. See [[L4D2_EMS/Appendix:_HUD]]
|-
|-
| <code>HUDSetLayout</code>
| <kbd>ToKVString</kbd> || <kbd>string ToKVString()</kbd>
| <code>void HUDSetLayout(table ''HUDTable'')</code>
| Returns a string without separations commas. {{note|Not required for the {{code|SpawnEntityWithTable}} function, as it understands the Vector data type.}}
| Applies a HUD to the screen. See [[L4D2_EMS/Appendix:_HUD]]
|-
|-
| <code>Msg</code>
| <kbd>tostring</kbd> || <kbd>string tostring()</kbd>
| <code>void Msg(string ''message'')</code>
| Returns a human readable string.
| Prints message to console without any line feed after.
|}
 
==== Members ====
{| class="standard-table" style="width: 100%;"
! Instance !! Type !! Description
|-
|-
| <code>print</code>
| <kbd>x</kbd> || <kbd>float</kbd>
| <code>void print(string ''message'')</code>
| Cartesian X axis.
| Prints message to console without any line feed after.
|-
|-
| <code>printl</code>
| <kbd>y</kbd> || <kbd>float</kbd>
| <code>void printl(string ''message'')</code>
| Cartesian Y axis.
| Prints message to console with a line feed after.
|-
|-
| <code>realPrint</code>
| <kbd>z</kbd> || <kbd>float</kbd>
| <code>void realPrint(string ''message'')</code>
| Cartesian Z axis.
| Identical to print. print seems to be a wrapper for this.
|}
|-
 
| <code>ShowMessage</code>
==== Operations ====
| <code>void ShowMessage(string ''message'')</code>
{| class="standard-table" style="width:100%"
| Print a HUD message on all clients. {{bug|Non-functional.}}
|- style="position:sticky; z-index:10; top:0"
! Operation !! Return Type !! Description
|-
|-
| <code>Say</code>
| <kbd>Vector + Vector</kbd> || <kbd>Vector</kbd>
| <code>void Say(CTerrorPlayer ''player'', string ''message'', bool ''teamOnly'') </code>
| Returns the sum of both classes's members (XYZ).
| Calling this will have the specified player send the message to chat, either to teamOnly (true) or to everyone.  
|-
|-
| <code>SendToConsole</code>
| <kbd>Vector - Vector</kbd> || <kbd>Vector</kbd>
| <code>void SendToConsole(string ''command'')</code>
| Returns the subtraction of both classes's members (XYZ).
| Send a string to the console as a command.
|-
|-
| <code>SendToServerConsole</code>
| <kbd>Vector * int</kbd> || rowspan="2"| <kbd>Vector</kbd>
| <code>void SendToServerConsole(string ''command'')</code>
|rowspan="2"| Returns the multiplication of a Vector against a scalar.
| 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.
|-
|-
| <kbd>Vector * float</kbd>
|}
|}


=== Entity Manipulation ===
=== QAngle ===
{| class="standard-table" style="width: 100%;"
{{↑|toc}}
! Function
Squirrel equivalent of the C++ [[QAngle]] class. Represents a three-dimensional orientation as Euler angles.
! Signature
 
! Description
Has overloaded arithmetic operations with both QAngles and scalar values.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function !! Signature !! Description
|-
|-
| <code>AddThinkToEnt</code>
| <kbd>constructor</kbd> || <kbd>QAngle(float ''pitch'' = 0, float ''yaw'' = 0, float ''roll'' = 0)</kbd>
| <code>void AddThinkToEnt(handle ''entity'', string ''FuncName'')</code>
| Creates a new QAngle.
| This will put a think function onto an entity, or pass null to remove it. This is NOT chained, so be careful.
|-
|-
| <code>[[List_of_L4D2_Script_Functions/CommandABot| CommandABot]]</code>
| <kbd>Forward </kbd> || <kbd>Vector Forward()</kbd>
| <code>bool CommandABot(table ''commandTable'')</code>
| Returns the Forward Vector of the angles.  
| Issues commands to bots based on a table configuration.  
|-
|-
| <code>ConnectOutputs</code>
| <kbd>Left</kbd> || <kbd>Vector Left()</kbd>
| <code>void ConnectOutputs(table)</code>
| Returns the left Vector of the angles. {{bug*|Returns right Vector instead}}
| sets output functions for entity by table {{todo}}
|-
|-
| <code>DoEntFire</code>
| <kbd>Pitch</kbd> || <kbd>float Pitch()</kbd>
| <code>void DoEntFire(string ''target'', string ''action'', string ''value'', float ''delay'', handle ''activator'', handle ''caller'')</code>
| Returns the pitch angle in degrees.
| Generate an entity I/O event. The ''caller'' argument takes a script handle, so it can be used with ''target'' set to ''!self'' to fire inputs to entities without usable targetnames.
|-
|-
| <code>EntFire</code>
| <kbd>Roll</kbd> || <kbd>float Roll()</kbd>
| <code>void EntFire(string ''target'', string ''action'', string ''value = null'', float ''delay = 0'', handle ''activator = null'')</code>
| Returns the roll angle in degrees.
| Wrapper for DoEntFire() that sets activator and caller to null.  
|-
|-
| <code>DropFire</code>
| <kbd>ToKVString</kbd> || <kbd>string ToKVString()</kbd>
| <code>void DropFire(Vector ''location'')</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.}}
| Drop a fire pool from the specified Vector location.
|-
|-
| <code>DropSpit</code>
| <kbd>ToQuat</kbd> || <kbd>Quaternion ToQuat()</kbd>
| <code>void DropSpit(Vector ''location'')</code>
| Returns a quaternion representaion of the orientation.
| Drop a spit pool from the specified Vector location.
|-
|-
| <code>EmitAmbientSoundOn</code>
| <kbd>Up</kbd> || <kbd>Vector Up()</kbd>
| <code>void EmitAmbientSoundOn(string ''soundName'', float ''volume'', int ''soundlevel'', int ''pitch'', handle ''entity'')</code>
| Returns the Up Vector of the angles.
| Play named ambient sound on an entity.
|-
|-
| <code>StopAmbientSoundOn</code>
| <kbd>Yaw</kbd> || <kbd>float Yaw()</kbd>
| <code>void StopAmbientSoundOn(string ''soundName'', handle ''entity'')</code>
| Returns the yaw angle in degrees.
| Stop named ambient sound on an entity.
|}
 
==== Members ====
{| class="standard-table" style="width: 100%;"
! Instance !! Type !! Description
|-
|-
| <code>EmitSoundOnClient</code>
| <kbd>x</kbd> || <kbd>float</kbd>
| <code>void EmitSoundOnClient(string ''soundScript'', handle ''player'')</code>
| Pitch in degrees.
| Play named sound only on the client for the specified player.
|-
|-
| <code>EmitSoundOn</code>
| <kbd>y</kbd> || <kbd>float</kbd>
| <code>void EmitSoundOn(string ''soundScript'', handle ''entity'')</code>
| Yaw in degrees.
| Play named sound on an entity.
|-
|-
| <code>StopSoundOn</code>
| <kbd>z</kbd> || <kbd>float</kbd>
| <code>void StopSoundOn(string ''soundScript'', handle ''entity'')</code>
| Roll in degrees.
| Stop named sound on an entity.
|}
 
==== Operations ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Operation !! Return Type !! Description
|-
|-
| <code>EntIndexToHScript</code>
| <kbd>QAngle + QAngle</kbd> || <kbd>QAngle</kbd>
| <code>CBaseEntity EntIndexToHScript(int ''entIndex'')</code>
| Sum of both classes's members (XYZ).  
| Returns the script handle for the given entity index.
|-
|-
| <code>GetListenServerHost</code>
| <kbd>QAngle - QAngle</kbd> || <kbd>QAngle</kbd>
| <code>handle GetListenServerHost()</code>
| Subtraction of both classes's members (XYZ).
| Get the host player on a listen server.
|-
|-
| <code>GetFriction</code>
| <kbd>QAngle * int</kbd> || rowspan="2"| <kbd>QAngle</kbd>
| <code>float GetFriction(CTerrorPlayer ''player'')</code>
|rowspan="2"| QAngle multiplied by a number.
| Returns the Friction on a player entity, meaningless if not a player.
|-
|-
| <code>[[List_of_L4D2_Script_Functions/GetInvTable| GetInvTable]]</code>
| <kbd>QAngle * float</kbd>
| <code>void GetInvTable(CTerrorPLayer ''player'',table ''invTable'')</code>
|}
| Fills ''invTable'' with the specified player's inventory.
 
=== Vector2D, Vector4D ===
{{↑|toc}}
Two and four-dimensional equivalents of the Vector data type. Has the same overloaded operators.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function !! Signature !! Description
|-
|-
| <code>GetPhysVelocity</code>
| <kbd>constructor</kbd> || <kbd>Vector2D(float ''x'' = 0, float ''y'' = 0)</kbd>
| <code>Vector GetPhysVelocity(handle ''entity'')</code>
| Creates a new 2D vector with the specified Cartesian coordinates.
| Returns the velocity of the entity.
|-
|-
| <code>GetPhysAngularVelocity</code>
| <kbd>constructor</kbd> || <kbd>Vector4D(float ''x'' = 0, float ''y'' = 0, float ''z'' = 0, float ''w'' = 0)</kbd>
| <code>Vector GetPhysAngularVelocity(handle ''entity'')</code>
| Creates a new 4D vector with the given coordinate numbers.
| Returns the Angular velocity of the entity.
|-
|-
| <code>GetPlayerFromCharacter</code>
| <kbd>Dot</kbd> || <kbd>float Dot(Vector''X''D ''factor'')</kbd>
| <code>handle GetPlayerFromCharacter(int ''characterType'')</code>
| The scalar product of two vectors.
| Given a character type, return the entity, or null.
|-
|-
| <code>GetPlayerFromUserID</code>
| <kbd>Length</kbd> || <kbd>float Length()</kbd>
| <code>handle GetPlayerFromUserID(int ''ID'')</code>
| Magnitude of the vector.
| Given a user id, return the entity, or null.
|-
|-
| <code>IsPlayerABot</code>
| <kbd>LengthSqr</kbd> || <kbd>float LengthSqr()</kbd>
| <code>bool IsPlayerABot(handle ''player'')</code>
| The magnitude of the vector squared. Faster than the above method.
| Is this player/entity a bot.
|-
|-
| <code>PickupObject</code>
| <kbd>Norm</kbd> || <kbd>float Norm()</kbd>
| <code>void PickupObject(handle ''player'', handle ''entity'')</code>
| Seems to also return the vector length.
| 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>ToKVString</kbd> || <kbd>string ToKVString()</kbd>
| <code>CTerrorPlayer PlayerInstanceFromIndex(int ''index'')</code>
| Returns a string without separations commas.
| Get a script handle of a player using the player index.
|}
 
==== Members ====
{| class="standard-table" style="width: 100%;"
! Instance !! Type !! Description
|-
|-
| <code>PrecacheEntityFromTable</code>
| <kbd>x</kbd> || <kbd>float</kbd>
| <code>bool PrecacheEntityFromTable(table ''keyvalues'')</code>
| Cartesian X axis.
| Precache an entity from [[KeyValues]] in a table.
|-
|-
| <code>RotateOrientation</code>
| <kbd>y</kbd> || <kbd>float</kbd>
| <code>QAngle RotateOrientation(QAngle, QAngle)</code>
| Cartesian Y axis.
| Rotate a QAngle by another QAngle.
|-
|-
| <code>RotatePosition</code>
| <kbd>z</kbd> || <kbd>float</kbd>
| <code>Vector RotatePosition(Vector ''origin'', QAngle ''rotation'', Vector ''input'')</code>
| Cartesian Z axis. Vector4D only.
| Rotate the input Vector around an origin.
|-
|-
| <code>SetFakeClientConVarValue</code>
| <kbd>w</kbd> || <kbd>float</kbd>
| <code>void SetFakeClientConVarValue(handle ''bot'', string ''cvar'', string ''value'')</code>
| Component for possibly creating homogeneous coordinates? Vector4D only.
| Sets a USERINFO client ConVar for a fakeclient.
|}
 
==== Operations ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Operation !! Return Type !! Description
|-
|-
| <code>SpawnEntityFromTable</code>
| <kbd>Vector2D + Vector2D</kbd><br><kbd>Vector4D + Vector4D</kbd> || <kbd>Vector2D</kbd><br><kbd>Vector4D</kbd>
| <code>handle SpawnEntityFromTable(string ''name'', handle ''keyvalues'')</code>
| Returns the sum of both classes's members (XYZ).
| Native function for entity spawning. See [[L4D2_EMS/Appendix:_Spawning]].
|-
| <code>SpawnEntityGroupFromTable</code>
| <code>bool SpawnEntityGroupFromTable(handle ''entityGroup'')</code>
| Native function for entity group spawning. See [[L4D2_EMS/Appendix:_Spawning]].
|-
|-
| <code>SpawnStartBox</code>
| <kbd>Vector2D - Vector2D</kbd><br><kbd>Vector4D - Vector4D</kbd> || <kbd>Vector2D</kbd><br><kbd>Vector4D</kbd>
| <code>handle SpawnStartBox(''centerobjname'', ''useFloating'', ''width'', ''depth'', ''barriermodel'', ''min_gap'')</code>
| Returns the subtraction of both classes's members (XYZ).
| Auto-create a startbox that will give you a callback when the first player exits it.
|-
|-
| <code>TeleportPlayersToStartPoints</code>
| <kbd>Vector2D * int</kbd><br><kbd>Vector4D * int</kbd> || rowspan="2"| <kbd>Vector2D</kbd><br><kbd>Vector4D</kbd>
| <code>void TeleportPlayersToStartPoints(string ''spawnpointName'')</code>
|rowspan="2"| Returns the multiplication of the given Vector variant against a scalar.
| Teleport players to start entities named by the argument - must have 4 spawnpoints.
|-
|-
| <code>[[List_of_L4D2_Script_Functions/ZSpawn| ZSpawn]]</code>
| <kbd>Vector2D * float</kbd><br><kbd>Vector4D * float</kbd>
| <code>bool ZSpawn(table ''spawnTable'')</code>
| Spawn a zombie.
|}
|}


=== Other ===
=== Quaternion ===
{{↑|toc}}
A [http://en.wikipedia.org/wiki/Quaternion Quaternion] represents rotations in three-dimensional space.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>AddToScriptHelp</code>
| <kbd>constructor</kbd> || <kbd>Quaternion()</kbd>
|  
| Creates a new identity quaternion.
|  
|-
|-
| <code>Assert</code>
| <kbd>constructor</kbd> || <kbd>Quaternion(float ''x'' = 0,float ''y'' = 0,float ''z'' = 0,float ''w'' = 0)</kbd>
| <code>void Assert(bool ''value'', string ''optional message'')</code>
| Creates a new quaternion of the form: <kbd>''w'' + ''x'''''i''' + ''y'''''j''' + ''z'''''k'''</kbd>.
| Test value and if not true, throws exception, optionally with message.
|-
|-
| <code>CheckForSpecialStage</code>
| <kbd>Dot</kbd> || <kbd>float Dot(Quaternion ''factor'')</kbd>
| <code>void CheckForSpecialStage(''level'', ''stage_list'', ''stage_info'')</code>
| The 4D scalar product of two quaternions. represents the angle between the quaternions in the range [1, 0].
| Helper for picking a random special stage based on stage_info table.
|-
|-
| <code>CheckOrSetMapCallback</code>
| <kbd>Invert</kbd> || <kbd>Quaternion Invert()</kbd>
| <code>void CheckOrSetMapCallback(''cb_name'', ''cb_default'')</code>
| Returns a quaternion with the complimentary rotation.
| Pass a callback and default @ for it, if it doesnt exist in current table, place it there.
|-
|-
| <code>ClearGameEventCallbacks</code>
| <kbd>Norm</kbd> || <kbd>Quaternion Norm()</kbd>
| <code>void ClearGameEventCallbacks()</code>
| Normalizes the 4D vector length. {{todo|What effect does this have in quaternions?}}
| Empties the tables of game event callback functions.
|-
|-
| <code>ClearSavedTables</code>
| <kbd>SetPitchYawRoll</kbd> || <kbd>void SetPitchYawRoll(float ''pitch'', float ''yaw'', float ''roll'')</kbd>
| <code>void ClearSavedTables()</code>
| Recomputes the quaternion from the supplied Euler angles.
| Removes any tables saved with <code>SaveTable()</code>.
|-
|-
| <code>developer</code>
| <kbd>ToKVString</kbd> || <kbd>string ToKVString()</kbd>
| <code>bool developer()</code>
| Returns a string with the values separated by one space.
| If developer mode is on.
|-
|-
| <code>Document</code>
| <kbd>ToQAngle</kbd> || <kbd>QAngle ToQAngle()</kbd>
| <code>void Document(unknown ''symbolOrTable'', unknown ''itemIfSymbol'' = null, string ''descriptionIfSymbol'' = null)</code>
| Returns the angles resulting from the rotation.
|  
|}
 
 
==== Members ====
{| class="standard-table" style="width: 100%;"
! Instance !! Type !! Description
|-
|-
| <code>DoIncludeScript</code>
| <kbd>x</kbd> || <kbd>float</kbd>
| <code>void DoIncludeScript(string ''file'', handle ''scope'')</code>
| Vector component along the '''i''' axis.
| Execute a script (internal)
|-
|-
| <code>DoUniqueString</code>
| <kbd>y</kbd> || <kbd>float</kbd>
| <code>string DoUniqueString(string ''input'')</code>
| Vector component along the '''j''' axis.
| Called by UniqueString, prob want to call that instead.
|-
|-
| <code>FileToString</code>
| <kbd>z</kbd> || <kbd>float</kbd>
| <code>string FileToString(string ''file'')</code>
| Vector component along the '''k''' axis.
| 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.  
|-
|-
| <code>FireGameEvent</code>
| <kbd>w</kbd> || <kbd>float</kbd>
| <code>string FireGameEvent(string ''event'', table ''params'')</code>
| Scalar part.
| Fire a game event to a listening callback function in script. Parameters are passed in a squirrel table.
|}
 
==== Operations ====
{| class="standard-table" style="width:100%"
! Operation !! Return Type !! Description
|-
|-
| <code>FireScriptEvent</code>
| <kbd>Quaternion + Quaternion</kbd> || <kbd>Quaternion</kbd>
| <code>void FireScriptEvent(event, params)</code>
| Sum of the two Quaternions.
| Wrapper for <code>__RunEventCallbacks()</code>
|-
|-
| <code>ForceScavengeStart</code>
| <kbd>Quaternion - Quaternion</kbd> || <kbd>Quaternion</kbd>
| <code>void ForceScavengeStart()</code>
| Subtraction of the two Quaternions.
| Starts the scavenge round, even if the setup timer hasn't elapsed.
|-
|-
| <code>ForceSurvivalStart</code>
| <kbd>Quaternion * int</kbd> || rowspan="2"| <kbd>Quaternion</kbd>
| <code>void ForceSurvivalStart()</code>
|rowspan="2"| Quaternion multiplied by a number.
| Starts the survival round, even if the survivors haven't activated the radio.
|-
|-
| <code>ForceVersusStart</code>
| <kbd>Quaternion * float</kbd>
| <code>void ForceVersusStart()</code>
|}
| Starts the versus round, even if the survivors haven't left the safe room.
 
== 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}}
 
Scripted Mode data are stored under the {{Code|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 [[L4D2_EMS/Appendix:_Functions|EMS tutorial]] for more examples. These functions are inside g_MapScript scope.
 
{| class="standard-table" style="width: 100%;"
! Function !! Signature !! Description
|-
|-
| <code>GetCharacterDisplayName</code>
| <kbd>CheckOrSetMapCallback</kbd> || <kbd>void CheckOrSetMapCallback(''cb_name'', ''cb_default'')</kbd>
| <code>string GetCharacterDisplayName(CTerrorPlayer ''player'')</code>
| Pass a callback and default @ for it, if it doesnt exist in current table, place it there.
| Return <code>null</code> if not a survivor, else the survivor characters name.
|-
|-
| <code>GetCurrentFlowDistanceForPlayer</code>
| <kbd>DeepPrintTable</kbd> || <kbd>void DeepPrintTable(handle ''table'', string ''prefix'' = "")</kbd>
| <code>float GetCurrentFlowDistanceForPlayer(CTerrorPlayer ''player'')</code>
| Print out a table (and subtables) to the console. This works with classes as well (not instances).
| Returns the navigation flow distance from the start to the specified player.
|-
|-
| <code>GetCurrentFlowPercentForPlayer</code>
| <kbd>DuplicateTable</kbd> || <kbd>table DuplicateTable(table ''source'')</kbd>
| <code>float GetCurrentFlowPercentForPlayer(CTerrorPlayer ''player'')</code>
| This returns a deep copy of the passed in table.
| Returns how far in the navigation flow from the start to the end the player is.
|-
|-
| <code>GetFlowDistanceForPosition</code>
| <kbd>InjectTable</kbd> || <kbd>void InjectTable(table ''override'', table ''base'')</kbd>
| <code>float GetFlowDistanceForPosition(Vector ''position'')</code>
| Inject the override data into the base table - i.e. add any new ones, overwrite dupes.
| Returns the navigation flow distance from the start to the specified point.
|-
|-
| <code>GetFlowPercentForPosition</code>
| <kbd>SpawnStartBox</kbd> || <kbd>handle SpawnStartBox(''centerobjname'', ''useFloating'', ''width'', ''depth'', ''barriermodel'', ''min_gap'')</kbd>
| <code>float GetCurrentFlowPercentForPosition(Vector ''position'', bool ''unknown'')</code>
| Auto-create a startbox that will give you a callback when the first player exits it.
| Returns how far in the navigation flow from the start to the end the position is.
|-
|-
| <code>GetMaxFlowDistance</code>
| <kbd>TeleportPlayersToStartPoints</kbd> || <kbd>void TeleportPlayersToStartPoints(string ''spawnpointName'')</kbd>
| <code>float GetMaxFlowDistance()</code>
| Teleport players to start entities named by the argument - must have 4 spawnpoints.
| Returns the navigation flow distance from the start to the end of the level.
|-
|-
| <code>GetAverageSurvivorFlowDistance</code>
| <kbd>Ticker_AddToHud</kbd> || <kbd>void Ticker_AddToHud(table ''hudTable'', string ''strInit'', bool ''blink'')</kbd>
| <code>float GetAverageSurvivorFlowDistance()</code>
| Adds ticker data to a passed in HUDTable.
| Returns the navigation flow distance from the start to the survivors position averaged.
|-
|-
| <code>GetFrameCount</code>
| <kbd>Ticker_NewStr</kbd> || <kbd>void Ticker_NewStr(string ''newStr'', float ''newTimeout'')</kbd>
| <code>void GetFrameCount()</code>
| Sets the current Ticker string, w/an optional timeout value.
| Returns the engine's current frame count.
|-
|-
| <code>GetFunctionSignature</code>
| <kbd>TimeToDisplayString</kbd> || <kbd>string TimeToDisplayString(float ''disp_time'')</kbd>
|  
| Convert a # of seconds to a displayable time string form m:ss
|  
|-
|-
| <code>GetInfectedStats</code>
|}
| <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.
 
|-
=== Hooks ===
| <code>GetSoundDuration</code>
{{↑|toc}}
| <code>float GetSoundDuration(string ''soundname'', string ''actormodel'')</code>
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.
| Returns float duration of the sound. Takes soundname and optional actormodelname.
{{todo|Everything to know about OnGamePlayStart and OnActivate.}}
|-
 
| <code>HasPlayerControlledZombies</code>
==== OnShutdown ====
| <code>bool HasPlayerControlledZombies()</code>
<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:
| Returns true if the current mode supports player controlled zombies.
 
|-
<source lang="JavaScript">
| <code>IncludeScript</code>
function OnShutdown()
| <code>void IncludeScript(string ''file'', handle ''scope'' = null)</code>
{
| Wrapper for DoIncludeScript
local reason = SessionState.ShutdownReason
|-
local nextmap = SessionState.NextMap
| <code>IsDedicatedServer</code>
 
| <code>bool IsDedicatedServer()</code>
printl("Mutation shut down under reason " + reason.tostring() + ", next map is " + nextmap)
| Returns true if this is a dedicated server.
}
|-
</source>
| <code>IsModelPrecached</code>
 
| <code>bool IsModelPrecached(string ''modelname'')</code>
==== OnActivate ====
| Checks if the modelname is precached.
<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())"
|-
 
| <code>IsSoundPrecached</code>
==== OnGameplayStart ====
| <code>bool IsSoundPrecached(string ''soundname'')</code>
<kbd>void OnGameplayStart()</kbd>: Called whenever the gameplay starts.
| Checks if the soundname is precached.
 
|-
==== AllowBash ====
| <code>IsWeakref</code>
<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
| <code>LocalTime</code>
*ALLOW_BASH_PUSHONLY - applies physics push but deals no damage (including prevention of insta-kill ambush behavior)  
| <code>void LocalTime(table)</code>
 
| Fills out a table with the local time (second, minute, hour, day, month, year, dayofweek, dayofyear, daylightsavings).
==== 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.
| <code>MakeNamespace</code>
 
|
<source lang="JavaScript">
|
ScriptedDamageInfo <-
|-
{
| <code>PrecacheModel</code>
Attacker = null // hscript of the entity that attacked
| <code>void PrecacheModel(string ''filename'')</code>
Victim = null // hscript of the entity that was hit
| Precache a model.
Inflictor = null // hscript of the entity that was the inflictor
|-
DamageDone = 0 // copyback variable for how much damage done
| <code>PrecacheSound</code>
DamageType = -1 // copyback variable for what type of damage
| <code>void PrecacheSound(string ''soundName'')</code>
Location = Vector(0,0,0) // where
| Precache a sound.
Weapon = null // by what - often Null (say if attacker was a common)
|-
}
| <code>QueueSpeak</code>
</source>  
| <code>void QueueSpeak(handle ''entity'', string ''concept'', float ''delay'', string ''criteria'')</code>
 
| Queue a speech concept.
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:
| <code>RandomFloat</code>
1. Falling from a slope that gives immunity to fall damage ( Dark Carnival First Chapter )
| <code>float RandomFloat()</code>
 
| Generate a random floating point number.
2. A tank rock hits you after a smoker grabbed you.
|-
 
| <code>RandomFloat</code>
==== BotQuery ====
| <code>float RandomFloat(float ''min'', float ''max'')</code>
<kbd>bool BotQuery(int ''queryflag'', handle ''entity'', bool ''defaultvalue'')</kbd>: Hook to control survivor bot behavior. Only one known flag is supported.
| Generate a random floating point number within a range, inclusive.
* <kbd>BOT_QUERY_NOTARGET</kbd> - Fired when a bot wants to bash a prop. Returning {{Code|false}} disallows the bashing.
|-
 
| <code>RandomInt</code>
==== CanPickupObject ====
| <code>int RandomInt()</code>
<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.
| Generate a random integer.
 
|-
==== InterceptChat ====
| <code>RandomInt</code>
<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.
| <code>int RandomInt(int ''min'', int ''max'')</code>
 
| Generate a random integer within a range, inclusive.
==== 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.
 
==== 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>
'''See [[L4D2_EMS/Appendix:_Game_Events|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|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.}}
 
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
|-
| <code>ReapplyInfectedFlags</code>
| <kbd>__DumpScope</kbd> || <kbd>void __DumpScope(int ''indentation'', table ''scope'')</kbd>
| <code>ReapplyInfectedFlags(int ''flags'', handle ''infected'')</code>
| Dumps a scope's contents and expands all tables and arrays; this is what the <kbd>ent_script_dump</kbd> command uses.
| Apply Infected Flags from DirectorOptions. Applies to all common (spawned and unspawned) unless a handle to a specific infected is specified.  
{{tip|You can use this to print tables/arrays.}}
|-
{{Expand|title=Example|
| <code>RegisterFunctionDocumentation</code>
Using this code:
| <code>void RegisterFunctionDocumentation(unknown ''func'', string ''name'', string ''signature'', string ''description'')</code>
<source lang=js>
|
local testTable =
|-
{
| <code>RegisterScriptGameEventListener</code>
integer = 20,
| <code>void RegisterScriptGameEventListener(string ''eventName'')</code>
string = "hello",
| 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.
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>ReloadMOTD</code>
| <kbd>[[/ClientPrint|ClientPrint]]</kbd> || <kbd>void ClientPrint(CTerrorPlayer ''player'', int ''destination'', string ''message'')</kbd>
| <code>void ReloadMOTD()</code>
| Print a client message. If you pass null instead of a valid player, the message will be sent to all clients.
| Reloads the MotD file.
|-
|-
| <code>RestoreTable</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 RestoreTable(string ''identifier'', table)</code>
| Draw a debug overlay box.
| See [[L4D2_EMS/Appendix:_Table_Save_Restore]].
|-
|-
| <code>RetrieveNativeSignature</code>
| <kbd>DebugDrawBoxAngles</kbd> || <kbd>void DebugDrawBoxAngles(Vector ''origin'', Vector ''min'', Vector ''max'', QAngle ''direction'', Vector ''rgb'', int ''alpha'', float ''duration'')</kbd>
| <code>unknown RetrieveNativeSignature(string ''nativeFunction'')</code>
| Draw a debug oriented box (cent, min, max, angles(p,y,r), vRgb, a, duration).
|  
|-
|-
| <code>rr_AddDecisionRule</code>
| <kbd>DebugDrawBoxDirection</kbd> || <kbd>void DebugDrawBoxDirection(Vector ''center'', Vector ''min'', Vector ''max'', Vector ''forward'', Vector ''rgb'', float ''alpha'', float ''duration'')</kbd>
| <code>bool rr_AddDecisionRule(RRule ''rule'')</code>
| Draw a debug forward box.
| Add a rule to the decision database. Takes a RRule object from rulescript_base.nut.
|-
|-
| <code>rr_CommitAIResponse</code>
| <kbd>DebugDrawCircle</kbd> || <kbd>void DebugDrawCircle(Vector ''center'', Vector ''rgb'', float ''alpha'', float ''radius'', bool ''ztest'', float ''duration'')</kbd>
| <code>bool rr_CommitAIResponse(handle ''entity'', table ''airesponse'')</code>
| Draw a debug circle.
| 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>DebugDrawClear</kbd> || <kbd>void DebugDrawClear()</kbd>
| <code>table rr_GetResponseTargets()</code>
| Try to clear all the debug overlay info.
| Retrieve a table of all available expresser targets, in the form { name : handle, name: handle }.
|-
|-
| <code>rr_QueryBestResponse</code>
| <kbd>DebugDrawLine</kbd> || <kbd>void DebugDrawLine(Vector ''start'', Vector ''end'', int ''red'', int ''green'', int ''blue', bool ''zTest'', float ''time'')</kbd>
| <code>unknown rr_QueryBestResponse(handle ''entity'', table ''query'')</code>
| Draw a debug overlay line.
| 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>DebugDrawLine_vCol</kbd> || <kbd>void DebugDrawLine_vCol(Vector ''start'', vector ''end'', vector ''rgb'', bool ''ztest'', float ''duration'')</kbd>
| <code>void RushVictim(handle ''hVictim'', float ''range'')</code>
| Draw a debug line using color vec.
| Make all common zombies in range rush the victim. (If hVictim isn't set, a random survivor will be chosen.)
|-
|-
| <code>SaveTable</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 SaveTable(string ''identifier'', table)</code>
| Draw text with a line offset.
| See [[L4D2_EMS/Appendix:_Table_Save_Restore]].
|-
|-
| <code>ScreenFade</code>
| <kbd>DebugDrawText</kbd> || <kbd>void DebugDrawText(Vector ''origin'', string ''text'', bool ''useViewCheck'', float ''duration'')</kbd>
| <code>void ScreenFade(handle ''player'', int ''red'', int ''green'', int ''blue'', int ''alpha'', float ''fadeTime'', float ''fadeHold'', int ''flags'')</code>
| Draw text on the screen, starting on the position of ''origin''.
| Start a screenfade with the following parameters.
|-
|-
| <code>ScreenShake</code>
| <kbd>DumpObject</kbd> || <kbd>void DumpObject(handle ''object'')</kbd>
| <code>void ScreenShake(Vector ''vecCenter'', float ''flAmplitude'', float ''flFrequency'', float ''flDuration'', float ''flRadius'', int ''eCommand'', bool ''bAirShake'')</code>
| Dumps information about a class or instance.
| Start a screenshake with the following parameters.
|-
|-
| <code>StageInfo_Execute</code>
| <kbd>HUDManageTimers</kbd> || <kbd>void HUDManageTimers(int ''timerID'', int ''command'', float ''value'')</kbd>
| <code>void StageInfo_Execute(''stageInfo'', ''stageDefaults'')</code>
| Manages the HUD timers. Valid command enumerations are: TIMER_DISABLE, TIMER_COUNTUP, TIMER_COUNTDOWN, TIMER_STOP, TIMER_SET
| Execute a stage table, i.e. move parameters to DirectorOptions, do callbacks and so on.
|-
| <kbd>HUDPlace</kbd> || <kbd>void HUDPlace(int ''slot'', float ''x'', float ''y'', float ''width'', float ''height'')</kbd>
| Sets the position of a HUD element. See [[L4D2_EMS/Appendix:_HUD]]
|-
|-
| <code>StartAssault</code>
| <kbd>HUDReadTimer</kbd> || <kbd>float HUDReadTimer(int ''timerID'')</kbd>
| <code>void StartAssault()</code>
| Returns the value of a HUD timer. See [[L4D2_EMS/Appendix:_HUD]]
| Tells all existing nextbots to swap into assault mode and not hide/dither/loiter.
|-
|-
| <code>StringToFile</code>
| <kbd>HUDSetLayout</kbd> || <kbd>void HUDSetLayout(table ''HUDTable'')</kbd>
| <code>void StringToFile(string ''file'', string ''string'')</code>
| Applies a HUD to the screen. See [[L4D2_EMS/Appendix:_HUD]] {{important|Scriptedmode feature, usable properly in mutations only}}
| Stores the string into the file.  
|-
|-
| <code>Time</code>
| <kbd>Msg</kbd> || <kbd>void Msg(string ''message'')</kbd>
| <code>float Time()</code>
| Prints message to console without any line feed after.
| Get the current server time.
|-
|-
| <code>[[List_of_L4D2_Script_Functions/TraceLine| TraceLine]]</code>
| <kbd>print</kbd> || <kbd>void print(string ''message'')</kbd>
| <code>bool TraceLine(table ''traceTable'')</code>
| Prints message to console without any line feed after. Identical to {{Code|Msg()}}.
| Uses a configuration table to do a raytrace, puts return information into the table for return usage.
|-
|-
| <code>UniqueString</code>
| <kbd>printl</kbd> || <kbd>void printl(string ''message'')</kbd>
| <code>string UniqueString(string ''input'')</code>
| Prints message to console with a line feed after.
| 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>realPrint</kbd> || <kbd>void realPrint(string ''message'')</kbd>
| <code>table VSquirrel_OnCreateScope(value, table ''scope'')</code>
| Identical to print. print seems to be a wrapper for this.
| Creates a new scope with the name of value in the submitted table (includes unique params).
|-
|-
| <code>VSquirrel_OnReleaseScope</code>
| <kbd>ShowMessage</kbd> || <kbd>void ShowMessage(string ''message'')</kbd>
| <code>void VSquirrel_OnReleaseScope(table ''createdScope'')</code>
| Print a HUD message on all clients. {{bug*|Non-functional.|only=l4d2}}
| Removes a scope created via VSquirrel_OnCreateScope.
|-
|-
| <code>__CollectEventCallbacks</code>
| <kbd>Say</kbd> || <kbd>void Say(CTerrorPlayer ''player'', string ''message'', bool ''teamOnly'') </kbd>
| <code>void __CollectEventCallbacks(scope)</code>
| Calling this will have the specified player send the message to chat, either to teamOnly (true) or to everyone.  
| Registers callbacks for [[#OnGameEvent_x|OnGameEvent_''x'']] functions.
|-
|-
| <code>__CollectEventCallbacks</code>
| <kbd>SendToConsole</kbd> || <kbd>void SendToConsole(string ''command'')</kbd>
| <code>void __CollectEventCallbacks(scope, prefix, globalTableName, regFunc)</code>
| Send a string to the console as a command.
| Overloaded function, used by the above one like this: <code>__CollectEventCallbacks(scope, "OnGameEvent_", "GameEventCallbacks", ::RegisterScriptGameEventListener)</code>
|-
|-
| <code>__ExecutePreSpawn</code>
| <kbd>SendToServerConsole</kbd> || <kbd>void SendToServerConsole(string ''command'')</kbd>
|  
| Send a string to the server console as a command.
|  
|-
|-
| <code>__FinishSpawn</code>
|}
|  
 
|  
=== Hooks ===
|-
{{↑|toc}}
| <code>__ReplaceClosures</code>
==== DebugTick ====
| <code>void __ReplaceClosures(script, scope)</code>
 
|  
<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.}}
|-
 
| <code>__RunEventCallbacks</code>
==== Update ====
| <code>void __RunEventCallbacks(event, params, prefix, globalTableName, bWarnIfMissing)</code>
<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.
| Call all functions in the callback array for the given game event.
 
|-
===== DirectorScript.Update =====
| <code>__RunGameEventCallbacks</code>
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.
| <code>void __RunGameEventCallbacks(event, params </code>
 
| Wrapper for <code>__RunEventCallbacks()</code>
===== 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).}}
=== Debugging functions ===
 
Functions for interacting with the debugger. Some of them are documented [[L4D2_EMS/Appendix:_Debugging|here]].
{| class="standard-table" style="width: 100%;"
 
|- style="position:sticky; z-index:10; top:0"
*BeginScriptDebug
! Function !! Signature !! Description
*EndScriptDebug
|-
*ScriptDebugAddTextFilter
| <kbd>ScriptedMode_CallNextUpdate</kbd> || <kbd>void ScriptedMode_CallNextUpdate(function callnext)</kbd>
*ScriptDebugAddTrace
| Pass a function to this, it will get called once as part of next Update, for doing something 'soon but not now'
*ScriptDebugAddWatch
|-
*ScriptDebugAddWatches
| <kbd>ScriptedMode_AddUpdate</kbd> || <kbd>void ScriptedMode_AddUpdate(function updatefunc)</kbd>
*ScriptDebugAddWatchPattern
| Register arbitrary function without parameters to run every second (single function cannot be registered twice).
*ScriptDebugClearTraces
|-
*ScriptDebugClearWatches
| <kbd>ScriptedMode_AddSlowPoll</kbd> || <kbd>void ScriptedMode_AddSlowPoll(function updatefunc)</kbd>
*ScriptDebugDraw
| Register arbitrary function without parameters to run every 3 seconds (single function cannot be registered twice).
*ScriptDebugDrawWatches
|-
*ScriptDebugDumpKeys
| <kbd>ScriptedMode_RemoveUpdate</kbd> || <kbd>void ScriptedMode_RemoveUpdate(function updatefunc)</kbd>
*ScriptDebugHook
| Removes a function that was before added by ScriptedMode_AddUpdate
*ScriptDebugIterateKeys
|-
*ScriptDebugIterateKeysRecursive
| <kbd>ScriptedMode_RemoveSlowPoll</kbd> || <kbd>void ScriptedMode_RemoveSlowPoll(function updatefunc)</kbd>
*ScriptDebugRemoveTextFilter
| Removes a function that was before added by ScriptedMode_AddSlowPoll
*ScriptDebugRemoveTrace
|}
*ScriptDebugRemoveWatch
 
*ScriptDebugRemoveWatches
===== DirectorScript.MapScript.LocalScript.Update =====
*ScriptDebugRemoveWatchPattern
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.
*ScriptDebugTextDraw
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.
*ScriptDebugTextPrint
 
*ScriptDebugTextTrace
===== DirectorScript.MapScript.ChallengeScript.Update =====
*ScriptDebugTraceAll
Update function defined inside a mutation script for example in <code>mymutation.nut</code>.
*__VScriptServerDebugHook
 
=== Entity Manipulation ===
{{↑|toc}}
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>[[/AddThinkToEnt|AddThinkToEnt]]</kbd> || <kbd>void AddThinkToEnt(handle ''entity'', string ''FuncName'')</kbd>
| Sets a function in the entity's script to rerun by itself constantly.
|-
| <kbd>[[/CommandABot|CommandABot]]</kbd> || <kbd>bool CommandABot(table ''commandTable'')</kbd>
| Issues commands to bots based on a table configuration.
|-
| <kbd>ConnectOutputs</kbd> || <kbd>void ConnectOutputs(table)</kbd>
| 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)
|-
| <kbd>DoEntFire</kbd> || <kbd>void DoEntFire(string ''target'', string ''action'', string ''value'', float ''delay'', handle ''activator'', handle ''caller'')</kbd>
| 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''.
|-
| <kbd>EntFire</kbd> || <kbd>void EntFire(string ''target'', string ''action'', string ''value = null'', float ''delay = 0'', handle ''activator = null'')</kbd>
| 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}}
|-
| <kbd>DropFire</kbd> || <kbd>void DropFire(Vector ''location'')</kbd>
| Drop a fire pool from the specified Vector location.
|-
| <kbd>DropSpit</kbd> || <kbd>void DropSpit(Vector ''location'')</kbd>
| Drop a spit pool from the specified Vector location.
|-
| <kbd>EmitAmbientSoundOn</kbd> || <kbd>void EmitAmbientSoundOn(string ''soundName'', float ''volume'', int ''soundlevel'', int ''pitch'', handle ''entity'')</kbd>
| Play named sound on an entity that has similar configurations to [[ambient_generic]].
|-
| <kbd>EmitSoundOnClient</kbd> || <kbd>void EmitSoundOnClient(string ''soundScript'', handle ''player'')</kbd>
| Play named sound only on the client for the specified player.
|-
| <kbd>EmitSoundOn</kbd> || <kbd>void EmitSoundOn(string ''soundScript'', handle ''entity'')</kbd>
| Play named sound on an entity.
|-
| <kbd>EntIndexToHScript</kbd> || <kbd>CBaseEntity EntIndexToHScript(int ''entIndex'')</kbd>
| Returns the script handle for the given entity index.
|-
| <kbd>FindRescueAreaTrigger</kbd> || <kbd>CBaseTrigger FindRescueAreaTrigger()</kbd>
| Returns the trigger entity for the rescue area.
|-
| <kbd>GetListenServerHost</kbd> || <kbd>handle GetListenServerHost()</kbd>
| Get the host player on a listen server.
|-
| <kbd>GetFriction</kbd> || <kbd>float GetFriction(CTerrorPlayer ''player'')</kbd>
| Returns the Friction on a player entity, meaningless if not a player.
|-
| <kbd>[[/GetInvTable| GetInvTable]]</kbd> || <kbd>void GetInvTable(CTerrorPLayer ''player'',table ''invTable'')</kbd>
| Fills ''invTable'' with the specified player's inventory.
|-
| <kbd>GetPhysVelocity</kbd> || <kbd>Vector GetPhysVelocity(handle ''entity'')</kbd>
| Returns the velocity of the entity.
|-
| <kbd>GetPhysAngularVelocity</kbd> || <kbd>Vector GetPhysAngularVelocity(handle ''entity'')</kbd>
| Returns the Angular velocity of the entity.
|-
| <kbd>GetPlayerFromCharacter</kbd> || <kbd>handle GetPlayerFromCharacter(int ''characterType'')</kbd>
| Given a character type, return the entity, or null.
|-
| <kbd>GetPlayerFromUserID</kbd> || <kbd>handle GetPlayerFromUserID(int ''ID'')</kbd>
| Given a user id, return the entity, or null.
|-
| <kbd>IsPlayerABot</kbd> || <kbd>bool IsPlayerABot(handle ''player'')</kbd>
| Is this player/entity a bot.
|-
| <kbd>PickupObject</kbd> || <kbd>void PickupObject(handle ''player'', handle ''entity'')</kbd>
| 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.
|-
| <kbd>PlayerInstanceFromIndex</kbd> || <kbd>CTerrorPlayer PlayerInstanceFromIndex(int ''index'')</kbd>
| Get a script handle of a player using the player index.
|-
| <kbd>PrecacheEntityFromTable</kbd> || <kbd>bool PrecacheEntityFromTable(table ''keyvalues'')</kbd>
| Precache an entity from [[KeyValues]] in a table.
|-
| <kbd>RotateOrientation</kbd> || <kbd>QAngle RotateOrientation(QAngle, QAngle)</kbd>
| Rotate a QAngle by another QAngle.
|-
| <kbd>RotatePosition</kbd> || <kbd>Vector RotatePosition(Vector ''origin'', QAngle ''rotation'', Vector ''input'')</kbd>
| Rotate the input Vector around an origin.
|-
| <kbd>SetFakeClientConVarValue</kbd> || <kbd>void SetFakeClientConVarValue(handle ''bot'', string ''cvar'', string ''value'')</kbd>
| Sets a USERINFO client ConVar for a fakeclient.
|-
| <kbd>SpawnEntityFromTable</kbd> || <kbd>handle SpawnEntityFromTable(string ''classname'', table ''keyvalues'')</kbd>
| Native function for entity spawning. See [[L4D2_EMS/Appendix:_Spawning]].
|-
| <kbd>SpawnEntityGroupFromTable</kbd> || <kbd>bool SpawnEntityGroupFromTable(table ''entityGroup'')</kbd>
| Native function for entity group spawning. See [[L4D2_EMS/Appendix:_Spawning]].
|-
| <kbd>StopAmbientSoundOn</kbd> || <kbd>void StopAmbientSoundOn(string ''soundName'', handle ''entity'')</kbd>
| Stop named sound on an entity that has similar configurations to [[ambient_generic]].
|-
| <kbd>StopSoundOn</kbd> || <kbd>void StopSoundOn(string ''soundScript'', handle ''entity'')</kbd>
| Stop named sound on an entity.
|-
| <kbd>[[/ZSpawn| ZSpawn]]</kbd> || <kbd>bool ZSpawn(table ''spawnTable'')</kbd>
| Spawn an infected of liking, with a choice.
|}
 
=== 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%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <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>
|
|-
| <kbd>rrDebugPrint</kbd> || <kbd>void rrDebugPrint(string ''message'')</kbd>
| Print function that works similarly to {{Code|printl()}} but prepends ''RR_TESTBED: '' to the start of the message.
|-
| <kbd>rr_ProcessResponse</kbd> || <kbd>unknown rr_ProcessResponse(unknown ''resp'')</kbd>
|
|-
| <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.
|-
| <kbd>ClearGameEventCallbacks</kbd> || <kbd>void ClearGameEventCallbacks()</kbd>
| Empties the tables of game event callback functions.
|-
| <kbd>ClearSavedTables</kbd> || <kbd>void ClearSavedTables()</kbd>
| Removes any tables saved with {{Code|SaveTable()}}.
|-
| <kbd>developer</kbd> || <kbd>int developer()</kbd>
| The current level of the <kbd>developer</kbd> console variable.
|-
| <kbd>Document</kbd> || <kbd>void Document(unknown ''symbolOrTable'', unknown ''itemIfSymbol'' = null, string ''descriptionIfSymbol'' = null)</kbd>
|
|-
| <kbd>DoIncludeScript</kbd> || <kbd>bool DoIncludeScript(string ''file'', handle/table ''scope'')</kbd>
| Execute a script. and put all its content for the argument passed to the {{Code|scope}} parameter. (internal)
|-
| <kbd>IncludeScript</kbd> || <kbd>bool IncludeScript(string ''file'', handle ''scope'' = null)</kbd>
| Wrapper for DoIncludeScript.
|-
| <kbd>DoUniqueString</kbd> || <kbd>string DoUniqueString(string/null ''input'')</kbd>
| 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 {{Code|UniqueString}} function instead, as it is converting any input value to a string before calling this function, making generation process practically errorless.
|-
| <kbd>Ent</kbd> || <kbd>handle Ent(string/int ''idxorname'')</kbd>
| 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.
|-
| <kbd>FileToString</kbd> || <kbd>string FileToString(string ''path'')</kbd>
| 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|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.}}
|-
| <kbd>FireGameEvent</kbd> || <kbd>string FireGameEvent(string ''event'', table ''params'')</kbd>
| Fire a game event to a listening callback function in script. Parameters are passed in a squirrel table.
|-
| <kbd>FireScriptEvent</kbd> || <kbd>void FireScriptEvent(event, params)</kbd>
| Wrapper for {{Code|__RunEventCallbacks()}}
|-
| <kbd>ForceScavengeStart</kbd> || <kbd>void ForceScavengeStart()</kbd>
| Starts the scavenge round, even if the setup timer hasn't elapsed.
|-
| <kbd>ForceSurvivalStart</kbd> || <kbd>void ForceSurvivalStart()</kbd>
| Starts the survival round, even if the survivors haven't activated the radio.
|-
| <kbd>ForceVersusStart</kbd> || <kbd>void ForceVersusStart()</kbd>
| Starts the versus round, even if the survivors haven't left the safe room.
|-
| <kbd>GetCharacterDisplayName</kbd> || <kbd>string GetCharacterDisplayName(CTerrorPlayer ''player'')</kbd>
| Return {{Code|null}} if not a survivor, else the survivor's chosen character's name. This does not work with team 4 survivors.
|-
| <kbd>GetCurrentFlowDistanceForPlayer</kbd> || <kbd>float GetCurrentFlowDistanceForPlayer(CTerrorPlayer ''player'')</kbd>
| Returns the navigation flow distance from the start to the specified player.
|-
| <kbd>GetCurrentFlowPercentForPlayer</kbd> || <kbd>float GetCurrentFlowPercentForPlayer(CTerrorPlayer ''player'')</kbd>
| Returns how far in the navigation flow from the start to the end the player is.
|-
| <kbd>GetFlowDistanceForPosition</kbd> || <kbd>float GetFlowDistanceForPosition(Vector ''position'')</kbd>
| Returns the navigation flow distance from the start to the specified point.
|-
| <kbd>GetFlowPercentForPosition</kbd> || <kbd>float GetFlowPercentForPosition(Vector ''position'', bool ''unknown'')</kbd>
| Returns how far in the navigation flow from the start to the end the position is.
|-
| <kbd>GetMaxFlowDistance</kbd> || <kbd>float GetMaxFlowDistance()</kbd>
| Returns the navigation flow distance from the start to the end of the level.
|-
| <kbd>GetAverageSurvivorFlowDistance</kbd> || <kbd>float GetAverageSurvivorFlowDistance()</kbd>
| Returns the navigation flow distance from the start to the survivors position averaged.
|-
| <kbd>GetDifficulty</kbd> || <kbd>int GetDifficulty()</kbd>
| Returns the current difficulty as a numeric value. Easy = 0, Normal = 1, Advanced = 2, Expert = 3.
|-
| <kbd>GetDifficultyString</kbd> || <kbd>string GetDifficultyString()</kbd>
| Returns the current difficulty as a string. Difficulty names are in z_difficulty cvar style: Easy, Normal, Hard, Impossible.
|-
| <kbd>GetFrameCount</kbd> || <kbd>void GetFrameCount()</kbd>
| Returns the engine's current frame count.
|-
| <kbd>GetFunctionSignature</kbd> ||
|
|-
| <kbd>GetInfectedStats</kbd> || <kbd>void GetInfectedStats(table ''statTable'') </kbd>
| 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.
|-
| <kbd>GetModelIndex</kbd> || <kbd>int GetModelIndex(string ''filename'')</kbd>
| Returns index of model by name.
|-
| <kbd>GetScavengeItemsGoal</kbd> || <kbd>int GetScavengeItemsGoal()</kbd>
| Returns number of Scavenge items needed.
|-
| <kbd>GetScavengeItemsRemaining</kbd> || <kbd>int GetScavengeItemsRemaining()</kbd>
| Returns number of Scavenge items remaining.
|-
| <kbd>GetSoundDuration</kbd> || <kbd>float GetSoundDuration(string ''soundname'', string ''actormodel'')</kbd>
| Returns float duration of the sound. Takes soundname and optional actormodelname.
|-
| <kbd>HasConfigurableDifficultySetting</kbd> || <kbd>bool HasConfigurableDifficultySetting()</kbd>
| Returns true if the mode has more than a single difficulty.
|-
| <kbd>HasPlayerControlledZombies</kbd> || <kbd>bool HasPlayerControlledZombies()</kbd>
| Returns true if the current mode supports player controlled zombies.
|-
| <kbd>IsMissionFinalMap</kbd> || <kbd>bool IsMissionFinalMap()</kbd>
| True if the current map is the final map of the campaign. Independent of {{ent|trigger_finale}} existence.
|-
| <kbd>IsDedicatedServer</kbd> || <kbd>bool IsDedicatedServer()</kbd>
| Returns true if this is a dedicated server.
|-
| <kbd>IsModelPrecached</kbd> || <kbd>bool IsModelPrecached(string ''modelname'')</kbd>
| Checks if the modelname is precached.
|-
| <kbd>IsSoundPrecached</kbd> || <kbd>bool IsSoundPrecached(string ''soundname'')</kbd>
| Checks if the soundname is precached.
|-
| <kbd>IsWeakref</kbd> || <kbd>bool IsWeakref(table, key)</kbd>
| Returns true/false based on whether table[key] is a weak reference
|-
| <kbd>LocalTime</kbd> || <kbd>void LocalTime(table)</kbd>
| Fills out a table with the local time (second, minute, hour, day, month, year, dayofweek, dayofyear, daylightsavings).
|-
| <kbd>MakeNamespace</kbd> ||
|
|-
| <kbd>PrecacheModel</kbd> || <kbd>int PrecacheModel(string ''filename'')</kbd>
| Precache a model and return index of the model.
|-
| <kbd>PrecacheSound</kbd> || <kbd>void PrecacheSound(string ''soundName'')</kbd>
| Precache a sound.
|-
| <kbd>QueueSpeak</kbd> || <kbd>void QueueSpeak(handle ''entity'', string ''concept'', float ''delay'', string ''criteria'')</kbd>
| Queue a speech concept.
|-
| <kbd>RandomFloat</kbd> || <kbd>float RandomFloat(float ''min'', float ''max'')</kbd>
| Generate a random floating-point number within a range, inclusive.
|-
| <kbd>RandomInt</kbd> || <kbd>int RandomInt(int ''min'', int ''max'')</kbd>
| Generate a random integer within a range, inclusive.
|-
| <kbd>ReapplyInfectedFlags</kbd> || <kbd>ReapplyInfectedFlags(int ''flags'', handle ''infected'')</kbd>
| Apply Infected Flags from {{Code|DirectorOptions}}. Applies to all common (spawned and unspawned) unless a handle to a specific infected is specified.
|-
| <kbd>RegisterFunctionDocumentation</kbd> || <kbd>void RegisterFunctionDocumentation(unknown ''func'', string ''name'', string ''signature'', string ''description'')</kbd>
|
|-
| <kbd>RegisterScriptGameEventListener</kbd> || <kbd>void RegisterScriptGameEventListener(string ''eventName'')</kbd>
| Register as a listener for a game event from script. It's what {{Code|__CollectGameEventCallbacks()}} uses to register event callbacks to the C++ code.
|-
| <kbd>ReloadMOTD</kbd> || <kbd>void ReloadMOTD()</kbd>
| Reloads the MotD file.
|-
| <kbd>RestoreTable</kbd> || <kbd>void RestoreTable(string ''identifier'', table)</kbd>
|Restores table data and '''deletes it'''. See [[L4D2_EMS/Appendix:_Table_Save_Restore]].
|-
| <kbd>RetrieveNativeSignature</kbd> || <kbd>unknown RetrieveNativeSignature(string ''nativeFunction'')</kbd>
|
|-
| <kbd>rr_AddDecisionRule</kbd> || <kbd>bool rr_AddDecisionRule(RRule ''rule'')</kbd>
| Add a rule to the decision database. Takes a RRule object from rulescript_base.nut.
|-
| <kbd>rr_CommitAIResponse</kbd> || <kbd>bool rr_CommitAIResponse(handle ''entity'', table ''airesponse'')</kbd>
| 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.
|-
| <kbd>rr_GetResponseTargets</kbd> || <kbd>table rr_GetResponseTargets()</kbd>
| Retrieve a table of all available expresser targets, in the form { name : handle, name: handle }.
|-
| <kbd>rr_QueryBestResponse</kbd> || <kbd>unknown rr_QueryBestResponse(handle ''entity'', table ''query'')</kbd>
| 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.
|-
| <kbd>RushVictim</kbd> || <kbd>void RushVictim(handle ''hVictim'', float ''range'')</kbd>
| Make all common zombies in range rush the victim. (If hVictim isn't set, a random survivor will be chosen.)
|-
| <kbd>SaveTable</kbd> || <kbd>void SaveTable(string ''identifier'', table)</kbd>
| See [[L4D2_EMS/Appendix:_Table_Save_Restore]].
|-
| <kbd>ScreenFade</kbd> || <kbd>void ScreenFade(handle ''player'', int ''red'', int ''green'', int ''blue'', int ''alpha'', float ''fadeTime'', float ''fadeHold'', int ''flags'')</kbd>
| Start a screenfade with the following parameters.
|-
| <kbd>ScreenShake</kbd> || <kbd>void ScreenShake(Vector ''vecCenter'', float ''flAmplitude'', float ''flFrequency'', float ''flDuration'', float ''flRadius'', int ''eCommand'', bool ''bAirShake'')</kbd>
| Start a screenshake with the following parameters.
|-
| <kbd>SetScavengeItemsGoal</kbd> || <kbd>void SetScavengeItemsGoal(int ''count'')</kbd>
| Set the number of Scavenge items needed.
|-
| <kbd>SetScavengeItemsRemaining</kbd> || <kbd>void SetScavengeItemsRemaining(int ''count'')</kbd>
| Set the number of Scavenge items remaining.
|-
| <kbd>StageInfo_Execute</kbd> || <kbd>void StageInfo_Execute(''stageInfo'', ''stageDefaults'')</kbd>
| Execute a stage table, i.e. move parameters to DirectorOptions, do callbacks and so on.
|-
| <kbd>StartAssault</kbd> || <kbd>void StartAssault()</kbd>
| Tells all existing nextbots to swap into assault mode and not hide/dither/loiter.
|-
| <kbd>StringToFile</kbd> || <kbd>void StringToFile(string ''path'', string ''string'')</kbd>
| 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.
|-
| <kbd>Time</kbd> || <kbd>float Time()</kbd>
| Get the current server time.
|-
| <kbd>[[/TraceLine| TraceLine]]</kbd> || <kbd>bool TraceLine(table ''traceTable'')</kbd>
| Uses a configuration table to do a raytrace, puts return information into the table for return usage.
|-
| <kbd>UniqueString</kbd> || <kbd>string UniqueString(string ''input''="")</kbd>
| 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.
|-
| <kbd>VSquirrel_OnCreateScope</kbd> || <kbd>table VSquirrel_OnCreateScope(value, table ''scope'')</kbd>
| Creates a new scope with the name of value in the submitted table (includes unique params).
|-
| <kbd>VSquirrel_OnReleaseScope</kbd> || <kbd>void VSquirrel_OnReleaseScope(table ''createdScope'')</kbd>
| Removes a scope created via VSquirrel_OnCreateScope.
|-
| <kbd>__CollectGameEventCallbacks</kbd> || <kbd>void __CollectGameEventCallbacks(scope)</kbd>
| Wrapper that registers callbacks for both [[#OnGameEvent_x|OnGameEvent_''x'' ↑]] and {{Code|OnScriptEvent_}} functions. Done using the {{Code|__CollectEventCallbacks}} function.
|-
| <kbd>__CollectEventCallbacks</kbd> || <kbd>void __CollectEventCallbacks(scope, prefix, globalTableName, regFunc)</kbd>
| Overloaded function, used by the above one like this: {{Code|__CollectEventCallbacks(scope, "OnGameEvent_", "GameEventCallbacks", ::RegisterScriptGameEventListener)}}
|-
| <kbd>__ExecutePreSpawn</kbd> ||
|
|-
| <kbd>__FinishSpawn</kbd> ||
|
|-
| <kbd>__ReplaceClosures</kbd> || <kbd>void __ReplaceClosures(script, scope)</kbd>
|
|-
| <kbd>__RunEventCallbacks</kbd> || <kbd>void __RunEventCallbacks(event, params, prefix, globalTableName, bWarnIfMissing)</kbd>
| Call all functions in the callback array for the given game event.
|-
| <kbd>__RunGameEventCallbacks</kbd> || <kbd>void __RunGameEventCallbacks(event, params </kbd>
| Wrapper for {{Code|__RunEventCallbacks()}}
|}
 
=== Squirrel Standard Library ===
{{↑|toc}}
 
{{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.
 
{| class = "standard-table" style = "width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <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''}}.
|-
| <kbd>assert</kbd> || <kbd>assert(bool ''exp'')</kbd>
| Throws an exception if exp is evaluated to false.
|-
| <kbd>callee</kbd> || <kbd>function callee()</kbd>
| Returns the currently running closure.
|-
| <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.
|-
| <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.
|-
| <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.
|-
| <kbd>error</kbd> || <kbd>void error(string ''x'')</kbd>
| Prints x in the standard error output.
|-
| <kbd>getconsttable</kbd> || <kbd>table getconsttable()</kbd>
| Returns the const table of the VM.
|-
| <kbd>getroottable</kbd> || <kbd>table getroottable()</kbd>
| Returns the root table of the VM.
|-
| <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>
}}
|-
| <kbd>newthread</kbd> || <kbd>coroutine newthread(function ''threadfunc'')</kbd>
| Creates a new cooperative thread object(coroutine) and returns it
|-
| <kbd>print</kbd> || <kbd>void print(string ''message'')</kbd>
| Prints message to console without any line feed after.
|-
| <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.
|-
| <kbd>setconsttable</kbd> || <kbd>table setconsttable(table ''consttable'')</kbd>
| Sets the const table of the VM which also returns the previous const table. 
|-
| <kbd>seterrorhandler</kbd> || <kbd>void seterrorhandler(function ''func'')</kbd>
| Sets the runtime error handler .
|-
| <kbd>setroottable</kbd> || <kbd>table setroottable(table ''roottable'')</kbd>
| Sets the root table of the VM which also returns the previous root table.
|-
| <kbd>suspend</kbd> || <kbd>void suspend(any ''ret'')</kbd>
| Suspends the coroutine that called this function.
|-
| <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
|-
| <kbd>abs</kbd> || <kbd> int abs(float ''x'')</kbd>
| Returns the absolute value of <kbd>x</kbd> as an integer.
|-
| <kbd>acos</kbd> || <kbd> float acos(float ''x'')</kbd>
| Returns the arccosine of <kbd>x</kbd>.
|-
| <kbd>asin</kbd> || <kbd> float asin(float ''x'')</kbd>
| Returns the arcsine of <kbd>x</kbd>.
|-
| <kbd>atan</kbd> || <kbd> float atan(float ''x'')</kbd>
| Returns the arctangent of <kbd>x</kbd>.
|-
| <kbd>atan2</kbd> || <kbd> float atan2(float ''x'', float ''y'')</kbd>
| Returns the arctangent of <kbd>x/y</kbd>.
|-
| <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>.
|-
| <kbd>cos</kbd> || <kbd> float cos(float ''x'')</kbd>
| Returns the cosine of <kbd>x</kbd>.
|-
| <kbd>exp</kbd> || <kbd> float exp(float ''x'')</kbd>
| Returns the exponential value (<kbd>e^x</kbd>) of the float parameter <kbd>x</kbd>.
|-
| <kbd>fabs</kbd> || <kbd> float fabs(float ''x'')</kbd>
| Returns the absolute value of <kbd>x</kbd> as a float.
|-
| <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>.
|-
| <kbd>log</kbd> || <kbd> float log(float ''x'')</kbd>
| Returns the natural logarithm of <kbd>x</kbd>.
|-
| <kbd>log10</kbd> || <kbd> float log10(float ''x'')</kbd>
| Returns the logarithm base-10 of <kbd>x</kbd>.
|-
| <kbd>pow</kbd> || <kbd> float pow(float ''x'', float ''y'')</kbd>
| Returns <kbd>x</kbd> raised to the power of <kbd>y</kbd>.
|-
| <kbd>rand</kbd> || <kbd> int rand()</kbd>
| Returns a pseudorandom integer in the range 0 to <kbd>RAND_MAX</kbd>.
|-
| <kbd>sin</kbd> || <kbd> float sin(float ''x'')</kbd>
| Returns the sine of <kbd>x</kbd>.
|-
| <kbd>sqrt</kbd> || <kbd> float sqrt(float ''x'')</kbd>
| Returns the square root of <kbd>x</kbd>.
|-
| <kbd>srand</kbd> || <kbd> void srand(float ''seed'')</kbd>
| Sets the starting point for generating a series of pseudorandom integers.
|-
| <kbd>tan</kbd> || <kbd> float tan(float ''x'')</kbd>
| Returns the tangent of <kbd>x</kbd>.
|}
 
==== Strings ====
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].
 
{| class="standard-table" style="width:100%"
! Function !! Signature !! Description
|-
| <kbd>format</kbd> || <kbd>string format(string ''format'', args...)</kbd>
| Returns a [[w:printf format string|formatted string]]. Same rules as the standard C functions (except * is not supported).
|-
| <kbd>lstrip</kbd> || <kbd>string lstrip(string ''str'')</kbd>
| Removes whitespace characters at the beginning of the given string.
|-
| <kbd>rstrip</kbd> || <kbd>string rstrip(string ''str'')</kbd>
| Removes whitespace characters at the end of the given string.
|-
| <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.
|}
 
=== Script Debug ===
{{↑|toc}}
Functions for interacting with the debugger. Some of them are documented [[L4D2_EMS/Appendix:_Debugging|here]].
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <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]]


=== Standard Squirrel library ===
<!--
 
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.
{{sq}}Standard Squirrel library functions (consult official Squirrel language league for more details):
For some of these pages, it might be better to make use of Github and its file viewer?
{| class="standard-table"
! Function
|-
|abs
|-
|acos
|-
|array
|-
|asin
|-
|assert
|-
|atan
|-
|atan2
|-
|ceil
|-
|collectgarbage
|-
|compilestring
|-
|cos
|-
|exp
|-
|fabs
|-
|floor
|-
|format
|-
|getconsttable
|-
|getroottable
|-
|getstackinfos
|-
|log
|-
|log10
|-
|lstrip
|-
|pow
|-
|print
|-
|rand
|-
|rstrip
|-
|setconsttable
|-
|seterrorhandler
|-
|setroottable
|-
|type
|-
|sin
|-
|split
|-
|sqrt
|-
|srand
|-
|strip
|-
|suspend
|-
|tan
|}


== See also ==
* {{l4d2}} [[L4D2_Vscript_Helpers|L4D2 VScript Helpers]]
* [[L4D2 Vscripts]]
* [[L4D2 Vscript Examples]]
* {{portal2}} [[List of Portal 2 Script Functions]]


=== [[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 ↑