This article relates to the game "Portal 2". Click here for more information.
This article relates to "Squirrel". Click here for more information.

Portal 2/Scripting/Script Functions: Difference between revisions

From Valve Developer Community
Jump to navigation Jump to search
(point_template hooks exist in portal 2 as well)
(→‎CPlayerVoiceListener: Add information about this)
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
{{lang|List of Portal 2 Script Functions|title=List of ''​Portal 2​'' Script Functions}}
{{LanguageBar|title=List of ''​Portal 2​'' Script Functions}}
{{p2 topicon}}{{SQ topicon}}
{{p2 topicon}}
{{SQ topicon}}
{{toc-right}}
{{toc-right}}
{{sq}} This list contains all engine-related Squirrel classes, functions, and variables available for [[VScript]] in {{Portal2|4}}.


This list contains all engine-related Squirrel functions available for [[VScript]] in {{Portal2|4}}. It can be printed in-game with the <code>script_help</code> command while running in [[Engine tools|tools mode]].
The official documentation can be printed in the console by setting [[developer]] to non-zero, loading a map, and executing <kbd>script_help</kbd>. However, that documentation does not list everything, requiring them to be found by other means instead.


== Variables ==
In addition to these, VScript also comes with many of Squirrel's predefined standard library functions. {{↓|Squirrel Standard Library|See below}} for a list of them.
 
{{tip|A tutorial on setting up Visual Studio Code (VSCode), including auto-completing of VScript functions, can be [[Setting_Up_VScript_in_Visual_Studio_Code|found here]].}}
 
== Global variables ==
{| class="standard-table"
{| class="standard-table"
!Instance
! Instance !! Type !! Description
!Type
!Description
|-
|-
|<code>Entities</code>
<!-- min-width applied to keep the arrow on the same line -->
|<code>[[#CEntities|CEntities]]</code>
| <kbd>Entities</kbd> || style="min-width: 80px;" | <kbd>{{↓|CEntities}}</kbd>
|Provides access to spawned entities in the server.
| Provides access to spawned entities in the server.
|-
|-
| <kbd>Documentation</kbd> || <kbd>table</kbd>
| A table that has 3 documentation sub-tables (<code>classes</code>, <code>functions</code>, <code>instances</code>) which store information related to function documentation. Only exists when the [[developer]] level is greater than 0.
|}
|}


== Global hooks ==
These hooks only work when defined in the root table.


== Constants ==
{| class="standard-table"
{| class="standard-table"
!Instance
|- style="position:sticky; z-index:10; top:0"
!Type
! Function !! Signature !! Description
!Value
|-
|-
|<code>_charsize_</code>
| <kbd>ConnectOutputs</kbd> || <kbd>void ConnectOutputs(table ''table'')</kbd>
|integer
| Called after an entity with an script assigned spawns (i.e. vscripts keyvalue is not blank), passing the entity's scope as the parameter. Unlike <code>OnPostSpawn</code>, this is called immediately and therefore on map respawn, some entities may not exist during this point.<br>
| 1
 
|-
Originally this would have been used for automatically connecting an entity's outputs on spawn, but the Squirrel code used for this was disabled due to a crash that occurred with regexp not saving/loading properly after a save/load. {{confirm|Can this supposed crash still occur?}}
|<code>_floatsize_</code>
 
|integer
To re-enable this behavior, define the following in the root table:
| 4
{{Expand|<source lang="cpp">
|-
::__OutputsPattern <- regexp("^On.*Output$");
|<code>_intsize_</code>
 
|integer
::ConnectOutputs <- function( table )
| 4
{
|-
const nCharsToStrip = 6;
|<code>_version_</code>
foreach( key, val in table )
|string
{
| "Squirrel 2.2.3 stable"
if ( typeof( val ) == "function" && __OutputsPattern.match( key ) )
|-
{
|<code>RAND_MAX</code>
//printl(key.slice( 0, nCharsToStrip ) );
|integer
table.self.ConnectOutput( key.slice( 0, key.len() - nCharsToStrip ), key );
| 32767
}
|-
}
|<code>PI</code>
}
|float
</source>
| 3.14159
}}
 
Then to use this system, define a function in an entity script with a name of the format <code>On<OutputName>Output</code>, where <code><OutputName></code> is the name of the entity's output you want to connect into (without the "On" prefix, as it's already provided).
|}
|}


== Classes ==
== Classes ==


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


All script handles in-game are accessible from [[#CEntities|Entities]]. Entity scripts can use <code>self</code> to access their own script handle. <code>activator</code> and <code>caller</code> variables can be accessed on function calls.
All script handles in-game are accessible from {{↓|CEntities|Entities}}. Entity scripts can use <code>self</code> to access their own script handle. <code>activator</code> and <code>caller</code> variables can be accessed on function calls.
 


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
|-
| <code>__KeyValueFromInt</code>
| <kbd>__KeyValueFromInt</kbd><br><kbd>__KeyValueFromFloat</kbd><br><kbd>__KeyValueFromString</kbd><br><kbd>__KeyValueFromVector</kbd>
| <code>void __KeyValueFromInt(string ''key'', int ''value'')</code>
| <kbd>bool __KeyValueFromInt(string ''key'', int ''value'')</kbd><br><kbd>bool __KeyValueFromFloat(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 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.
| Sets an entity [[keyvalue]] from a specific data type. Returns true if successfully set, false if it the key does not exist.<br>
This simply changes the value without executing any other code that may be needed for the entity to fully process the keyvalue, such as code for updating the entity's internal network state. This can create unexpected side effects on already-spawned entities such as visual changes being delayed for clients.
|-
|-
| <code>__KeyValueFromFloat</code>
| <kbd>ConnectOutput</kbd> || <kbd>void CBaseEntity::ConnectOutput(string output, string func_name)</kbd>
| <code>void __KeyValueFromFloat(string ''key'', float ''value'')</code>
| Adds an I/O connection that will call the named function when the specified output fires.
| 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>DisconnectOutput</kbd> || <kbd>void CBaseEntity::DisconnectOutput(string output, string func_name)</kbd>
| <code>void __KeyValueFromString(string ''key'', string ''value'')</code>
| Removes a connected script function from an I/O event.
| Sets an entity Keyvalue from a string. This simply changes the value without executing any code that may be needed for the entity to process the KeyValue, so there may be unintended side effects.
|-
| <code>__KeyValueFromVector</code>
| <code>void __KeyValueFromVector(string ''key'', Vector ''value'')</code>
| Sets an entity Keyvalue from a [[#Vector|Vector]]. This simply changes the value without executing any code that may be needed for the entity to process the KeyValue, so there may be unintended side effects.
|-
| <code>ConnectOutput</code>
| <code>void CBaseEntity::ConnectOutput(string output, string func_name)</code>
| Adds an I/O connection that will call the named function when the specified output fires.  
|-
|-
| <code>Destroy</code>
| <kbd>Destroy</kbd> || <kbd>void CBaseEntity::Destroy()</kbd>
| <code>void CBaseEntity::Destroy()</code>
| Kills this entity.
| Kill this entity.
|-
|-
| <code>DisconnectOutput</code>
| <kbd>entindex</kbd> |<kbd>int CBaseEntity::entindex()</kbd>
| <code>void CBaseEntity::DisconnectOutput(string output, string func_name)</code>
| Returns the [[Entity_index|entity index]].
| Removes a connected script function from an I/O event.
|-
|-
| <code>EmitSound</code>
| <kbd>EmitSound</kbd> || <kbd>void CBaseEntity::EmitSound(string sound)</kbd>
| <code>void CBaseEntity::EmitSound(string sound)</code>
| Plays a sound from this entity.
| Plays a sound from this entity.
|-
|-
| <code>EyePosition</code>
| <kbd>EyePosition</kbd> || <kbd>Vector CBaseEntity::EyePosition()</kbd>
| <code>Vector CBaseEntity::EyePosition()</code>
| Get vector to eye position - absolute coords.
| Get vector to eye position - absolute coords.
|-
|-
| <code>FirstMoveChild</code>
| <kbd>FirstMoveChild</kbd> || <kbd>handle CBaseEntity::FirstMoveChild()</kbd>
| <code>handle CBaseEntity::FirstMoveChild()</code>
| If in hierarchy, get the first move child.
| If in hierarchy, get the first move child.
|-
|-
| <code>GetAngles</code>
| <kbd>GetAngles</kbd> || <kbd>Vector CBaseEntity::GetAngles()</kbd>
| <code>Vector CBaseEntity::GetAngles()</code>
| Get entity pitch, yaw, roll as a vector.
| Get entity pitch, yaw, roll as a vector.
|-
|-
| <code>GetAngularVelocity</code>
| <kbd>GetAngularVelocity</kbd> || <kbd>Vector CBaseEntity::GetAngularVelocity()</kbd>
| <code>Vector CBaseEntity::GetAngularVelocity()</code>
| Get the local angular velocity - returns a vector of pitch,yaw,roll.
| Get the local angular velocity - returns a vector of pitch,yaw,roll.
|-
|-
| <code>GetBoundingMaxs</code>
| <kbd>GetVelocity</kbd> || <kbd>Vector CBaseEntity::GetVelocity()</kbd>
| <code>Vector CBaseEntity::GetBoundingMaxs()</code>
| Get the velocity of the entity. Note that this reads the [[QPhysics]] velocity value, so it only works for players, NPCs and moving brush entities. VPhysics objects always have a velocity of zero. A workaround is to record the position over multiple frames, and derive the velocity manually.
|-
| <kbd>GetBoundingMaxs</kbd> || <kbd>Vector CBaseEntity::GetBoundingMaxs()</kbd>
| Get a vector containing max bounds, centered on object.
| Get a vector containing max bounds, centered on object.
|-
|-
| <code>GetBoundingMins</code>
| <kbd>GetBoundingMins</kbd> || <kbd>Vector CBaseEntity::GetBoundingMins()</kbd>
| <code>Vector CBaseEntity::GetBoundingMins()</code>
| Get a vector containing min bounds, centered on object.
| Get a vector containing min bounds, centered on object.
|-
|-
| <code>GetCenter</code>
| <kbd>GetCenter</kbd> || <kbd>Vector CBaseEntity::GetCenter()</kbd>
| <code>Vector CBaseEntity::GetCenter()</code>
| Get vector to center of object - absolute coords.
| Get vector to center of object - absolute coords.
|-
|-
| <code>GetClassname</code>
| <kbd>GetClassname</kbd> || <kbd>string CBaseEntity::GetClassname()</kbd>
| <code>string CBaseEntity::GetClassname()</code>
| Get the classname of this entity.
| Get the classname of this entity.
|-
|-
| <code>GetForwardVector</code>
| <kbd>GetForwardVector</kbd> || <kbd>Vector CBaseEntity::GetForwardVector()</kbd>
| <code>Vector CBaseEntity::GetForwardVector()</code>
| Get the forward vector (+X) of the entity.
| Get the forward vector (+X) of the entity.
|-
|-
| <code>GetHealth</code>
| <kbd>GetLeftVector</kbd> || <kbd>Vector CBaseEntity::GetLeftVector()</kbd>
| <code>int CBaseEntity::GetHealth()</code>
| Get the left vector (+Y) of the entity.
|-
| <kbd>GetUpVector</kbd> || <kbd>Vector CBaseEntity::GetUpVector()</kbd>
| Get the up vector (+Z) of the entity.
|-
| <kbd>GetHealth</kbd> || <kbd>int CBaseEntity::GetHealth()</kbd>
| Returns the current [[health]].
| Returns the current [[health]].
|-
|-
| <code>GetLeftVector</code>
| <kbd>GetMaxHealth</kbd> || <kbd>int CBaseEntity::GetMaxHealth()</kbd>
| <code>Vector CBaseEntity::GetLeftVector()</code>
| Get the left vector of the entity.
|-
| <code>GetMaxHealth</code>
| <code>int CBaseEntity::GetMaxHealth()</code>
| Returns the maximum health.
| Returns the maximum health.
|-
|-
| <code>GetModelKeyValues</code>
| <kbd>GetModelKeyValues</kbd> || <kbd>handle CBaseEntity::GetModelKeyValues()</kbd>
| <code>handle CBaseEntity::GetModelKeyValues()</code>
| Get a KeyValue class instance on this entity's model.
| Get a KeyValue class instance on this entity's model.
|-
|-
| <code>GetModelName</code>
| <kbd>GetModelName</kbd> || <kbd>string CBaseEntity::GetModelName()</kbd>
| <code>string CBaseEntity::GetModelName()</code>
| Returns the name of the model.
| Returns the name of the model.
|-
|-
| <code>GetMoveParent</code>
| <kbd>GetMoveParent</kbd> || <kbd>handle CBaseEntity::GetMoveParent()</kbd>
| <code>handle CBaseEntity::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 CBaseEntity::GetName()</kbd>
| <code>string CBaseEntity::GetName()</code>
| Get the Targetname of this entity.
| Get the Targetname of this entity.
|-
|-
| <code>GetOrigin</code>
| <kbd>GetOrigin</kbd> || <kbd>Vector CBaseEntity::GetOrigin()</kbd>
| <code>Vector CBaseEntity::GetOrigin()</code>
| Returns this entity's local origin.
| Returns this entity's local origin.
|-
|-
| <code>GetOwner</code>
| <kbd>GetOwner</kbd> || <kbd>handle CBaseEntity::GetOwner()</kbd>
| <code>handle CBaseEntity::GetOwner()</code>
| Gets this entity's owner.
| Gets this entity's owner.
|-
|-
| <code>GetPreTemplateName</code>
| <kbd>GetPreTemplateName</kbd> || <kbd>string CBaseEntity::GetPreTemplateName()</kbd>
| <code>string CBaseEntity::GetPreTemplateName()</code>
| Get the entity name stripped of template unique decoration - the &001 suffix.
| Get the entity name stripped of template unique decoration - the &001 suffix.
|-
|-
| <code>GetRootMoveParent</code>
| <kbd>GetRootMoveParent</kbd> || <kbd>handle CBaseEntity::GetRootMoveParent()</kbd>
| <code>handle CBaseEntity::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 CBaseEntity::GetScriptId()</kbd>
| <code>string CBaseEntity::GetScriptId()</code>
| Returns the name of the entity's think function.
| Retrieve the unique identifier used to refer to the entity within the scripting system.
|-
|-
| <code>GetScriptScope</code>
| <kbd>GetScriptScope</kbd> || <kbd>handle CBaseEntity::GetScriptScope()</kbd>
| <code>handle CBaseEntity::GetScriptScope()</code>
| Retrieve the script-side data associated with an entity.
| Retrieve the script-side data associated with an entity.
|-
|-
| <code>GetSoundDuration</code>
| <kbd>GetSoundDuration</kbd> || <kbd>float CBaseEntity::GetSoundDuration(string, string)</kbd>
| <code>float CBaseEntity::GetSoundDuration(string, string)</code>
| Returns float duration of the sound. Takes soundname and optional actormodelname.
| Returns float duration of the sound. Takes soundname and optional actormodelname.
|-
|-
| <code>GetTeam</code>
| <kbd>GetTeam</kbd> || <kbd>int CBaseEntity::GetTeam()</kbd>
| <code>int CBaseEntity::GetTeam()</code>
| Get the team this entity is on.
| Get the team this entity is on.
|-
|-
| <code>GetUpVector</code>
| <kbd>IsValid</kbd> || <kbd>bool CBaseEntity::IsValid()</kbd>
| <code>Vector CBaseEntity::GetUpVector()</code>
| Get the up vector (+Z) of the entity.
|-
| <code>GetVelocity</code>
| <code>Vector CBaseEntity::GetVelocity()</code>
| Get the velocity of the entity. Note that this reads the [[QPhysics]] velocity value, so it only works for players, NPCs and moving brush entities. VPhysics objects always have a velocity of zero. A workaround is to record the position over multiple frames, and derive the velocity manually.
|-
| <code>IsValid</code>
| <code>bool CBaseEntity::IsValid()</code>
| Returns true if this entity is valid.
| Returns true if this entity is valid.
|-
|-
| <code>NextMovePeer</code>
| <kbd>NextMovePeer</kbd> || <kbd>handle CBaseEntity::NextMovePeer()</kbd>
| <code>handle CBaseEntity::NextMovePeer()</code>
| Return the next entity in the same movement hierarchy.
| Return the next entity in the same movement hierarchy.
|-
|-
| <code>PrecacheSoundScript</code>
| <kbd>PrecacheSoundScript</kbd> || <kbd>void CBaseEntity::PrecacheSoundScript(string)</kbd>
| <code>void CBaseEntity::PrecacheSoundScript(string)</code>
| Precache a sound for later playing. Should be called in the 'Precache()' hook function.
| Precache a sound for later playing. Should be called in the 'Precache()' hook function.
|-
|-
| <code>SetAbsOrigin</code>
| <kbd>SetAbsOrigin</kbd> || <kbd>void CBaseEntity::SetAbsOrigin(Vector)</kbd>
| <code>void CBaseEntity::SetAbsOrigin(Vector)</code>
| Teleport the entity to this world position.
| Teleport the entity to this world position.
|-
|-
| <code>SetAngles</code>
| <kbd>SetAngles</kbd> || <kbd>void CBaseEntity::SetAngles(float, float, float)</kbd>
| <code>void CBaseEntity::SetAngles(float, float, float)</code>
| Set entity pitch, yaw, roll
| Set entity pitch, yaw, roll
|-
|-
| <code>SetAngularVelocity</code>
| <kbd>SetAngularVelocity</kbd> || <kbd>void CBaseEntity::SetAngularVelocity(float, float, float)</kbd>
| <code>void CBaseEntity::SetAngularVelocity(float, float, float)</code>
| Set the local angular velocity - takes float pitch,yaw,roll velocities
| Set the local angular velocity - takes float pitch,yaw,roll velocities
|-
|-
| <code>SetForwardVector</code>
| <kbd>SetVelocity</kbd> || <kbd>void CBaseEntity::SetVelocity(Vector)</kbd>
| <code>void CBaseEntity::SetForwardVector(Vector)</code>
| Set local velocity.  Note that this sets the [[QPhysics]] velocity value, so it only works for players, NPCs and moving brush entities. On VPhysics objects, this has no effect.
|-
| <kbd>SetForwardVector</kbd> || <kbd>void CBaseEntity::SetForwardVector(Vector)</kbd>
| Set the orientation of the entity to have this forward (+X) vector.
| Set the orientation of the entity to have this forward (+X) vector.
|-
|-
| <code>SetHealth</code>
| <kbd>SetHealth</kbd> || <kbd>void CBaseEntity::SetHealth(int)</kbd>
| <code>void CBaseEntity::SetHealth(int)</code>
| Sets the current [[health]].
| Sets the current [[health]].
|-
|-
| <code>SetMaxHealth</code>
| <kbd>SetMaxHealth</kbd> || <kbd>void CBaseEntity::SetMaxHealth(int)</kbd>
| <code>void CBaseEntity::SetMaxHealth(int)</code>
| Sets the maximum health.
| Sets the maximum health.
|-
|-
| <code>SetModel</code>
| <kbd>SetModel</kbd> || <kbd>void CBaseEntity::SetModel(string)</kbd>
| <code>void CBaseEntity::SetModel(string)</code>
| Change the model used for the entity. This can be used to change models for prop_weighted_cube or other similar entities. The model must be precached, which is usually done by placing it elsewhere in the map.
| Change the model used for the entity. This can be used to change models for prop_weighted_cube or other similar entities. The model must be precached, which is usually done by placing it elsewhere in the map.
|-
|-
| <code>SetOrigin</code>
| <kbd>SetOrigin</kbd> || <kbd>void CBaseEntity::SetOrigin(Vector)</kbd>
| <code>void CBaseEntity::SetOrigin(Vector)</code>
| Teleport this entity to the given location.
| Teleport this entity to the given location.
|-
|-
| <code>SetOwner</code>
| <kbd>SetOwner</kbd> || <kbd>void CBaseEntity::SetOwner(handle)</kbd>
| <code>void CBaseEntity::SetOwner(handle)</code>
| Sets this entity's owner.
| Sets this entity's owner.
|-
|-
| <code>SetSize</code>
| <kbd>SetSize</kbd> || <kbd>void CBaseEntity::SetSize(Vector, Vector)</kbd>
| <code>void CBaseEntity::SetSize(Vector, Vector)</code>
| Sets the bounding box size.
| Sets the bounding box size.
|-
|-
| <code>SetTeam</code>
| <kbd>SetTeam</kbd> || <kbd>void CBaseEntity::SetTeam(int)</kbd>
| <code>void CBaseEntity::SetTeam(int)</code>
| Set the team this entity is on.
| Set the team this entity is on.
|-
|-
| <code>SetVelocity</code>
| <kbd>ValidateScriptScope</kbd> || <kbd>bool CBaseEntity::ValidateScriptScope()</kbd>
| <code>void CBaseEntity::SetVelocity(Vector)</code>
| Ensure that an entity's script scope has been created. This should be called before assigning to the entity's scope.
| Set local velocity. Note that this sets the [[QPhysics]] velocity value, so it only works for players, NPCs and moving brush entities. On VPhysics objects, this has no effect.
|}
 
==== Metamethods ====
{| class="standard-table" style="width: 100%;"
! Function !! Signature !! Description
|-
| <kbd>_tostring</kbd> || <kbd>string CBaseEntity::_tostring()</kbd>
| Overload for string conversion. Returns a string in the form "<kbd>([<''entindex''>] <''entity_class''>: <''targetname''>)</kbd>". If the entity does not have a targetname, it is omitted.
|}
 
==== Hooks ====
If one of these functions are declared in an Entity Script, the entity will run this function automatically in the appropriate situation.
 
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>DispatchOnPostSpawn</kbd> || <kbd>void DispatchOnPostSpawn()</kbd>
| Called after the entity spawns.<br>If both this function and <code>OnPostSpawn()</code> are defined, this one takes precedence and the other never runs.<br>
{{note|This hook is predefined internally by {{↓|CSimpleCallChainer}} but it won't have any effect until redefined.}}
|-
| <kbd>DispatchPrecache</kbd> || <kbd>void DispatchPrecache()</kbd>
| This is called during entity spawning and after restore to allow scripts to precache any resources they need.<br>If both this function and <code>Precache()</code> are defined, this one takes precedence and the other never runs.<br>
{{note|This hook is predefined internally by {{↓|CSimpleCallChainer}} but it won't have any effect until redefined.}}
|-
| <kbd>Input<''InputName''></kbd> || <kbd>bool Input<''InputName''>()</kbd>
| Called when the entity receives an I/O input that matches the function's name. The name that follows after <code>Input</code> must match the casing, i.e. {{Code|InputFireUser1}} will catch any "FireUser1" inputs but not "fireuser1" inputs from the <kbd>[[ent_fire]]</kbd> command.
 
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.
|-
| <kbd>OnPostSpawn</kbd> || <kbd>void OnPostSpawn()</kbd>
| 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.<br>If both this function and <code>DispatchOnPostSpawn()</code> are defined, that one takes precedence and this one never runs.
|-
| <kbd>Precache</kbd> || <kbd>void Precache()</kbd>
| Called after the script executes. Can be used to call precache functions for models and sounds on map load.<br>If both this function and <code>DispatchPrecache()</code> are defined, that one takes precedence and this one never runs.
|}
 
==== Variables ====
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Instance !! Type !! Description
|-
| <kbd>__vname</kbd> || <kbd>string</kbd>
| Internal name for the current scope.
|-
| <kbd>__vrefs</kbd> || <kbd>int</kbd>
| Reference count for the current scope. This variable is managed by <kbd>VSquirrel_OnCreateScope()</kbd> and <kbd>VSquirrel_OnReleaseScope()</kbd>. {{elaborate}}
|-
|-
| <code>ValidateScriptScope</code>
| <kbd>OnPostSpawnCallChain</kbd> || <kbd>CSimpleCallChainer</kbd>
| <code>bool CBaseEntity::ValidateScriptScope()</code>
| Callchain instance for OnPostSpawn hooks.
| Ensure that an entity's script scope has been created. This should be called before assigning to the entity's scope.
|-
|-
| <code>entindex</code>
| <kbd>PrecacheCallChain</kbd> || <kbd>CSimpleCallChainer</kbd>
| <code>int CBaseEntity::entindex()</code>
| Callchain instance for Precache hooks.
| Returns the entity index.
|}
|}


=== CBaseAnimating ===
=== CBaseAnimating ===
Extends [[#CBaseEntity|CBaseEntity]]
Extends {{↑|CBaseEntity}}


Script handle class for animating entities such as props.
Script handle class for animating entities such as props.


==== 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>GetAttachmentAngles</code>
| <kbd>GetAttachmentAngles</kbd> || <kbd>Vector CBaseAnimating::GetAttachmentAngles(int id)</kbd>
| <code>Vector CBaseAnimating::GetAttachmentAngles(int id)</code>
| Get the attachment id's angles as a p,y,r vector.
| Get the attachment id's angles as a p,y,r vector.
|-
|-
| <code>GetAttachmentOrigin</code>
| <kbd>GetAttachmentOrigin</kbd> || <kbd>Vector CBaseAnimating::GetAttachmentOrigin(int id)</kbd>
| <code>Vector CBaseAnimating::GetAttachmentOrigin(int id)</code>
| Get the attachment id's origin vector
| Get the attachment id's origin vector
|-
|-
| <code>GetObjectScaleLevel</code>
| <kbd>GetObjectScaleLevel</kbd> || <kbd>int CBaseAnimating::GetObjectScaleLevel()</kbd>
| <code>int CBaseAnimating::GetObjectScaleLevel()</code>
| The scale size of the entity
| The scale size of the entity
|-
|-
| <code>IsSequenceFinished</code>
| <kbd>IsSequenceFinished</kbd> || <kbd>bool CBaseAnimating::IsSequenceFinished()</kbd>
| <code>bool CBaseAnimating::IsSequenceFinished()</code>
| Ask whether the main sequence is done playing
| Ask whether the main sequence is done playing
|-
|-
| <code>LookupAttachment</code>
| <kbd>LookupAttachment</kbd> || <kbd>int CBaseAnimating::LookupAttachment(string)</kbd>
| <code>int CBaseAnimating::LookupAttachment(string)</code>
| Get the ID for the named attachment.
| Get the ID for the named attachment.
|-
|-
| <code>SetBodygroup</code>
| <kbd>SetBodygroup</kbd> || <kbd>void CBaseAnimating::SetBodygroup(int group, int index)</kbd>
| <code>void CBaseAnimating::SetBodygroup(int group, int index)</code>
| Sets a bodygroup. Group is the index for the desired group, and index is the desired part to use.
| Sets a bodygroup. Group is the index for the desired group, and index is the desired part to use.
|}
|}


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


==== 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 CBaseFlex::GetCurrentScene()</kbd>
| <code>handle CBaseFlex::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 CBaseFlex::GetSceneByIndex(int)</kbd>
| <code>handle CBaseFlex::GetSceneByIndex(int)</code>
| Returns the instance of the scene entity at the specified index.
| Returns the instance of the scene entity at the specified index.
|}
|}


=== CBasePlayer ===
=== CBasePlayer ===
Extends [[#CBaseAnimating|CBaseAnimating]]
Extends {{↑|CBaseAnimating}}


Script handle class for [[player]] entities.


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>IsNoclipping</code>
| <kbd>IsNoclipping</kbd> || <kbd>bool CBasePlayer::IsNoclipping()</kbd>
| <code>bool CBasePlayer::IsNoclipping()</code>
| Returns true if the player is in noclip mode.
| Returns true if the player is in noclip mode.
|}
|}


=== CEntities ===
=== CEntities ===
Script instance: <code>Entities</code>
Script instance: <code>Entities</code>


An interface to find and iterate over the script handles for the entities in play.  
An interface to find and iterate over the script handles for the entities in play. To iterate over a set of entities, pass <kbd>null</kbd> 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 [[Entity_index|entity index]] is used to determine the order of the search; any entity with an entity index smaller than the one in ''previous'' is skipped over. {{confirm}}


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. Example:
The following are two equivalent examples and iterate over all entities with the name "entityname":
 
{| width=100%
|- style="vertical-align:top;
|
<source lang=cpp>
<source lang=cpp>
//The first way
local ent = null;
local ent = null;     //The variable name "ent" is arbitrary.
while ( ent = Entities.FindByName(ent, "entityname") )
while(ent = Entities.FindByName(ent, "entityname"))     //Indeed, we mean '=' and not '==' ! The loop aborts if "ent" becomes null.
{
{
   //...    //In every iteration, "ent" is not null.
   // ...
}
}
 
</source>
//The second way
|
for(local ent;ent = Entities.FindByName(ent, "entityname");)    //The variable name "ent" is arbitrary. Indeed, we mean '=' and not '==' ! The loop aborts if "ent" becomes null. (All the semicolons are correctly placed)
<source lang=cpp>
for (local ent; ent = Entities.FindByName(ent, "entityname"); )
{
{
   //...    //In every iteration, "ent" is not null.
   // ...
}
}
</source>
</source>
|}


{{Note |
* The variable name <kbd>ent</kbd> is arbitrary.
* Indeed, we mean "{{=}}" and not "{{=}}{{=}}" in the loop conditions! The loops end if <kbd>ent</kbd> becomes <kbd>null</kbd>, which happens when no matching entities have an [[entity index]] higher to the one in ''previous'' parameter.
* In every iteration, "ent" is not null.
* Semicolons are optional, except in the header of the <kbd>for</kbd> statement.
}}


==== 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>CreateByClassname</code>
| <kbd>CreateByClassname</kbd> || <kbd>handle CEntities::CreateByClassname(string)</kbd>
| <code>handle CEntities::CreateByClassname(string)</code>
| Creates an entity by classname
| Creates an entity by classname
|-
|-
| <code>FindByClassname</code>
| <kbd>FindByClassname</kbd> || <kbd>handle CEntities::FindByClassname(handle start_ent, string classname)</kbd>
| <code>handle CEntities::FindByClassname(handle start_ent, string classname)</code>
| Find entities by class name. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Find entities by class name. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
|-
|-
| <code>FindByClassnameNearest</code>
| <kbd>FindByClassnameNearest</kbd> || <kbd>handle CEntities::FindByClassnameNearest(string classname, Vector loc, float radius)</kbd>
| <code>handle CEntities::FindByClassnameNearest(string classname, Vector loc, float radius)</code>
| Find entities by class name nearest to a point.
| Find entities by class name nearest to a point.
|-
|-
| <code>FindByClassnameWithin</code>
| <kbd>FindByClassnameWithin</kbd> || <kbd>handle CEntities::FindByClassnameWithin(handle start_ent, string classname, Vector loc, float radius)</kbd>
| <code>handle CEntities::FindByClassnameWithin(handle start_ent, string classname, Vector loc, float radius)</code>
| Find entities by class name within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Find entities by class name within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
|-
|-
| <code>FindByModel</code>
| <kbd>FindByModel</kbd> || <kbd>handle CEntities::FindByModel(handle start_ent, string model)</kbd>
| <code>handle CEntities::FindByModel(handle start_ent, string model)</code>
| Find entities by model name. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Find entities by model name. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
|-
|-
| <code>FindByName</code>
| <kbd>FindByName</kbd> || <kbd>handle CEntities::FindByName(handle start_ent, string targetname)</kbd>
| <code>handle CEntities::FindByName(handle start_ent, string targetname)</code>
| Find entities by name (including wildcards). Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
| Find entities by name (including wildcards). Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
|-
|-
| <code>FindByNameNearest</code>
| <kbd>FindByNameNearest</kbd> || <kbd>handle CEntities::FindByNameNearest(string targetname, Vector loc, float radius)</kbd>
| <code>handle CEntities::FindByNameNearest(string targetname, Vector loc, float radius)</code>
| Find entities by name nearest to a point.
| Find entities by name nearest to a point.
|-
|-
| <code>FindByNameWithin</code>
| <kbd>FindByNameWithin</kbd> || <kbd>handle CEntities::FindByNameWithin(handle, string, Vector loc, float radius)</kbd>
| <code>handle CEntities::FindByNameWithin(handle, string, Vector loc, float radius)</code>
| Find entities by name within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Find entities by name within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
|-
|-
| <code>FindByTarget</code>
| <kbd>FindByTarget</kbd> || <kbd>handle CEntities::FindByTarget(handle start_ent, string targetname)</kbd>
| <code>handle CEntities::FindByTarget(handle start_ent, string targetname)</code>
| Find entities with a specific <code>target</code> keyvalue. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Find entities with a specific <code>target</code> keyvalue. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
|-
|-
| <code>FindInSphere</code>
| <kbd>FindInSphere</kbd> || <kbd>handle CEntities::FindInSphere(handle start_ent, Vector loc, float radius)</kbd>
| <code>handle CEntities::FindInSphere(handle start_ent, Vector loc, float radius)</code>
| Find entities within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
| Find entities within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
|-
|-
| <code>First</code>
| <kbd>First</kbd> || <kbd>handle CEntities::First()</kbd>
| <code>handle CEntities::First()</code>
| Begin an iteration over the list of entities. Equivalent to Next(null).
| Begin an iteration over the list of entities. Equivalent to Next(null).
|-
|-
| <code>Next</code>
| <kbd>Next</kbd> || <kbd>handle CEntities::Next(handle)</kbd>
| <code>handle CEntities::Next(handle)</code>
| Continue an iteration over the list of entities, providing reference to a previously found entity.
| Continue an iteration over the list of entities, providing reference to a previously found entity.
|}
|}


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


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


==== 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>SpawnEntity</code>
| <kbd>SpawnEntity</kbd> || <kbd>void CEnvEntityMaker::SpawnEntity()</kbd>
| <code>void CEnvEntityMaker::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 CEnvEntityMaker::SpawnEntityAtEntityOrigin(handle)</kbd>
| <code>void CEnvEntityMaker::SpawnEntityAtEntityOrigin(handle)</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 CEnvEntityMaker::SpawnEntityAtLocation(Vector, Vector)</kbd>
| <code>void CEnvEntityMaker::SpawnEntityAtLocation(Vector, Vector)</code>
| Create an entity at a specified location and orientaton, orientation is Euler angle in degrees (pitch, yaw, roll)
| Create an entity at a specified location and orientaton, orientation is Euler angle in degrees (pitch, yaw, roll)
|-
|-
| <code>SpawnEntityAtNamedEntityOrigin</code>
| <kbd>SpawnEntityAtNamedEntityOrigin</kbd> || <kbd>void CEnvEntityMaker::SpawnEntityAtNamedEntityOrigin(string)</kbd>
| <code>void CEnvEntityMaker::SpawnEntityAtNamedEntityOrigin(string)</code>
| Create an entity at the location of a named entity
| Create an entity at the location of a named entity
|}
|}


=== CLinkedPortalDoor ===
=== CLinkedPortalDoor ===
{{todo}}
Extends {{↑|CBaseAnimating}}


Script handle class for [[linked_portal_door]].


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>GetPartnerInstance</code>
| <kbd>GetPartnerInstance</kbd> || <kbd>handle CLinkedPortalDoor::GetPartnerInstance()</kbd>
| <code>handle CLinkedPortalDoor::GetPartnerInstance()</code>
| Get the instance handle of the door's linked partner
| Get the instance handle of the door's linked partner
|-
|-
| <code>GetPartnername</code>
| <kbd>GetPartnername</kbd> || <kbd>string CLinkedPortalDoor::GetPartnername()</kbd>
| <code>string CLinkedPortalDoor::GetPartnername()</code>
| Returns the partnername of the door.
| Returns the partnername of the door.
|}
|}


=== CPropLinkedPortalDoor ===
Extends {{↑|CLinkedPortalDoor}}
Script handle class for [[prop_linked_portal_door]]. Has the same methods as <kbd>CLinkedPortalDoor</kbd>.
=== CLogicScript ===
Extends {{↑|CBaseEntity}}
Script handle class for [[logic_script]].
==== Functions ====
{| class="standard-table" style="width: 100%;"
! Function !! Signature !! Description
|-
| <kbd>__AppendToScriptGroup</kbd> || <kbd>void __AppendToScriptGroup(string ''name'')</kbd>
| Internal function used for gathering the entities defined by the entity group keyvalues. It is only briefly defined while the entity is spawning, then it is removed.
|}
==== Variables ====
{| class="standard-table" style="width: 100%;"
! Instance !! Type !! Description
|-
| <kbd>EntityGroup</kbd> || <kbd>array</kbd>
| Array containing every entity set by this <kbd>logic_script</kbd>'s <code>Group</code> keyvalues. This variable is only defined if one or more of those keyvalues have been defined.
|}


=== CPlayerVoiceListener ===
=== CPlayerVoiceListener ===
{{todo}}
Extends [[CAutoGameSystem]]


Maintains data about voice communications from various players so that the server can react to it.


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>GetPlayerSpeechDuration</code>
| <kbd>GetPlayerSpeechDuration</kbd> || <kbd>float CPlayerVoiceListener::GetPlayerSpeechDuration(int)</kbd>
| <code>float CPlayerVoiceListener::GetPlayerSpeechDuration(int)</code>
| Returns the number of seconds the player has been continuously speaking.
| Returns the number of seconds the player has been continuously speaking.
|-
|-
| <code>IsPlayerSpeaking</code>
| <kbd>IsPlayerSpeaking</kbd> || <kbd>bool CPlayerVoiceListener::IsPlayerSpeaking(int)</kbd>
| <code>bool CPlayerVoiceListener::IsPlayerSpeaking(int)</code>
| Returns whether the player specified is speaking.
| Returns whether the player specified is speaking.
|}
|}


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


Script handle class for [[point_template]].
Script handle class for [[point_template]].
==== Functions ====
{| class="standard-table" style="width: 100%;"
! Function !! Signature !! Description
|-
| <kbd>__ExecutePreSpawn</kbd> || <kbd>table<nowiki>|</nowiki>null __ExecutePreSpawn(handle ''entity'')</kbd>
| Internal function executed when a spawner on the server is getting ready to prespawn an entity. It calls this function, sending the entity that it's preparing to spawn.
If the <code>PreSpawnInstance</code> hook is defined, this function will run that hook with the provided entity parameter.
|-
| <kbd>__FinishSpawn</kbd> || <kbd>void __FinishSpawn()</kbd>
| Internal function executed after the entity finishes spawning. Sets <code>__EntityMakerResult</code> to <code>null</code>.
|}
==== Variables ====
{| class="standard-table" style="width: 100%;"
! Instance !! Type !! Description
|-
| <kbd>__EntityMakerResult</kbd> || <kbd>table</kbd>
| Contains the entity handle for the entity that should spawn. This only exists while an entity is in the process of being spawned (it gets deleted afterwards), meaning this is only accessible in the <code>PreSpawnInstance</code> or <code>PostSpawn</code> hooks.
|}


==== Hooks ====
==== Hooks ====


;<code>table PreSpawnInstance(string ''entityClass'', string ''entityName'')</code>
{| class="standard-table" style="width: 100%;"
:If this is defined, it will be called right before the entity is created, and any KeyValues returned will be assigned to the entity.
|- style="position:sticky; z-index:10; top:0"
 
! Function !! Signature !! Description
<source lang="cpp">function PreSpawnInstance( entityClass, entityName )
|-
| <kbd>PreSpawnInstance</kbd> || <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.
{{Expand|title=Example|<source lang="cpp">
function PreSpawnInstance( entityClass, entityName )
{
{
local keyvalues =
local keyvalues =
Line 509: Line 524:
}
}
return keyvalues
return keyvalues
}
}
</source>
</source>
}}
|-
| <kbd>PostSpawn</kbd> || <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.
{{Expand|title=Example|<source lang="cpp">
function PostSpawn( entities )
{
foreach( name, handle in entities )
{
printl( name + ": " + handle )
}
}
</source>
}}
|}
===== Example =====
Spawned entities can be accessed synchronously in script by using an entity maker. The following generalised example creates a global <code>SpawnMyEntity()</code> function which spawns and returns the templated entity. It can be modified to support multiple templated entities.
{{Expand|
<source lang="cpp">
m_hSpawnedEntity <- null;
m_KeyValues <- null;


;<code>void PostSpawn(table ''entities'')</code>
m_hSpawner <- Entities.CreateByClassname( "env_entity_maker" );
: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.  
m_hSpawner.__KeyValueFromString( "EntityTemplate", self.GetName() );


<source lang="cpp">function PostSpawn( entities )
function PreSpawnInstance( classname, targetname )
{
{
foreach( name, handle in entities )
return m_KeyValues;
}
 
function PostSpawn( entities )
{
foreach ( targetname, entity in entities )
{
{
printl( name + ": " + handle )
m_hSpawnedEntity = entity;
break;
}
}
}
}
::SpawnMyEntity <- function( keyvalues = null )
{
m_KeyValues = keyvalues;
m_hSpawner.SpawnEntity();
return m_hSpawnedEntity;
}.bindenv(this)
</source>
</source>


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


=== CPortal_Player ===
=== CPortal_Player ===
{{todo}}
Extends {{↑|CBasePlayer}}


Script handle class for [[Player_(Portal_series)|player]] entities of Portal.


==== 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>GetWheatleyMonitorDestructionCount</code>
| <kbd>GetWheatleyMonitorDestructionCount</kbd> || <kbd>int CPortal_Player::GetWheatleyMonitorDestructionCount()</kbd>
| <code>int CPortal_Player::GetWheatleyMonitorDestructionCount()</code>
| Get number of wheatley monitors destroyed by the player.
| Get number of wheatley monitors destroyed by the player.
|-
|-
| <code>IncWheatleyMonitorDestructionCount</code>
| <kbd>IncWheatleyMonitorDestructionCount</kbd> || <kbd>void CPortal_Player::IncWheatleyMonitorDestructionCount()</kbd>
| <code>void CPortal_Player::IncWheatleyMonitorDestructionCount()</code>
| Set number of wheatley monitors destroyed by the player.
| Set number of wheatley monitors destroyed by the player.
|-
|-
| <code>TurnOffPotatos</code>
| <kbd>TurnOffPotatos</kbd> || <kbd>void CPortal_Player::TurnOffPotatos()</kbd>
| <code>void CPortal_Player::TurnOffPotatos()</code>
| Turns Off the Potatos material light
| Turns Off the Potatos material light
|-
|-
| <code>TurnOnPotatos</code>
| <kbd>TurnOnPotatos</kbd> || <kbd>void CPortal_Player::TurnOnPotatos()</kbd>
| <code>void CPortal_Player::TurnOnPotatos()</code>
| Turns On the Potatos material light
| Turns On the Potatos material light
|}
|}
=== CPropLinkedPortalDoor ===
{{todo}}
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function
! Signature
! Description
|-
| <code>GetPartnerInstance</code>
| <code>handle CPropLinkedPortalDoor::GetPartnerInstance()</code>
| Get the instance handle of the door's linked partner
|-
| <code>GetPartnername</code>
| <code>string CPropLinkedPortalDoor::GetPartnername()</code>
| Returns the partnername of the door.
|}


=== CSceneEntity ===
=== CSceneEntity ===
Extends [[#CBaseEntity|CBaseEntity]]
Extends {{↑|CBaseEntity}}
 


==== 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>AddBroadcastTeamTarget</code>
| <kbd>AddBroadcastTeamTarget</kbd> || <kbd>void CSceneEntity::AddBroadcastTeamTarget(int)</kbd>
| <code>void CSceneEntity::AddBroadcastTeamTarget(int)</code>
| Adds a team (by index) to the broadcast list
| Adds a team (by index) to the broadcast list
|-
|-
| <code>EstimateLength</code>
| <kbd>EstimateLength</kbd> || <kbd>float CSceneEntity::EstimateLength()</kbd>
| <code>float CSceneEntity::EstimateLength()</code>
| Returns length of this scene in seconds.
| Returns length of this scene in seconds.
|-
|-
| <code>FindNamedEntity</code>
| <kbd>FindNamedEntity</kbd> || <kbd>handle CSceneEntity::FindNamedEntity(string)</kbd>
| <code>handle CSceneEntity::FindNamedEntity(string)</code>
| given an entity reference, such as !target, get actual entity from scene object
| given an entity reference, such as !target, get actual entity from scene object
|-
|-
| <code>IsPaused</code>
| <kbd>IsPaused</kbd> || <kbd>bool CSceneEntity::IsPaused()</kbd>
| <code>bool CSceneEntity::IsPaused()</code>
| If this scene is currently paused.
| If this scene is currently paused.
|-
|-
| <code>IsPlayingBack</code>
| <kbd>IsPlayingBack</kbd> || <kbd>bool CSceneEntity::IsPlayingBack()</kbd>
| <code>bool CSceneEntity::IsPlayingBack()</code>
| If this scene is currently playing.
| If this scene is currently playing.
|-
|-
| <code>LoadSceneFromString</code>
| <kbd>LoadSceneFromString</kbd> || <kbd>bool CSceneEntity::LoadSceneFromString(string, string)</kbd>
| <code>bool CSceneEntity::LoadSceneFromString(string, string)</code>
| given a dummy scene name and a vcd string, load the scene
| given a dummy scene name and a vcd string, load the scene
|-
|-
| <code>RemoveBroadcastTeamTarget</code>
| <kbd>RemoveBroadcastTeamTarget</kbd> || <kbd>void CSceneEntity::RemoveBroadcastTeamTarget(int)</kbd>
| <code>void CSceneEntity::RemoveBroadcastTeamTarget(int)</code>
| Removes a team (by index) from the broadcast list
| Removes a team (by index) from the broadcast list
|}
|}


=== CScriptKeyValues ===
=== CScriptKeyValues ===
Script handle representation of a models [[$keyvalues]] block.
Script handle representation of a models [[$keyvalues]] block.
Sub keys are instances of the same class.
Sub keys are instances of the same class.


==== 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>FindKey</code>
| <kbd>FindKey</kbd> || <kbd>handle CScriptKeyValues::FindKey(string)</kbd>
| <code>handle CScriptKeyValues::FindKey(string)</code>
| Given a KeyValues object and a key name, find a KeyValues object associated with the key name
| Given a KeyValues object and a key name, find a KeyValues object associated with the key name
|-
|-
| <code>GetFirstSubKey</code>
| <kbd>GetFirstSubKey</kbd> || <kbd>handle CScriptKeyValues::GetFirstSubKey()</kbd>
| <code>handle CScriptKeyValues::GetFirstSubKey()</code>
| Given a KeyValues object, return the first sub key object
| Given a KeyValues object, return the first sub key object
|-
|-
| <code>GetKeyBool</code>
| <kbd>GetKeyBool</kbd> || <kbd>bool CScriptKeyValues::GetKeyBool(string)</kbd>
| <code>bool CScriptKeyValues::GetKeyBool(string)</code>
| Given a KeyValues object and a key name, return associated bool value
| Given a KeyValues object and a key name, return associated bool value
|-
|-
| <code>GetKeyFloat</code>
| <kbd>GetKeyFloat</kbd> || <kbd>float CScriptKeyValues::GetKeyFloat(string)</kbd>
| <code>float CScriptKeyValues::GetKeyFloat(string)</code>
| Given a KeyValues object and a key name, return associated float value
| Given a KeyValues object and a key name, return associated float value
|-
|-
| <code>GetKeyInt</code>
| <kbd>GetKeyInt</kbd> || <kbd>int CScriptKeyValues::GetKeyInt(string)</kbd>
| <code>int CScriptKeyValues::GetKeyInt(string)</code>
| Given a KeyValues object and a key name, return associated integer value
| Given a KeyValues object and a key name, return associated integer value
|-
|-
| <code>GetKeyString</code>
| <kbd>GetKeyString</kbd> || <kbd>string CScriptKeyValues::GetKeyString(string)</kbd>
| <code>string CScriptKeyValues::GetKeyString(string)</code>
| Given a KeyValues object and a key name, return associated string value
| Given a KeyValues object and a key name, return associated string value
|-
|-
| <code>GetNextKey</code>
| <kbd>GetNextKey</kbd> || <kbd>handle CScriptKeyValues::GetNextKey()</kbd>
| <code>handle CScriptKeyValues::GetNextKey()</code>
| Given a KeyValues object, return the next key object in a sub key group
| Given a KeyValues object, return the next key object in a sub key group
|-
|-
| <code>IsKeyEmpty</code>
| <kbd>IsKeyEmpty</kbd> || <kbd>bool CScriptKeyValues::IsKeyEmpty(string)</kbd>
| <code>bool CScriptKeyValues::IsKeyEmpty(string)</code>
| Given a KeyValues object and a key name, return true if key name has no value
| Given a KeyValues object and a key name, return true if key name has no value
|-
|-
| <code>ReleaseKeyValues</code>
| <kbd>ReleaseKeyValues</kbd> || <kbd>void CScriptKeyValues::ReleaseKeyValues()</kbd>
| <code>void CScriptKeyValues::ReleaseKeyValues()</code>
| Given a root KeyValues object, release its contents
| Given a root KeyValues object, release its contents
|}
|}


=== CTriggerCamera ===
=== CTriggerCamera ===
Extends [[#CBaseEntity|CBaseEntity]]
Extends {{↑|CBaseEntity}}


Script handle class for [[point_viewcontrol]].


==== Methods ====
==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>GetFov</code>
| <kbd>GetFov</kbd> || <kbd>int CTriggerCamera::GetFov()</kbd>
| <code>int CTriggerCamera::GetFov()</code>
| get camera's current fov setting as integer
| get camera's current fov setting as integer
|-
|-
| <code>SetFov</code>
| <kbd>SetFov</kbd> || <kbd>void CTriggerCamera::SetFov(int, float)</kbd>
| <code>void CTriggerCamera::SetFov(int, float)</code>
| set camera's current fov in integer degrees and fov change rate as float
| set camera's current fov in integer degrees and fov change rate as float
|}
|}


==== Hooks ====
{| class="standard-table" style="width: 100%;"
! Function !! Signature !! Description
|-
| <kbd>ScriptStartCameraShot</kbd> || <kbd>void ScriptStartCameraShot(string ''shotType'', handle ''sceneEntity'', handle ''actor1'', handle ''actor2'', float ''duration'')</kbd>
| ''Called from SceneEntity in response to a CChoreoEvent::CAMERA sent from a VCD.'' {{todo}}
|}


=== Math ===
=== CCallChainer ===
The built-in [http://www.squirrel-lang.org/mainsite/doc/sqstdlib2.html#d0e1519 Squirrel math library].
'''CCallChainer''' objects collect all functions with a matching prefix in a given scope, then inserts it all into the <code>chains</code> table with the prefix removed. All collected unprefixed functions can then be called in a chain using the class's <code>Call()</code> method, given the method's ''event'' argument matches the functions' name.


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


==== Methods ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
! Function !! Signature !! Description
! Signature
! Description
|-
|-
| <code>abs</code>
| <kbd>constructor</kbd> || <kbd>CCallChainer(string ''functionPrefix'', table ''scope'' = null)</kbd>
| <code> int abs(float ''x'')</code>
| Creates a CCallChainer object that'll collect functions that have a matching prefix in the given scope.
| Returns the absolute value of <code>x</code> as an integer.
|-
|-
| <code>acos</code>
| <kbd>PostScriptExecute</kbd> || <kbd>void CCallChainer::PostScriptExecute()</kbd>
| <code> float acos(float ''x'')</code>
| Search for all non-native functions with matching prefixes, then push them into the <code>chains</code> table.
| Returns the arccosine of <code>x</code>.
|-
|-
| <code>asin</code>
| <kbd>Call</kbd> || <kbd>bool CCallChainer::Call(string ''event'', any ...)</kbd>
| <code> float asin(float ''x'')</code>
| Find an unprefixed function name in the <code>chains</code> table and call it with the given arguments.
| Returns the arcsine of <code>x</code>.
|}
 
==== 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</code> table. Set by the constructor.
|-
| <kbd>scope</kbd> || <kbd>table</kbd>
| If set, seek functions in this scope instead. Set by the constructor.
|}
 
=== CSimpleCallChainer ===
Intended to be simpler to use than {{↑|CCallChainer}}, the class '''CSimpleCallChainer''' holds only a single chain of functions inside an array instead of multiple inside a table. As such, its <code>Call()</code> method does not need a function's name.
 
This class is also used internally by these {{↑|Hooks|CBaseEntity hooks}}: <code>Precache()</code> and <code>OnPostSpawn()</code>.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
! Function !! Signature !! Description
|-
|-
| <code>atan</code>
| <kbd>constructor</kbd> || <kbd>CSimpleCallChainer(string ''functionPrefix'', table ''scope'' = null, exactMatch = false)</kbd>
| <code> float atan(float ''x'')</code>
| Creates a CSimpleCallChainer object that'll collect functions that have a matching prefix in the given scope, unless it seek for an exact name match. Also automatically exposes two bound global functions to dispatch to this object: <code>DispatchPrecache()</code> and <code>DispatchOnPostSpawn()</code>.
| Returns the arctangent of <code>x</code>.
|-
|-
| <code>atan2</code>
| <kbd>PostScriptExecute</kbd> || <kbd>void CSimpleCallChainer::PostScriptExecute()</kbd>
| <code> float atan2(float ''x'', float ''y'')</code>
| Begin searching for all non-native functions with matching prefixes, then push them into the <code>chain</code> array.
| Returns the arctangent of <code>x/y</code>.
|-
|-
| <code>ceil</code>
| <kbd>Call</kbd> || <kbd>bool CSimpleCallChainer::Call(any ...)</kbd>
| <code> float ceil(float ''x'')</code>
| Call all functions inside the <code>chain</code> array with the given arguments.
| Returns a float value representing the smallest integer that is greater than or equal to <code>x</code>.
|}
 
==== Members ====
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Instance !! Type !! Description
|-
|-
| <code>cos</code>
| <kbd>chain</kbd> || <kbd>array</kbd>
| <code> float cos(float ''x'')</code>
| All functions to be called by the <code>Call()</code> method.
| Returns the cosine of <code>x</code>.
|-
|-
| <code>exp</code>
| <kbd>exactMatch</kbd> || <kbd>bool</kbd>
| <code> float exp(float ''x'')</code>
| If set, names of non-native functions and <code>prefix</code> must be an exact match.  Set by the constructor.
| Returns the exponential value (<code>e^x</code>) of the float parameter <code>x</code>.
|-
|-
| <code>fabs</code>
| <kbd>prefix</kbd> || <kbd>string</kbd>
| <code> float fabs(float ''x'')</code>
| Prefix that functions should have to be added into the <code>chain</code> array. Set by the constructor.
| Returns the absolute value of <code>x</code> as a float.
|-
|-
| <code>floor</code>
| <kbd>scope</kbd> || <kbd>table</kbd>
| <code> float floor(float ''x'')</code>
| If set, seek functions in this scope instead. Set by the constructor.
| Returns a float value representing the largest integer that is less than or equal to <code>x</code>.
|}
 
=== LateBinder ===
Late binding: allows a table to refer to parts of itself, it's children, it's owner, and then have the references fixed up after it's fully parsed.
 
{{expand|title=Usage example|
<source lang=cpp>
// Usage:
lateBinder <- LateBinder();
lateBinder.Begin( this );
 
Test1 <-
  Foo=1
 
Test2 <-
  FooFoo = "I'm foo foo"
  BarBar="@Test1.Foo"
  SubTable = { boo=[bah, "@Test2.FooFoo", "@Test1.Foo"], booboo2={one=bah, two="@Test2.FooFoo", three="@Test1.Foo"} }
  booboo=[bah, "@Test2.FooFoo", "@Test1.Foo"]
  booboo2={one=bah, two="@Test2.FooFoo", three="@Test1.Foo"}
  bah=wha
 
lateBinder.End();
delete lateBinder;
</source>
}}
 
When End() is called, all of the unresolved symbols in the tables and arrays will be resolved, any left unresolved will become a string prepended with '~', which later code can deal with.
 
==== Methods ====
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
|-
| <code>log</code>
| <kbd>Begin</kbd> || <kbd> void LateBinder::Begin(table ''target'', bool ''log'' = false)</kbd>
| <code> float log(float ''x'')</code>
| {{todo}}
| Returns the natural logarithm of <code>x</code>.
|-
|-
| <code>log10</code>
| <kbd>End</kbd> || <kbd> void LateBinder::End()</kbd>
| <code> float log10(float ''x'')</code>
| {{todo}}
| Returns the logarithm base-10 of <code>x</code>.
|-
|-
| <code>pow</code>
| <kbd>EstablishDelegation</kbd> || <kbd> void LateBinder::EstablishDelegation(table ''parentTable'', table ''childTable'')</kbd>
| <code> float pow(float ''x'', float ''y'')</code>
| {{todo}}
| Returns <code>x</code> raised to the power of <code>y</code>.
|-
|-
| <code>rand</code>
| <kbd>RemoveDelegation</kbd> || <kbd> void LateBinder::EstablishDelegation(table ''parentTable'', table ''childTable'')</kbd>
| <code> int rand()</code>
| {{todo}}
| Returns a pseudorandom integer in the range 0 to <code>RAND_MAX</code>.
|-
|-
| <code>sin</code>
| <kbd>HookRootMetamethod</kbd> || <kbd> void LateBinder::HookRootMetamethod(string ''name'', unknown ''value'')</kbd>
| <code> float sin(float ''x'')</code>
| "private" method. {{todo}}
| Returns the sine of <code>x</code>.
|-
|-
| <code>sqrt</code>
| <kbd>UnhookRootMetamethod</kbd> || <kbd> void LateBinder::UnhookRootMetamethod(string ''name'')</kbd>
| <code> float sqrt(float ''x'')</code>
| {{todo}}
| Returns the square root of <code>x</code>.
|-
|-
| <code>srand</code>
| <kbd>Log</kbd> || <kbd> void LateBinder::Log(string ''string'')</kbd>
| <code> void srand(float ''seed'')</code>
| {{todo}}
| Sets the starting point for generating a series of pseudorandom integers.
|-
|-
| <code>tan</code>
| <kbd>Resolve</kbd> || <kbd> bool LateBinder::Resolve(table ''lookupTable'', table<nowiki>|</nowiki>array ''subTableOrArray'', bool ''throwException'' = false )</kbd>
| <code> float tan(float ''x'')</code>
| {{todo}}
| Returns the tangent of <code>x</code>.
|}
|}


==== Members ====
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Instance !! Type !! Description
|-
| <kbd>m_bindNamesStack</kbd> || <kbd>array</kbd>
| {{todo}}
|-
| <kbd>m_fixupSet</kbd> || <kbd>array</kbd>
| {{todo}}
|-
| <kbd>m_log</kbd> || <kbd>bool</kbd>
| {{todo}}
|-
| <kbd>m_logIndent</kbd> || <kbd>int</kbd>
| {{todo}}
|-
| <kbd>m_targetTable</kbd> || <kbd>table</kbd>
| {{todo}}
|}


=== Vector ===
=== Vector ===
Represents an x/y/z position, returned/passed to many functions. It takes the 3 x/y/z positions as a parameter.<br>
Squirrel equivalent of the C++ [[Vector]] class. A three-dimensional vector with overloaded arithmetic operations for both Vectors and scalar values.  
A few math operations can be applied to vectors - ''+/-'' between any two vectors, and <code>Vector * number</code> in that order only. All three operations return another vector. Other math operations are done with method calls:
 


==== 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
|-
| <kbd>constructor</kbd> || <kbd>Vector(float ''x'' = 0, float ''y'' = 0, float ''z'' = 0)</kbd>
| Creates a new vector with the specified Cartesian coordiantes.
|-
|-
| <code>Cross</code>
| <kbd>Cross</kbd> || <kbd>Vector Vector::Cross(Vector other)</kbd>
| <code>Vector Vector::Cross(Vector other)</code>
| Return the vector cross product - <code>this × other</code>.
| Return the vector cross product - <code>this × other</code>.
|-
|-
| <code>Dot</code>
| <kbd>Dot</kbd> || <kbd>float Vector::Dot(Vector other)</kbd>
| <code>float Vector::Dot(Vector other)</code>
| Return the vector dot product - <code>this · other</code>.
| Return the vector dot product - <code>this · other</code>.
|-
|-
| <code>Length</code>
| <kbd>Length</kbd> || <kbd>float Vector::Length()</kbd>
| <code>float Vector::Length()</code>
| Return the distance from the origin.
| Return the distance from the origin.
|-
|-
| <code>Length2D</code>
| <kbd>Length2D</kbd> || <kbd>float Vector::Length2D()</kbd>
| <code>float Vector::Length2D()</code>
| Return the distance from the origin, ignoring the Z axis.
| Return the distance from the origin, ignoring the Z axis.
|-
|-
| <code>LengthSqr</code>
| <kbd>LengthSqr</kbd> || <kbd>float Vector::LengthSqr()</kbd>
| <code>float Vector::LengthSqr()</code>
| Return the distance from the origin, but squared. This is faster to compute since a square root isn\'t required.
| Return the distance from the origin, but squared. This is faster to compute since a square root isn\'t required.
|-
|-
| <code>Length2DSqr</code>
| <kbd>Length2DSqr</kbd> || <kbd>float Vector::Length2DSqr()</kbd>
| <code>float Vector::Length2DSqr()</code>
| Return the distance from the origin, ignoring the Z axis and squared. This is faster to compute since a square root isn\'t required.
| Return the distance from the origin, ignoring the Z axis and squared. This is faster to compute since a square root isn\'t required.
|-
|-
| <code>Norm</code>
| <kbd>Norm</kbd> || <kbd>float Vector::Norm()</kbd>
| <code>float Vector::Norm()</code>
| Modify the vector to have a length of 1, and return its original length.
| Modify the vector to have a length of 1, and return its original length.
|-
|-
| <code>ToKVString</code>
| <kbd>ToKVString</kbd> || <kbd>string Vector::ToKVString()</kbd>
| <code>string Vector::ToKVString()</code>
| Return a string in the form "X Y Z".
| Return a string in the form "X Y Z".
|}
|}


==== Metamethods ====
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>_add</kbd> || <kbd>Vector Vector::_add(Vector ''add'')</kbd>
| Overload for the <kbd>+</kbd> operator - <code>Vector + Vector</code>. Adds each value of the provided vector to the current vector.
|-
| <kbd>_sub</kbd> || <kbd>Vector Vector::_sub(Vector ''add'')</kbd>
| Overload for the <kbd>-</kbd> operator - <code>Vector - Vector</code>. Subtracts each value of the provided vector from the current vector.
|-
| <kbd>_mul</kbd> || <kbd>Vector Vector::_mul(float ''scale'')</kbd>
| Overload for the <kbd>*</kbd> operator - <code>Vector * number</code>. Multiplies each value in the vector by this scale factor.
{{note|The number ''must'' come after the vector.}}
|-
| <kbd>_typeof</kbd> || <kbd>string Vector::_typeof()</kbd>
| Overload for the <code>typeof</code> operator. Returns <kbd>"Vector"</kbd>.
|-
| <kbd>_tostring</kbd> || <kbd>string Vector::_tostring()</kbd>
| Overload for string conversion. Returns a string in the form "<kbd>(vector : (X, Y, Z))</kbd>".
|-
| <kbd>_nexti</kbd> || <kbd>string Vector::_nexti()</kbd>
| Overload for iteration. {{todo}}
|-
| <kbd>_get</kbd> || <kbd>string Vector::_get()</kbd>
| Overload for accessing. {{todo}}
|-
| <kbd>_set</kbd> || <kbd>string Vector::_set()</kbd>
| Overload for setting. {{todo}}
|}
==== Members ====
{| class="standard-table" style="width: 100%;"
! Instance !! Type !! Description
|-
| <kbd>x</kbd> || <kbd>float</kbd>
| Cartesian X axis.
|-
| <kbd>y</kbd> || <kbd>float</kbd>
| Cartesian Y axis.
|-
| <kbd>z</kbd> || <kbd>float</kbd>
| Cartesian Z axis.
|}
== Global functions ==
=== Printing and drawing ===
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>DebugDrawBox</kbd> || <kbd>void DebugDrawBox(Vector origin, Vector mins, Vector maxs, int r, int g, int b, int alpha, float duration)</kbd>
| Draw a debug box, for visualizing code. It's positioned at <code>origin</code>, with the dimensions <code>mins</code>/<code>maxs</code> Developer must be on to show this, and it'll stay around for <code>duration</code> seconds (or 1 frame if -1.0). The color ranges from 0-255.
|-
| <kbd>DebugDrawLine</kbd> || <kbd>void DebugDrawLine(Vector start, Vector end, int r, int g, int b, bool hitTest, float duration)</kbd>
| Draw a debug line, for visualizing code. Developer must be on to show this, and it'll stay around for <code>duration</code> seconds (or 1 frame if -1.0). The color ranges from 0-255.
|-
| <kbd>Msg</kbd> || <kbd>void Msg(string ''text'')</kbd>
| Equivalent to <code>print</code>
|-
| <kbd>printl</kbd> || <kbd>void printl(string ''text'')</kbd>
| Prints the given message to the developer console with newline. Equivalent to <code>print(message + "\n")</code>
|-
| <kbd>ShowMessage</kbd> || <kbd>void ShowMessage(string)</kbd>
| Print a hud message on all clients. {{Note|Uses localized strings as found in <code>/scripts/titles.txt</code> {{confirm}}}}
|-
| <kbd>__DumpScope</kbd> || <kbd>void __DumpScope(int ''indentation'', table ''scope'')</kbd>
| Dumps the contents of ''scope''.
|}
=== Singleplayer only ===
These functions can only be used in singleplayer games, and may cause errors if used in multiplayer.
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>GetPlayer</kbd> || <kbd>handle GetPlayer()</kbd>
| Returns the player.
|-
| <kbd>GivePlayerPortalgun</kbd> || <kbd>void GivePlayerPortalgun()</kbd>
| Equips the player with a blue-only portalgun.
|-
| <kbd>PrecacheMovie</kbd> || <kbd>void PrecacheMovie(string)</kbd>
| Precaches a named movie. Only valid to call within the entity's 'Precache' function called on mapspawn.
|-
| <kbd>ScriptShowHudMessageAll</kbd> || <kbd>void ScriptShowHudMessageAll(string, float)</kbd>
| Show center print text message for specified number of seconds.
|-
| <kbd>ScriptSteamShowURL</kbd> || <kbd>bool ScriptSteamShowURL(string)</kbd>
| Bring up the steam overlay and shows the specified URL.  (Full address with protocol type is required, e.g. http://www.steamgames.com/)
|-
| <kbd>TryDLC1InstalledOrCatch</kbd> || <kbd>void TryDLC1InstalledOrCatch()</kbd>
| Throws an exception if the Peer Review DLC isn't installed. Useless in the current PC version of the game, as Peer Review will always be present.
|-
| <kbd>UpgradePlayerPortalgun</kbd> || <kbd>void UpgradePlayerPortalgun()</kbd>
| Upgrades the player's portalgun to shoot orange portals.
|-
| <kbd>UpgradePlayerPotatogun</kbd> || <kbd>void UpgradePlayerPotatogun()</kbd>
| Upgrades the player's portalgun to shoot orange portals and have PotatOS impaled on it.
|}
=== Multiplayer only ===
These functions can only be used in multiplayer games, and may cause errors if used in singleplayer.


== Other functions ==
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
| <kbd>AddBranchLevelName</kbd> || <kbd>void AddBranchLevelName(int, string)</kbd>
| Adds a level to the specified branch's list. {{note|In co-op maps, this function must be called at least once or players will not be able to move.}}
|-
| <kbd>AddCoopCreditsName</kbd> || <kbd>void AddCoopCreditsName(string)</kbd>
| Adds a name to the coop credit's list.
|-
| <kbd>AddGladosSpokenFlags</kbd> || <kbd>void AddGladosSpokenFlags(int, int)</kbd>
| Adds bit flags for specific lines that are tracked per session.
|-
| <kbd>CoopGladosBlowUpBots</kbd> || <kbd>void CoopGladosBlowUpBots()</kbd>
| Blows up both robots and prevents respawning.
|-
| <kbd>CoopGetNumPortalsPlaced</kbd> || <kbd>int CoopGetNumPortalsPlaced()</kbd>
| Returns the number of portals the players have placed so far.
|-
| <kbd>CoopGetLevelsCompletedThisBranch</kbd> || <kbd>int CoopGetLevelsCompletedThisBranch()</kbd>
| Returns the number of levels the players have completed in their run of the current branch.
|-
| <kbd>CoopGetBranchTotalLevelCount</kbd> || <kbd>int CoopGetBranchTotalLevelCount()</kbd>
| Returns the number of levels in the current branch.
|-
|-
| <code>Assert</code>
| <kbd>CoopSetCameFromLastDLCMap</kbd> || <kbd>void CoopSetCameFromLastDLCMap(bool)</kbd>
| <code>void Assert(''exp'', string ''message'' = null)</code>
| Set whether the players came from the last coop DLC map or not.
|-
| <kbd>CoopSetMapRunTime</kbd> || <kbd>void CoopSetMapRunTime(float runLength)</kbd>
| Sets the time to complete a coop map from spawn to completing the puzzle. (Possibly related to the Triple Crown achievement.)
|-
| <kbd>GetBluePlayerIndex</kbd> || <kbd>int GetBluePlayerIndex()</kbd>
| Player index of the blue player.
|-
| <kbd>GetCameFromLastDLCMap</kbd> || <kbd>bool GetCameFromLastDLCMap()</kbd>
| Returns true if coming from the last DLC coop map (as set by <code>CoopSetCameFromLastDLCMap</code>).
|-
| <kbd>GetCoopBranchLevelIndex</kbd> || <kbd>int GetCoopBranchLevelIndex(int)</kbd>
| Given the 'branch' argument, returns the current chosen level.
|-
| <kbd>GetCoopSectionIndex</kbd> || <kbd>int GetCoopSectionIndex()</kbd>
| Section that the coop players have selected to load.
|-
| <kbd>GetGladosSpokenFlags</kbd> || <kbd>int GetGladosSpokenFlags(int)</kbd>
| Returns bit flags for specific lines that are tracked per session.
|-
| <kbd>GetHaveSeenDLCTubesReveal</kbd> || <kbd>bool GetHaveSeenDLCTubesReveal()</kbd>
| Get whether players have seen the DLC tubes reveal this session (as set by <code>SetHaveSeenDLCTubesReveal</code>).
|-
| <kbd>GetHighestActiveBranch</kbd> || <kbd>int GetHighestActiveBranch()</kbd>
| Returns which branches should be available in the hub.
|-
| <kbd>GetNumPlayersConnected</kbd> || <kbd>int GetNumPlayersConnected()</kbd>
| Returns how many players are connected. In normal co-op, this will almost always be 2.
|-
| <kbd>GetOrangePlayerIndex</kbd> || <kbd>int GetOrangePlayerIndex()</kbd>
| Player index of the orange player.
|-
| <kbd>GetPlayerDeathCount</kbd> || <kbd>int GetPlayerDeathCount(int player)</kbd>
| Returns the number of times that a specific player has died in the session.
|-
| <kbd>IsBranchComplete</kbd> || <kbd>bool IsBranchComplete(int course)</kbd>
| Returns true if every level in the course has been completed by either player.
|-
| <kbd>IsLevelComplete</kbd> || <kbd>bool IsLevelComplete(int course, int level)</kbd>
| Returns true if the level in the specified course is completed by either player.
|-
| <kbd>IsLocalSplitScreen</kbd> || <kbd>bool IsLocalSplitScreen()</kbd>
| Returns true if players are in split screen.
|-
| <kbd>IsPlayerBranchComplete</kbd> || <kbd>bool IsPlayerBranchComplete(int player, int course)</kbd>
| Returns true if every level in the course has been completed by the specified player.
|-
| <kbd>IsPlayerLevelComplete</kbd> || <kbd>bool IsPlayerLevelComplete(int, int, int)</kbd>
| Returns true if the level in the specified course is completed by a specific player.
|-
| <kbd>MarkMapComplete</kbd> || <kbd>void MarkMapComplete(string)</kbd>
| Marks a maps a complete for both players.
|-
| <kbd>NotifySpeedRunSuccess</kbd> || <kbd>void NotifySpeedRunSuccess(int runLength, string mapname)</kbd>
| Tells the client that a successful speed run has been completed. (Used for the Triple Crown achievement.)
|-
| <kbd>SaveMPStatsData</kbd> || <kbd>void SaveMPStatsData()</kbd>
| Save the multiplayer stats for the score board.
|-
| <kbd>SetHaveSeenDLCTubesReveal</kbd> || <kbd>void SetHaveSeenDLCTubesReveal()</kbd>
| Set that players have seen the DLC tubes reveal this session.
|}
 
=== Developer only ===
These functions require that the [[developer]] level is set to a value above 0. Otherwise these functions are either undefined, or defined to do nothing.
 
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>Document</kbd> || <kbd>void Document(table<nowiki>|</nowiki>string ''symbolOrTable'', unknown ''itemIfSymbol'' = null, string ''descriptionIfSymbol'' = null)</kbd>
| If developer < 0, does nothing. {{todo}}
|-
| <kbd>PrintHelp</kbd> || <kbd>void PrintHelp(string ''string'' = "*", bool ''exact'' = false)</kbd>
| If <code>string</code> matches some part of the registered function documentation, prints it. <code>exact</code> specifies whether the search string should be an exact match.<br>If developer < 0, does nothing.
|-
| <kbd>RegisterFunctionDocumentation</kbd> || <kbd>void RegisterFunctionDocumentation(unknown ''func'', string ''name'', string ''signature'', string ''description'')</kbd>
| If developer < 0, this function is undefined. {{todo}}
|-
| <kbd>RetrieveNativeSignature</kbd> || <kbd>string RetrieveNativeSignature(string ''nativeFunction'')</kbd>
| Attempts to retrieve the native function signature for the provided string, however the function references a non-existant index <code>NativeFunctionSignatures</code>, resulting in an error.<br>If developer < 0, returns <kbd>"<unnamed>"</kbd>.
|}
 
=== Other ===
 
{| class="standard-table" style="width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>Assert</kbd> || <kbd>void Assert(''exp'', string ''message'' = null)</kbd>
| Throws an exception if ''exp'' equates to false, optionally with message.
| Throws an exception if ''exp'' equates to false, optionally with message.
|-
|-
| <code>CreateProp</code>
| <kbd>CreateProp</kbd> || <kbd>handle CreateProp(string classname, Vector origin, string modelname, int activity)</kbd>
| <code>handle CreateProp(string classname, Vector origin, string modelname, int activity)</code>
| Create a prop. The class should be a prop_physics style entity.
| Create a prop. The class should be a prop_physics style entity.
|-
|-
| <code>CreateSceneEntity</code>
| <kbd>CreateSceneEntity</kbd> || <kbd>handle CreateSceneEntity(string)</kbd>
| <code>handle CreateSceneEntity(string)</code>
| Create a scene entity to play the specified scene.
| Create a scene entity to play the specified scene.
|-
|-
| <code>DebugDrawBox</code>
| <kbd>dummy</kbd> || <kbd>void dummy()</kbd>
| <code>void DebugDrawBox(Vector origin, Vector mins, Vector maxs, int r, int g, int b, int alpha, float duration)</code>
| Dummy function. Does nothing.
| Draw a debug box, for visualizing code. It's positioned at <code>origin</code>, with the dimensions <code>mins</code>/<code>maxs</code> Developer must be on to show this, and it'll stay around for <code>duration</code> seconds (or 1 frame if -1.0). The color ranges from 0-255.
|-
| <code>DebugDrawLine</code>
| <code>void DebugDrawLine(Vector start, Vector end, int r, int g, int b, bool hitTest, float duration)</code>
| Draw a debug line, for visualizing code. Developer must be on to show this, and it'll stay around for <code>duration</code> seconds (or 1 frame if -1.0). The color ranges from 0-255.
|-
|-
| <code>DoIncludeScript</code>
| <kbd>DoIncludeScript</kbd> || <kbd>bool DoIncludeScript(string ''filename'', table ''scope'')</kbd>
| <code>bool DoIncludeScript(string ''filename'', table ''scope'')</code>
| Execute the script file <code>"scripts/vscripts/" + filename</code> in the scope of <code>scope</code>. The extension <code>.nut</code> can be omitted.
| Execute the script file <code>"scripts/vscripts/" + filename</code> in the scope of <code>scope</code>. The extension <code>.nut</code> can be omitted.
|-
|-
| <code>IncludeScript</code>
| <kbd>IncludeScript</kbd> || <kbd>bool IncludeScript(string ''filename'', table ''scope'' = null)</kbd>
| <code>bool IncludeScript(string ''filename'', table ''scope'' = null)</code>
| Execute the script file <code>"scripts/vscripts/" + filename</code> in the scope of <code>scope</code>, <code>this</code> by default. The extension <code>.nut</code> can be omitted.
| Execute the script file <code>"scripts/vscripts/" + filename</code> in the scope of <code>scope</code>, <code>this</code> by default. The extension <code>.nut</code> can be omitted.
|-
|-
| <code>DoEntFire</code>
| <kbd>DoEntFire</kbd> || <kbd>void DoEntFire(string ''target'', string ''action'', string ''value'', float ''delay'', handle ''activator'', handle ''caller'')</kbd>
| <code>void DoEntFire(string ''target'', string ''action'', string ''value'', float ''delay'', handle ''activator'', handle ''caller'')</code>
| Generate an entity [[I/O]] event.
| Generate an entity [[I/O]] event.
|-
|-
| <code>EntFire</code>
| <kbd>EntFire</kbd> || <kbd>function EntFire(target, action, value, delay, activator)</kbd>
| <code>function EntFire(target, action, value, delay, activator)</code>
| Generate an entity [[I/O]] event. Value, delay and activator are optional.
| Generate an entity [[I/O]] event. Value, delay and activator are optional.
|-
|-
| <code>EntFireByHandle</code>
| <kbd>EntFireByHandle</kbd> || <kbd>void EntFireByHandle(handle target, string action, string value, float delay, handle activator, handle caller)</kbd>
| <code>void EntFireByHandle(handle target, string action, string value, float delay, handle activator, handle caller)</code>
| Generate an entity I/O event. First parameter is an entity instance.
| Generate an entity I/O event. First parameter is an entity instance.
|-
|-
| <code>FrameTime</code>
| <kbd>FrameTime</kbd> || <kbd>float FrameTime()</kbd>
| <code>float FrameTime()</code>
| Get the time spent on the server in the last frame.
| Get the time spent on the server in the last frame.
|-
|-
| <code>GetDeveloperLevel</code>
| <kbd>GetDeveloperLevel</kbd> || <kbd>int GetDeveloperLevel()</kbd>
| <code>int GetDeveloperLevel()</code>
| Gets the level of 'developer'.
| Gets the level of 'developer'.
|-
|-
| <code>GetMapIndexInPlayOrder</code>
| <kbd>GetFunctionSignature</kbd> || <kbd>string GetFunctionSignature(function ''function'', string ''name'')</kbd>
| <code>int GetMapIndexInPlayOrder()</code>
| {{todo}}
|-
| <kbd>GetMapIndexInPlayOrder</kbd> || <kbd>int GetMapIndexInPlayOrder()</kbd>
| For workshop maps, determines which index (by order played) this map is. Returns -1 if entry is not found or -2 if this is not a workshop map.
| For workshop maps, determines which index (by order played) this map is. Returns -1 if entry is not found or -2 if this is not a workshop map.
|-
|-
| <code>GetMapName</code>
| <kbd>GetMapName</kbd> || <kbd>string GetMapName()</kbd>
| <code>string GetMapName()</code>
| Get the name of the map.
| Get the name of the map.
|-
|-
| <code>GetNumMapsPlayed</code>
| <kbd>GetNumMapsPlayed</kbd> || <kbd>int GetNumMapsPlayed()</kbd>
| <code>int GetNumMapsPlayed()</code>
| Returns how many workshop maps the player has played through.
| Returns how many workshop maps the player has played through.
|-
|-
| <code>GetPlayerSilenceDuration</code>
| <kbd>GetPlayerSilenceDuration</kbd> || <kbd>float GetPlayerSilenceDuration(int player_index)</kbd>
| <code>float GetPlayerSilenceDuration(int player_index)</code>
| Time that the specified player has been silent on the mic.
| Time that the specified player has been silent on the mic.
|-
|-
| <code>IsMultiplayer</code>
| <kbd>IsMultiplayer</kbd> || <kbd>bool IsMultiplayer()</kbd>
| <code>bool IsMultiplayer()</code>
| Returns true if this is a multiplayer game, or false if singleplayer.
| Returns true if this is a multiplayer game, or false if singleplayer.
|-
|-
| <code>LoopSinglePlayerMaps</code>
| <kbd>LoopSinglePlayerMaps</kbd> || <kbd>bool LoopSinglePlayerMaps()</kbd>
| <code>bool LoopSinglePlayerMaps()</code>
| Returns true if the cvar <code>loopsingleplayermaps</code> is enabled. Still works in multiplayer.
| Returns true if the cvar <code>loopsingleplayermaps</code> is enabled. Still works in multiplayer.
|-
|-
| <code>RandomFloat</code>
| <kbd>RandomFloat</kbd> || <kbd>float RandomFloat(float min, float max)</kbd>
| <code>float RandomFloat(float min, float max)</code>
| Generate a random floating point number within a range, inclusive
| Generate a random floating point number within a range, inclusive
|-
|-
| <code>RandomInt</code>
| <kbd>RandomInt</kbd> || <kbd>int RandomInt(int min, int max)</kbd>
| <code>int RandomInt(int min, int max)</code>
| Generate a random integer within a range, inclusive
| Generate a random integer within a range, inclusive
|-
|-
| <code>RecordAchievementEvent</code>
| <kbd>RecordAchievementEvent</kbd> || <kbd>void RecordAchievementEvent(string name, int player_index)</kbd>
| <code>void RecordAchievementEvent(string name, int player_index)</code>
| Earns a given achievement or increases progress.
| Earns a given achievement or increases progress.
|-
|-
| <code>RequestMapRating</code>
| <kbd>RequestMapRating</kbd> || <kbd>void RequestMapRating()</kbd>
| <code>void RequestMapRating()</code>
| In workshop maps, pops up the map rating dialog for user input.
| In workshop maps, pops up the map rating dialog for user input.
|-
|-
| <code>RetrieveNativeSignature</code>
| <kbd>SendToConsole</kbd> || <kbd>void SendToConsole(string command)</kbd>
| <code>void RetrieveNativeSignature(string ''nativeFunction'')</code>
| {{todo}}
|-
| <code>SendToConsole</code>
| <code>void SendToConsole(string command)</code>
| Send a string to the console as a command. The command is treated as coming from the host in multiplayer.
| Send a string to the console as a command. The command is treated as coming from the host in multiplayer.
|-
|-
| <code>SetDucking</code>
| <kbd>SetDucking</kbd> || <kbd>void SetDucking(string, string, float)</kbd>
| <code>void SetDucking(string, string, float)</code>
| Set the level of an audio ducking channel.
| Set the level of an audio ducking channel.
|-
|-
| <code>SetMapAsPlayed</code>
| <kbd>SetMapAsPlayed</kbd> || <kbd>int SetMapAsPlayed()</kbd>
| <code>int SetMapAsPlayed()</code>
| For workshop maps, adds the current map to the play order and returns the new index therein. Returns -2 if this is not a workshop map.
| For workshop maps, adds the current map to the play order and returns the new index therein. Returns -2 if this is not a workshop map.
|-
|-
| <code>ShowMessage</code>
| <kbd>Time</kbd> || <kbd>float Time()</kbd>
| <code>void ShowMessage(string)</code>
| Print a HUD message on all clients.
|-
| <code>Time</code>
| <code>float Time()</code>
| Get the current server time
| Get the current server time
|-
|-
| <code>TraceLine</code>
| <kbd>TraceLine</kbd> || <kbd>float TraceLine(Vector start, Vector end, handle ignored_ent)</kbd>
| <code>float TraceLine(Vector start, Vector end, handle ignored_ent)</code>
| Given 2 points and an entity to ignore, returns fraction along line that hits the world. Does not hit entities, seemingly making the ignored entity parameter useless.
| Given 2 points and an entity to ignore, returns fraction along line that hits the world. Does not hit entities, seemingly making the ignored entity parameter useless.
|-
|-
| <code>UniqueString</code>
| <kbd>UniqueString</kbd> || <kbd>string UniqueString(string ''suffix'' = "")</kbd>
| <code>string UniqueString(string ''suffix'' = "")</code>
| Generate a string guaranteed to be unique across the life of the script VM, with an optional root string. Useful for adding data to tables when not sure what keys are already in use in that table. Equivalent to <code>DoUniqueString(suffix)</code>.
| Generate a string guaranteed to be unique across the life of the script VM, with an optional root string. Useful for adding data to tables when not sure what keys are already in use in that table. Equivalent to <code>DoUniqueString(suffix)</code>.
|-
|-
| <code>DoUniqueString</code>
| <kbd>DoUniqueString</kbd> || <kbd>string DoUniqueString(string ''suffix'')</kbd>
| <code>string DoUniqueString(string ''suffix'')</code>
| Generate a string guaranteed to be unique across the life of the script VM, with an optional root string. Useful for adding data to tables when not sure what keys are already in use in that table.
| 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>__ReplaceClosures</code>
| <kbd>VSquirrel_OnCreateScope</kbd> || <kbd>table(?) VSquirrel_OnCreateScope(string ''name'', table(?) ''outer'')</kbd>
| <code>void __ReplaceClosures(function ''script'', table ''scope'')</code>
| Run internally when a new scope is created. {{todo}}
| Internal function called in <code>script_reload_</code> server commands.
|-
| <kbd>VSquirrel_OnReleaseScope</kbd> || <kbd>void VSquirrel_OnReleaseScope(table(?) ''scope'')</kbd>
| Run internally when a scope is released. {{todo}}
|-
| <kbd>__ReplaceClosures</kbd> || <kbd>void __ReplaceClosures(function ''script'', table ''scope'')</kbd>
| Internal function called in <code>script_reload_</code> server commands. {{todo}}
|}
 
== Squirrel Standard Library ==
{{sq}} List of functions, classes, and variables that come from Squirrel's built-in [https://web.archive.org/web/20210517033527/http://squirrel-lang.org/doc/sqstdlib2.html standard library]. Not all functions from the linked documentation are present in VScript, such as the {{Code|blob}} library.
 
=== General ===
 
==== Constants ====
{| class="standard-table"
|- style="position:sticky; z-index:10; top:0"
! Instance !! Type !! Value !! Description
|-
| <kbd>_charsize_</kbd> || integer
| 1
| Size in bytes of the internal VM representation for characters.
|-
| <kbd>_intsize_</kbd> || integer
| 4
| Size in bytes of the internal VM representation for integers.
|-
| <kbd>_floatsize_</kbd> || integer
| 4
| Size in bytes of the internal VM representation for floats.
|-
| <kbd>_version_</kbd> || string
| "Squirrel 2.2.3 stable"
| String values describing the version of VM and compiler.  
|}
|}
{{note|These are simply global variables, namely table slots in the root table. They can be changed at will, for example <code>::_charsize_ {{=}} 2</code>.}}
==== Functions ====


=== Singleplayer only ===
{| class = "standard-table" style = "width: 100%;"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>assert</kbd> || <kbd>assert(bool ''exp'')</kbd>
| Throws an exception if exp is evaluated to false.
|-
| <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. Enables if <kbd>''enable'' != null</kbd>, disables if <kbd>''enable'' == null</kbd>.
|-
| <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 lang="cpp">
{
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>print</kbd> || <kbd>void print(string ''message'')</kbd>
| Prints message to console without any line feed after.
|-
| <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>type</kbd> || <kbd>string type(any ''obj'')</kbd>
| Return the 'raw' type of an object without invoking the metatmethod <code>_typeof</code>.
|}
 
=== Math ===
The built-in [https://web.archive.org/web/20210517033527/http://squirrel-lang.org/doc/sqstdlib2.html#d0e1519 Squirrel math library].


These functions can only be used in singleplayer games, and may cause errors if used in multiplayer.
==== Constants ====
{| class="standard-table"
! Instance !! Type !! Value !! Description
|-
| <kbd>PI</kbd> || float
| 3.141592
| The numeric constant pi is the ratio of the circumference of a circle to its diameter.
|-
| <kbd>RAND_MAX</kbd> || integer
| 32767
| The maximum value that can be returned by the <kbd>rand()</kbd> function.
|}
{{note|These are simply global variables, namely table slots in the root table. They can be changed at will, for example <code>::PI {{=}} 3</code>.}}


==== Functions ====
{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
| <kbd>abs</kbd> || <kbd>int abs(float ''x'')</kbd>
| Returns the absolute value of <kbd>''x''</kbd> as an integer (<kbd><nowiki>|x|</nowiki></kbd>).
|-
| <kbd>fabs</kbd> || <kbd>float fabs(float ''x'')</kbd>
| Returns the absolute value of <kbd>''x''</kbd> as a float (<kbd><nowiki>|x|</nowiki></kbd>).
|-
|-
| <code>GetPlayer</code>
| <kbd>sin</kbd> || <kbd> float sin(float ''x'')</kbd>
| <code>handle GetPlayer()</code>
| Returns the sine of <kbd>''x''</kbd> (<kbd>sin(x)</kbd>).
| Returns the player.
|-
| <kbd>cos</kbd> || <kbd>float cos(float ''x'')</kbd>
| Returns the cosine of <kbd>''x''</kbd> (<kbd>cos(x)</kbd>).
|-
| <kbd>tan</kbd> || <kbd>float tan(float ''x'')</kbd>
| Returns the tangent of <kbd>''x''</kbd> (<kbd>tan(x)</kbd>).
|-
| <kbd>asin</kbd> || <kbd>float asin(float ''x'')</kbd>
| Returns the arcsine of <kbd>''x''</kbd> (<kbd>sin<sup>-1</sup>(x), -1 ≤ x ≤ 1.</kbd>).
|-
| <kbd>acos</kbd> || <kbd>float acos(float ''x'')</kbd>
| Returns the arccosine of <kbd>''x''</kbd> (<kbd>cos<sup>-1</sup>(x), -1 ≤ x ≤ 1.</kbd>).
|-
| <kbd>atan</kbd> || <kbd>float atan(float ''x'')</kbd>
| Returns the arctangent of <kbd>''x''</kbd> (<kbd>tan<sup>-1</sup>(x).</kbd>).
|-
| <kbd>atan2</kbd> || <kbd>float atan2(float ''y'', float ''x'')</kbd>
| Returns the angle between the ray from the point (0, 0) through (''x'', ''y'') and the positive x-axis, confined to (−<kbd>PI</kbd>, <kbd>PI</kbd>] (<kbd>arctan(y/x), x > 0</kbd> ; <kbd>arctan(y/x)±π, x < 0</kbd>). Note the order of the parameters <kbd>''x''</kbd> and <kbd>''y''</kbd>!
 
See also [[w:atan2|atan2]].
|-
| <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>x</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>x</kbd>⌉).
|-
|-
| <code>GivePlayerPortalgun</code>
| <kbd>pow</kbd> || <kbd>float pow(float ''x'', float ''y'')</kbd>
| <code>void GivePlayerPortalgun()</code>
| Returns <kbd>''x''</kbd> raised to the power of <kbd>''y''</kbd> (<kbd>x<sup>y</sup></kbd>).
| Equips the player with a blue-only portalgun.
|-
|-
| <code>PrecacheMovie</code>
| <kbd>exp</kbd> || <kbd>float exp(float ''x'')</kbd>
| <code>void PrecacheMovie(string)</code>
| Returns the exponential value of <kbd>''x''</kbd> (<kbd>e<sup>x</sup></kbd>).
| Precaches a named movie. Only valid to call within the entity's 'Precache' function called on mapspawn.
|-
|-
| <code>ScriptShowHudMessageAll</code>
| <kbd>log</kbd> || <kbd>float log(float ''x'')</kbd>
| <code>void ScriptShowHudMessageAll(string, float)</code>
| Returns the natural logarithm of <kbd>''x''</kbd> (<kbd>log<sub>e</sub>(x) = ln(x)</kbd>).
| Show center print text message for specified number of seconds.
|-
|-
| <code>ScriptSteamShowURL</code>
| <kbd>log10</kbd> || <kbd> float log10(float ''x'')</kbd>
| <code>bool ScriptSteamShowURL(string)</code>
| Returns the logarithm base-10 of <kbd>''x''</kbd> (<kbd>log<sub>10</sub>(x)</kbd>).
| Bring up the steam overlay and shows the specified URL.  (Full address with protocol type is required, e.g. http://www.steamgames.com/)
|-
|-
| <code>TryDLC1InstalledOrCatch</code>
| <kbd>sqrt</kbd> || <kbd>float sqrt(float ''x'')</kbd>
| <code>void TryDLC1InstalledOrCatch()</code>
| Returns the square root of <kbd>''x''</kbd> (√<span style="text-decoration:overline"><kbd>x</kbd></span>).
| Throws an exception if the Peer Review DLC isn't installed. Useless in the current PC version of the game, as Peer Review will always be present.
|-
|-
| <code>UpgradePlayerPortalgun</code>
| <kbd>rand</kbd> || <kbd>int rand()</kbd>
| <code>void UpgradePlayerPortalgun()</code>
| Returns a pseudorandom integer in the range 0 to <kbd>RAND_MAX</kbd> (<kbd>0 ≤ rand() ≤ RAND_MAX</kbd>).
| Upgrades the player's portalgun to shoot orange portals.
|-
|-
| <code>UpgradePlayerPotatogun</code>
| <kbd>srand</kbd> || <kbd>void srand(float ''seed'')</kbd>
| <code>void UpgradePlayerPotatogun()</code>
| Sets the starting point for generating a series of pseudorandom integers.
| Upgrades the player's portalgun to shoot orange portals and have PotatOS impaled on it.
|}
|}


=== Multiplayer only ===
=== Strings ===
The built-in [https://web.archive.org/web/20210517033527/http://squirrel-lang.org/doc/sqstdlib2.html#d0e2162 Squirrel string library].
 
==== Functions ====
{| class="standard-table" style="width:100
|- style="position:sticky; z-index:10; top:0"
! 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>split</kbd> || <kbd>array split(string ''str'', string ''separator'')</kbd>
| Returns an array of strings split at each point where the ''separator'' string occurs in ''str''. The separator is not returned as part of any array element.
|-
| <kbd>strip</kbd> || <kbd>string strip(string ''str'')</kbd>
| Removes whitespace at the beginning and end of the given string
|-
| <kbd>lstrip</kbd> || <kbd>string lstrip(string ''str'')</kbd>
| Removes whitespace at the beginning of the given string.
|-
| <kbd>rstrip</kbd> || <kbd>string rstrip(string ''str'')</kbd>
| Removes whitespace at the end of the given string.
|}


These functions can only be used in multiplayer games, and may cause errors if used in singleplayer.
==== Regexp ====
The built-in [https://web.archive.org/web/20210517033527/http://squirrel-lang.org/doc/sqstdlib2.html#d0e2580 Squirrel class] for regular expressions.


{| class="standard-table" style="width: 100%;"
{| class="standard-table" style="width: 100%;"
! Function
|- style="position:sticky; z-index:10; top:0"
! Signature
! Function !! Signature !! Description
! Description
|-
| <kbd>constructor</kbd> || <kbd>regexp(string ''pattern'')</kbd>
| Creates and compiles a regular expression represented by ''pattern''.
{{Note|Make sure to use double back slashes (<code>\\</code> instead of <code>\</code>) if you want to insert one in the regex instead of escaping a character.}}
|-
| <kbd>capture</kbd> || <kbd>table regexp::capture(string ''str'', int ''start'' = 0)</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 regexp::match(string ''str'')</kbd>
| Returns a true if the regular expression matches the string str, otherwise returns false.
|-
| <kbd>search</kbd> || <kbd>table regexp::search(string ''str'', int ''start'' = 0)</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> || <kbd>int regexp::subexpcount()</kbd>
| Counts the amount of groups present in the regular expression.
{{note|The whole regex is considered a group so the result will always be ≥ 1.}}
|-
| <kbd>_typeof</kbd> || <kbd>string regexp::_typeof()</kbd>
| <code>typeof</code> overload. Returns "regexp".
|}
 
=== Types ===
 
==== Integer ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>tointeger</kbd> || <kbd>int tointeger()</kbd>
| Returns the value of the integer (dummy function).
|-
| <kbd>tofloat</kbd> || <kbd>float tofloat()</kbd>
| Converts the integer to float and returns it.
|-
| <kbd>tostring</kbd> || <kbd>string tostring()</kbd>
| Converts the integer to string and returns it.
|-
| <kbd>tochar</kbd> || <kbd>string tochar()</kbd>
| Returns a string containing a single character represented by the integer.
|-
| <kbd>weakref</kbd> || <kbd>int weakref()</kbd>
| Dummy function, returns the integer itself.
|}
 
==== Float ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>tointeger</kbd> || <kbd>int tointeger()</kbd>
| Converts the float to integer and returns it.
|-
| <kbd>tofloat</kbd> || <kbd>float tofloat()</kbd>
| Returns the value of the float (dummy function).
|-
| <kbd>tostring</kbd> || <kbd>string tostring()</kbd>
| Converts the integer to string and returns it.
|-
| <kbd>tochar</kbd> || <kbd>string tochar()</kbd>
| Returns a string containing a single character represented by the integer part of the float.
|-
| <kbd>weakref</kbd> || <kbd>float weakref()</kbd>
| Dummy function, returns the float itself.
|}
 
==== Bool ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>tofloat</kbd> || <kbd>float tofloat()</kbd>
| Returns <kbd>1.0</kbd> for true and <kbd>0.0</kbd> for false.
|-
| <kbd>tointeger</kbd> || <kbd>int tointeger()</kbd>
| Returns <kbd>1</kbd> for true and <kbd>0</kbd> for false.
|-
| <kbd>tostring</kbd> || <kbd>string tostring()</kbd>
| Returns "<kbd>true<kbd>" for true and "<kbd>false<kbd>" for false.
|-
| <kbd>weakref</kbd> || <kbd>bool weakref()</kbd>
| Dummy function, returns the bool itself.
|}
 
==== String ====
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>find</kbd> || <kbd>int find(string ''search_string'', int ''start_index'' = 0)</kbd>
| Looks for the sub-string passed as its first parameter, starting at either the beginning of the string or at a specific character index if one is provided as a second parameter. If the sub-string is found, returns the index at which it first occurs, otherwise returns null.
|-
| <kbd>len</kbd> || <kbd>int len()</kbd>
| Returns the length of the string, ie. the number of characters it comprises.
|-
|-
| <code>AddBranchLevelName</code>
| <kbd>slice</kbd> || <kbd>string slice(int ''start_index'', int ''end_index'' = null)</kbd>
| <code>void AddBranchLevelName(int, string)</code>
| Creates a sub-string from a string. Copies characters from ''start_index'' to ''end_index''. The sub-string includes the character at ''start_index'', but excludes the one at ''end_index''. If ''end_index'' is not specified, copies until the last character. If the provided end index is beyond the string, an exception is thrown. If the numbers are negative the count will start from the end of the string (e.g. -2 represents a second last character).
| Adds a level to the specified branch's list. {{note|In co-op maps, this function must be called at least once or players will not be able to move.}}
|-
| <kbd>tolower</kbd> || <kbd>string tolower()</kbd>
| Returns a new string with all upper-case characters converted to lower-case.
|-
| <kbd>toupper</kbd> || <kbd>string toupper()</kbd>
| Returns a new string with all lower-case characters converted to upper-case.
|-
| <kbd>tointeger</kbd> || <kbd>int tointeger(int ''base'' = 10)</kbd>
| Returns integer value represented by the string. Must only contain numeric characters. An exception is thrown otherwise. Hexadecimal notation is supported (i.e. <code>0xFF</code>). If a hexadecimal string contains more than 10 characters, including the <code>0x</code>, returns -1.
|-
| <kbd>tofloat</kbd> || <kbd>float tofloat()</kbd>
| Returns float value represented by the string. Must only contain numeric characters and/or plus and minus symbols. An exception is thrown otherwise.
|-
| <kbd>tostring</kbd> || <kbd>string tostring()</kbd>
| Returns the string (dummy function).
|-
| <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd>
| Returns a weak reference to the object.
|}
 
==== Table ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>clear</kbd> || <kbd>void clear()</kbd>
| Removes all of the items from a table.
|-
| <kbd>len</kbd> || <kbd>int len()</kbd>
| Returns the length of the table, ie. the number of entries it has.
|-
| <kbd>rawdelete</kbd> || <kbd>any rawdelete(any ''key'')</kbd>
| This method deletes the target slot without employing delegation. If the table lacks the target slot, the methods returns null, otherwise it returns the value associated with that slot.
|-
| <kbd>rawget</kbd> || <kbd>any rawget(any ''key'')</kbd>
| Retrieves the value of the specified key without employing delegation.
|-
| <kbd>rawin</kbd> || <kbd>bool rawin(any ''key'')</kbd>
| Checks for the presence of the specified key in the table/class/handle without employing delegation.
|-
| <kbd>rawset</kbd> || <kbd>table rawset(any ''key'', any ''value'')</kbd>
| Sets the value of the specified key without employing delegation. Returns table itself.
|-
| <kbd>tostring</kbd> || <kbd>string tostring()</kbd>
| Tries to invoke the <code>_tostring</code> metamethod. If that fails, returns a string in the form "<kbd>(table: <''pointer''>)</kbd>".
|-
| <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd>
| Returns a weak reference to the object.
|}
 
==== Array ====
 
===== Methods =====
The following belong as member methods of the array object, in other words they must be called with the dot operator on an array, e.g. <code>arr.append(0)</code>.
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>append</kbd> || <kbd>void append(any ''val'')</kbd>
| Adds an item to the end of an array.
|-
| <kbd>clear</kbd> || <kbd>void clear()</kbd>
| Removes all of the items from an array.
|-
| <kbd>extend</kbd> || <kbd>array extend(array ''other'')</kbd>
| Combines two arrays into one.
|-
| <kbd>find</kbd> || <kbd>int find(any ''element'')</kbd>
| Looks for the element passed as its parameter, starting at either the beginning of the array. If the element is found, returns the index at which it first occurs, otherwise returns null.
|-
| <kbd>insert</kbd> || <kbd>void insert(int ''index'', any ''item'')</kbd>
| Inserts an item into an array at the specified index.
|-
| <kbd>len</kbd> || <kbd>int len()</kbd>
| Returns the length of the array, ie. the number of elements it has..
|-
| <kbd>push</kbd> || <kbd>void push(any ''val'')</kbd>
| Adds an item to the end of an array.
|-
| <kbd>pop</kbd> || <kbd>any pop()</kbd>
| Returns and removes the value at the end of the array.
|-
| <kbd>remove</kbd> || <kbd>any remove(int ''index'')</kbd>
| Returns and removes an array item at a specified index.
|-
| <kbd>resize</kbd> || <kbd>void resize(int ''size'', any ''fill'' = null)</kbd>
| Increases or decreases the size of an array. In case of increasing fills the new spots with ''fill'' parameter.
|-
| <kbd>reverse</kbd>  || <kbd>void reverse()</kbd>
| Reverses the order of the elements in an array.
|-
| <kbd>slice</kbd> || <kbd>array slice(int ''start_index'', int ''end_index'' = null)</kbd>
| Creates a new array from an array. Copies elements from ''start_index'' to ''end_index''. The new array includes the element at ''start_index'', but excludes the one at ''end_index''. If ''end_index'' is not specified, copies until the last element. If the provided end index is beyond the array, an exception is thrown. If the numbers are negative the count will start from the end of the array (e.g. -2 represents a second last character).
|-
| <kbd>sort</kbd> || <kbd>void sort(function<a, b> ''compare_func'' = null)</kbd>
| This method sorts the items within the target array into either a lowest-to-highest order or according to the results of an optional comparison function which may be passed to the method as a parameter. If the items are arrays, blobs, functions, objects and/or tables, they will be sorted by reference not value. The optional comparison function should take two parameters: two values which will be compared in some way. It should return the value -1 if the first value should be placed before the second, or 1 if it should follow the second value. Return 0 if the two values are equivalent. Spaceship operator <code><=></code> may come in handy if trying to sort by some field value. E.g. <source lang=cpp>arr.sort(@(a, b) a.distance <=> b.distance)</source>
|-
| <kbd>top</kbd> || <kbd>any top()</kbd>
| Returns the value at the end of an array.
|-
| <kbd>tostring</kbd> || <kbd>string tostring()</kbd>
| Returns a string in the form "<kbd>(array: <''pointer''>)</kbd>".
|-
| <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd>
| Returns a weak reference to the object.
|}
 
===== Functions =====
The following belong as global array functions, e.g. <code>arr = array(3, 0)</code>.
 
{| class="standard-table" style="width:100
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>array</kbd> || <kbd>array(int ''length'', any ''fill'' = null)</kbd>
| Returns a new array of the given length where each element is set to <kbd>''fill''</kbd>.
|}
 
==== Function ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
| <kbd>call</kbd> || <kbd>any call(table ''env'', any ''args''...)</kbd>
| Calls the function with a non-default context object.
|-
| <kbd>acall</kbd> || <kbd>any acall(array ''array_args'')</kbd>
| Calls the target function and passes array values into its parameters. First element of the array should be the non-default context object.
|-
| <kbd>pcall</kbd> || <kbd>any pcall(table ''env'', any ''args''...)</kbd>
| Calls the function with a non-default context object, bypassing Squirrel error callbacks.
|-
| <kbd>pacall</kbd> || <kbd>any pacall(array ''array_args'')</kbd>
| Calls the function with an array of parameters, bypassing Squirrel error callbacks. First element of the array should be the non-default context object.
|-
|-
| <code>AddCoopCreditsName</code>
| <kbd>bindenv</kbd> || <kbd>function bindenv(table ''env'')</kbd>
| <code>void AddCoopCreditsName(string)</code>
| Clones the target function and binds it to a specified context object. The <code>this</code> parameter of the newly create function will always be set to ''env''.
| Adds a name to the coop credit's list.
{{note|The created function holds a weak reference to its environment object so it cannot be used to control its lifetime.}}
|-
|-
| <code>AddGladosSpokenFlags</code>
| <kbd>getinfos</kbd> || <kbd>table getinfos()</kbd>
| <code>void AddGladosSpokenFlags(int, int)</code>
| Returns a table containing informations about the function, like parameters, name and source name.
| Adds bit flags for specific lines that are tracked per session.
{{Expand|title=Example|
<source lang="cpp">
//pure squirrel function
{
  native = false
  name = "zefuncname"
  src = "/somthing/something.nut"
  parameters = ["a","b","c"]
  defparams = [1,"def"]
  varargs = 2
}
//native C function
{
  native = true
  name = "zefuncname"
  paramscheck = 2
  typecheck = [83886082,83886384] //this is the typemask (see C defines OT_INTEGER,OT_FLOAT etc...)
}
</source>
}}
|-
|-
| <code>CoopGladosBlowUpBots</code>
| <kbd>tostring</kbd> || <kbd>string tostring()</kbd>
| <code>void CoopGladosBlowUpBots()</code>
| Returns a string in the form "<kbd>(closure: <''pointer''>)</kbd>".
| Blows up both robots and prevents respawning.
|-
|-
| <code>CoopGetNumPortalsPlaced</code>
| <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd>
| <code>int CoopGetNumPortalsPlaced()</code>
| Returns a weak reference to the object.
| Returns the number of portals the players have placed so far.
|}
 
==== Class ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
|-
| <code>CoopGetLevelsCompletedThisBranch</code>
| <kbd>instance</kbd> || <kbd>instance instance()</kbd>
| <code>int CoopGetLevelsCompletedThisBranch()</code>
| Returns a new instance of the class. This function does not invoke the instance constructor. The constructor must be explicitly called (e.g., <code>class_inst.constructor(class_inst)</code>).
| Returns the number of levels the players have completed in their run of the current branch.
|-
|-
| <code>CoopGetBranchTotalLevelCount</code>
| <kbd>getattributes</kbd> || <kbd>any getattributes(string ''membername'')</kbd>
| <code>int CoopGetBranchTotalLevelCount()</code>
| Returns the attributes of the specified member. If the parameter member is null, the function returns the class-level attributes.
| Returns the number of levels in the current branch.
|-
|-
| <code>CoopSetCameFromLastDLCMap</code>
| <kbd>setattributes</kbd> || <kbd>any setattributes(string ''membername'', any ''value'')</kbd>
| <code>void CoopSetCameFromLastDLCMap(bool)</code>
| Sets the attribute of the specified member and returns the previous attribute value. If the parameter member is null, sets the class-level attributes.
| Set whether the players came from the last coop DLC map or not.
|-
|-
| <code>CoopSetMapRunTime</code>
| <kbd>rawin</kbd> || <kbd>bool rawin(any ''key'')</kbd>
| <code>void CoopSetMapRunTime(float runLength)</code>
| Checks for the presence of the specified key in the class without employing delegation.
| Sets the time to complete a coop map from spawn to completing the puzzle. (Possibly related to the Triple Crown achievement.)
|-
|-
| <code>GetBluePlayerIndex</code>
| <kbd>tostring</kbd> || <kbd>string tostring()</kbd>
| <code>int GetBluePlayerIndex()</code>
| Returns a string in the form "<kbd>(class: <''pointer''>)</kbd>".
| Player index of the blue player.
|-
|-
| <code>GetCameFromLastDLCMap</code>
| <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd>
| <code>bool GetCameFromLastDLCMap()</code>
| Returns a weak reference to the object.
| Returns true if coming from the last DLC coop map (as set by <code>CoopSetCameFromLastDLCMap</code>).
|}
 
==== Class instance ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
|-
| <code>GetCoopBranchLevelIndex</code>
| <kbd>getclass</kbd> || <kbd>class getclass()</kbd>
| <code>int GetCoopBranchLevelIndex(int)</code>
| Returns the class that created the instance.
| Given the 'branch' argument, returns the current chosen level.
|-
|-
| <code>GetCoopSectionIndex</code>
| <kbd>rawin</kbd> || <kbd>bool rawin(any ''key'')</kbd>
| <code>int GetCoopSectionIndex()</code>
| Checks for the presence of the specified key in the instance without employing delegation.
| Section that the coop players have selected to load.
|-
|-
| <code>GetGladosSpokenFlags</code>
| <kbd>tostring</kbd> || <kbd>string tostring()</kbd>
| <code>int GetGladosSpokenFlags(int)</code>
| Tries to invoke the <code>_tostring</code> metamethod. If that fails, returns a string in the form "<kbd>(instance: <''pointer''>)</kbd>".
| Returns bit flags for specific lines that are tracked per session.
|-
|-
| <code>GetHaveSeenDLCTubesReveal</code>
| <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd>
| <code>bool GetHaveSeenDLCTubesReveal()</code>
| Returns a weak reference to the object.
| Get whether players have seen the DLC tubes reveal this session (as set by <code>SetHaveSeenDLCTubesReveal</code>).
|}
 
==== Generator ====
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
|-
| <code>GetHighestActiveBranch</code>
| <kbd>getstatus</kbd> || <kbd>string getstatus()</kbd>
| <code>int GetHighestActiveBranch()</code>
| Returns the status of the generator as string: "running", "dead" or "suspended".
| Returns which branches should be available in the hub.
|-
|-
| <code>GetNumPlayersConnected</code>
| <kbd>tostring</kbd> || <kbd>string tostring()</kbd>
| <code>int GetNumPlayersConnected()</code>
| Returns a string in the form "<kbd>(generator: <''pointer''>)</kbd>".
| Returns how many players are connected. In normal co-op, this will almost always be 2.
|-
|-
| <code>GetOrangePlayerIndex</code>
| <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd>
| <code>int GetOrangePlayerIndex()</code>
| Returns a weak reference to the object.
| Player index of the orange player.
|}
 
==== Thread ====
 
===== Methods =====
The following belong as member methods of the thread object, in other words they must be called with the dot operator on a thread, e.g. <code>thread.call()</code>.
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
|-
| <code>GetPlayerDeathCount</code>
| <kbd>call</kbd> || <kbd>any call(any ''args''...)</kbd>
| <code>int GetPlayerDeathCount(int player)</code>
| Starts the thread with the specified parameters. Returns either the first <code>suspend</code> value or the returned value of the function if none suspends were triggered.
| Returns the number of times that a specific player has died in the session.
|-
|-
| <code>IsBranchComplete</code>
| <kbd>getstatus</kbd> || <kbd>string getstatus()</kbd>
| <code>bool IsBranchComplete(int course)</code>
| Returns the status of the thread ("idle", "running", "suspended").
| Returns true if every level in the course has been completed by either player.
|-
|-
| <code>IsLevelComplete</code>
| <kbd>tostring</kbd> || <kbd>string tostring()</kbd>
| <code>bool IsLevelComplete(int course, int level)</code>
| Returns a string in the form "<kbd>(thread: <''pointer''>)</kbd>".
| Returns true if the level in the specified course is completed by either player.
|-
|-
| <code>IsLocalSplitScreen</code>
| <kbd>wakeup</kbd> || <kbd>any wakeup(any ''return'' = null)</kbd>
| <code>bool IsLocalSplitScreen()</code>
| Wakes up a suspended thread, accepts a optional parameter that will be used as return value for the function that suspended the thread (<code>suspend</code> method). The returned value will be received on the next thread suspension depending on what was passed in the <code>suspend</code> method.
| Returns true if players are in split screen.
|-
|-
| <code>IsPlayerBranchComplete</code>
| <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd>
| <code>bool IsPlayerBranchComplete(int player, int course)</code>
| Returns a weak reference to the object.
| Returns true if every level in the course has been completed by the specified player.
|}
 
===== Functions =====
The following belong as global thread functions, e.g. <code>thread = newthread(func)</code>.
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
|-
| <code>IsPlayerLevelComplete</code>
| <kbd>newthread</kbd> || <kbd>thread newthread(function ''threadfunc'')</kbd>
| <code>bool IsPlayerLevelComplete(int, int, int)</code>
| Creates a new cooperative thread object (coroutine) and returns it.
| Returns true if the level in the specified course is completed by a specific player.
{{warning|Coroutines introduce their own additional overhead and require very specific configuration to avoid server crashes. {{workaround|Use a [https://developer.electricimp.com/squirrel/squirrel-guide/functions#generator-functions generator function] instead.  Generators can spread expensive functions across multiple frames to avoid stutters/timeouts.
[https://github.com/ficool2/TF2Ware_Ultimate/blob/d698583894b87f5b94f99a0535f40fafd34a98ce/scripts/vscripts/tf2ware_ultimate/main.nut#L416 Real world TF2 example]}}}}
|-
|-
| <code>MarkMapComplete</code>
| <kbd>suspend</kbd> || <kbd>any suspend(any ''return'' = this)</kbd>
| <code>void MarkMapComplete(string)</code>
| Suspends the coroutine that called this function. Needs to be called inside the thread's function body. Accepts a optional parameter that will be used as return value for the function that woke up the thread (<code>wakeup</code> method). If nothing is passed defaults to <code>this</code> (the scope in which this function was called). The returned value will be received on the next thread wake up depending on what was passed in the <code>wakeup</code> method.
| Marks a maps a complete for both players.
|}
 
==== Weak reference ====
Weak references let you reference an object without preventing it from being garbage collected. They're useful when you want to refer to an object, but don't want to increase its reference count and keep it alive unnecessarily. When the object pointed by weak reference is destroyed, the weak reference is automatically set to null. <code>weakref</code> method that returns weak reference to an object exist on every object in squirrel, but primitive types like numbers will return itself since they're stored differently, therefore making this method redundant. Everything else works as expected.
 
{| class="standard-table" style="width:100%"
|- style="position:sticky; z-index:10; top:0"
! Function !! Signature !! Description
|-
|-
| <code>NotifySpeedRunSuccess</code>
| <kbd>ref</kbd> || <kbd>instance ref()</kbd>
| <code>void NotifySpeedRunSuccess(int runLength, string mapname)</code>
| Returns the object that the weak reference is pointing at, or null if the object that it was pointing to was destroyed.
| Tells the client that a successful speed run has been completed. (Used for the Triple Crown achievement.)
|-
|-
| <code>SaveMPStatsData</code>
| <kbd>tostring</kbd> || <kbd>string tostring()</kbd>
| <code>void SaveMPStatsData()</code>
| Returns a string in the form "<kbd>(weakref: <''pointer''>)</kbd>".
| Save the multiplayer stats for the score board.
|-
|-
| <code>SetHaveSeenDLCTubesReveal</code>
| <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd>
| <code>void SetHaveSeenDLCTubesReveal()</code>
| Returns a weak reference to the object.
| Set that players have seen the DLC tubes reveal this session.
|}
|}


Line 1,114: Line 1,789:
* [[VScript Fundamentals]]
* [[VScript Fundamentals]]
* {{sq}} [[Squirrel]]
* {{sq}} [[Squirrel]]
* [[PCapture-Lib - Portal 2 Script Library]]
* {{l4d2}} [[Left 4 Dead 2/Script Functions]]
* {{l4d2}} [[Left 4 Dead 2/Script Functions]]
* {{csgo}} [[List of Counter-Strike: Global Offensive Script Functions]]
* {{csgo}} [[List of Counter-Strike: Global Offensive Script Functions]]
* [[PCapture-Lib - Portal 2 Script Library]]
* [[List of Script Libraries]]


[[Category:Portal 2]]
[[Category:Portal 2]]
[[Category:Scripting]]
[[Category:Scripting]]

Latest revision as of 23:37, 17 September 2025

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


Squirrel This list contains all engine-related Squirrel classes, functions, and variables available for VScript in Portal 2 Portal 2.

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

In addition to these, VScript also comes with many of Squirrel's predefined standard library functions. See below ↓ for a list of them.

Tip.pngTip:A tutorial on setting up Visual Studio Code (VSCode), including auto-completing of VScript functions, can be found here.

Global variables

Instance Type Description
Entities CEntities ↓ Provides access to spawned entities in the server.
Documentation table A table that has 3 documentation sub-tables (classes, functions, instances) which store information related to function documentation. Only exists when the developer level is greater than 0.

Global hooks

These hooks only work when defined in the root table.

Function Signature Description
ConnectOutputs void ConnectOutputs(table table) Called after an entity with an script assigned spawns (i.e. vscripts keyvalue is not blank), passing the entity's scope as the parameter. Unlike OnPostSpawn, this is called immediately and therefore on map respawn, some entities may not exist during this point.
Originally this would have been used for automatically connecting an entity's outputs on spawn, but the Squirrel code used for this was disabled due to a crash that occurred with regexp not saving/loading properly after a save/load.
Confirm:Can this supposed crash still occur?

To re-enable this behavior, define the following in the root table:

::__OutputsPattern <- regexp("^On.*Output$");

::ConnectOutputs <- function( table )
{
	const nCharsToStrip = 6;
	foreach( key, val in table )
	{
		if ( typeof( val ) == "function" && __OutputsPattern.match( key ) )
		{
			//printl(key.slice( 0, nCharsToStrip ) );
			table.self.ConnectOutput( key.slice( 0, key.len() - nCharsToStrip ), key );
		}
	}
}

Then to use this system, define a function in an entity script with a name of the format On<OutputName>Output, where <OutputName> is the name of the entity's output you want to connect into (without the "On" prefix, as it's already provided).

Classes

CBaseEntity

This is a script handle class for entities. All entities spawned have a script handle using this or one of its subclasses.

All script handles in-game are accessible from Entities ↓. Entity scripts can use self to access their own script handle. activator and caller variables can be accessed on function calls.

Methods

Function Signature Description
__KeyValueFromInt
__KeyValueFromFloat
__KeyValueFromString
__KeyValueFromVector
bool __KeyValueFromInt(string key, int value)
bool __KeyValueFromFloat(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.

ConnectOutput void CBaseEntity::ConnectOutput(string output, string func_name) Adds an I/O connection that will call the named function when the specified output fires.
DisconnectOutput void CBaseEntity::DisconnectOutput(string output, string func_name) Removes a connected script function from an I/O event.
Destroy void CBaseEntity::Destroy() Kills this entity.
entindex int CBaseEntity::entindex() Returns the entity index.
EmitSound void CBaseEntity::EmitSound(string sound) Plays a sound from this entity.
EyePosition Vector CBaseEntity::EyePosition() Get vector to eye position - absolute coords.
FirstMoveChild handle CBaseEntity::FirstMoveChild() If in hierarchy, get the first move child.
GetAngles Vector CBaseEntity::GetAngles() Get entity pitch, yaw, roll as a vector.
GetAngularVelocity Vector CBaseEntity::GetAngularVelocity() Get the local angular velocity - returns a vector of pitch,yaw,roll.
GetVelocity Vector CBaseEntity::GetVelocity() Get the velocity of the entity. Note that this reads the QPhysics velocity value, so it only works for players, NPCs and moving brush entities. VPhysics objects always have a velocity of zero. A workaround is to record the position over multiple frames, and derive the velocity manually.
GetBoundingMaxs Vector CBaseEntity::GetBoundingMaxs() Get a vector containing max bounds, centered on object.
GetBoundingMins Vector CBaseEntity::GetBoundingMins() Get a vector containing min bounds, centered on object.
GetCenter Vector CBaseEntity::GetCenter() Get vector to center of object - absolute coords.
GetClassname string CBaseEntity::GetClassname() Get the classname of this entity.
GetForwardVector Vector CBaseEntity::GetForwardVector() Get the forward vector (+X) of the entity.
GetLeftVector Vector CBaseEntity::GetLeftVector() Get the left vector (+Y) of the entity.
GetUpVector Vector CBaseEntity::GetUpVector() Get the up vector (+Z) of the entity.
GetHealth int CBaseEntity::GetHealth() Returns the current health.
GetMaxHealth int CBaseEntity::GetMaxHealth() Returns the maximum health.
GetModelKeyValues handle CBaseEntity::GetModelKeyValues() Get a KeyValue class instance on this entity's model.
GetModelName string CBaseEntity::GetModelName() Returns the name of the model.
GetMoveParent handle CBaseEntity::GetMoveParent() If in hierarchy, retrieves the entity's parent.
GetName string CBaseEntity::GetName() Get the Targetname of this entity.
GetOrigin Vector CBaseEntity::GetOrigin() Returns this entity's local origin.
GetOwner handle CBaseEntity::GetOwner() Gets this entity's owner.
GetPreTemplateName string CBaseEntity::GetPreTemplateName() Get the entity name stripped of template unique decoration - the &001 suffix.
GetRootMoveParent handle CBaseEntity::GetRootMoveParent() If in hierarchy, walks up the hierarchy to find the root parent
GetScriptId string CBaseEntity::GetScriptId() Returns the name of the entity's think function.
GetScriptScope handle CBaseEntity::GetScriptScope() Retrieve the script-side data associated with an entity.
GetSoundDuration float CBaseEntity::GetSoundDuration(string, string) Returns float duration of the sound. Takes soundname and optional actormodelname.
GetTeam int CBaseEntity::GetTeam() Get the team this entity is on.
IsValid bool CBaseEntity::IsValid() Returns true if this entity is valid.
NextMovePeer handle CBaseEntity::NextMovePeer() Return the next entity in the same movement hierarchy.
PrecacheSoundScript void CBaseEntity::PrecacheSoundScript(string) Precache a sound for later playing. Should be called in the 'Precache()' hook function.
SetAbsOrigin void CBaseEntity::SetAbsOrigin(Vector) Teleport the entity to this world position.
SetAngles void CBaseEntity::SetAngles(float, float, float) Set entity pitch, yaw, roll
SetAngularVelocity void CBaseEntity::SetAngularVelocity(float, float, float) Set the local angular velocity - takes float pitch,yaw,roll velocities
SetVelocity void CBaseEntity::SetVelocity(Vector) Set local velocity. Note that this sets the QPhysics velocity value, so it only works for players, NPCs and moving brush entities. On VPhysics objects, this has no effect.
SetForwardVector void CBaseEntity::SetForwardVector(Vector) Set the orientation of the entity to have this forward (+X) vector.
SetHealth void CBaseEntity::SetHealth(int) Sets the current health.
SetMaxHealth void CBaseEntity::SetMaxHealth(int) Sets the maximum health.
SetModel void CBaseEntity::SetModel(string) Change the model used for the entity. This can be used to change models for prop_weighted_cube or other similar entities. The model must be precached, which is usually done by placing it elsewhere in the map.
SetOrigin void CBaseEntity::SetOrigin(Vector) Teleport this entity to the given location.
SetOwner void CBaseEntity::SetOwner(handle) Sets this entity's owner.
SetSize void CBaseEntity::SetSize(Vector, Vector) Sets the bounding box size.
SetTeam void CBaseEntity::SetTeam(int) Set the team this entity is on.
ValidateScriptScope bool CBaseEntity::ValidateScriptScope() Ensure that an entity's script scope has been created. This should be called before assigning to the entity's scope.

Metamethods

Function Signature Description
_tostring string CBaseEntity::_tostring() Overload for string conversion. Returns a string in the form "([<entindex>] <entity_class>: <targetname>)". If the entity does not have a targetname, it is omitted.

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
DispatchOnPostSpawn void DispatchOnPostSpawn() Called after the entity spawns.
If both this function and OnPostSpawn() are defined, this one takes precedence and the other never runs.
Note.pngNote:This hook is predefined internally by CSimpleCallChainer ↓ but it won't have any effect until redefined.
DispatchPrecache void DispatchPrecache() This is called during entity spawning and after restore to allow scripts to precache any resources they need.
If both this function and Precache() are defined, this one takes precedence and the other never runs.
Note.pngNote:This hook is predefined internally by CSimpleCallChainer ↓ but it won't have any effect until redefined.
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.

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.
If both this function and DispatchOnPostSpawn() are defined, that one takes precedence and this one never runs.
Precache void Precache() Called after the script executes. Can be used to call precache functions for models and sounds on map load.
If both this function and DispatchPrecache() are defined, that one takes precedence and this one never runs.

Variables

Instance Type Description
__vname string Internal name for the current scope.
__vrefs int Reference count for the current scope. This variable is managed by VSquirrel_OnCreateScope() and VSquirrel_OnReleaseScope(). [Elaborate?]
OnPostSpawnCallChain CSimpleCallChainer Callchain instance for OnPostSpawn hooks.
PrecacheCallChain CSimpleCallChainer Callchain instance for Precache hooks.

CBaseAnimating

Extends CBaseEntity ↑

Script handle class for animating entities such as props.

Methods

Function Signature Description
GetAttachmentAngles Vector CBaseAnimating::GetAttachmentAngles(int id) Get the attachment id's angles as a p,y,r vector.
GetAttachmentOrigin Vector CBaseAnimating::GetAttachmentOrigin(int id) Get the attachment id's origin vector
GetObjectScaleLevel int CBaseAnimating::GetObjectScaleLevel() The scale size of the entity
IsSequenceFinished bool CBaseAnimating::IsSequenceFinished() Ask whether the main sequence is done playing
LookupAttachment int CBaseAnimating::LookupAttachment(string) Get the ID for the named attachment.
SetBodygroup void CBaseAnimating::SetBodygroup(int group, int index) Sets a bodygroup. Group is the index for the desired group, and index is the desired part to use.

CBaseFlex

Extends CBaseAnimating ↑

Methods

Function Signature Description
GetCurrentScene handle CBaseFlex::GetCurrentScene() Returns the instance of the oldest active scene entity (if any).
GetSceneByIndex handle CBaseFlex::GetSceneByIndex(int) Returns the instance of the scene entity at the specified index.

CBasePlayer

Extends CBaseAnimating ↑

Script handle class for player entities.

Methods

Function Signature Description
IsNoclipping bool CBasePlayer::IsNoclipping() Returns true if the player is in noclip mode.

CEntities

Script 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 entity index is used to determine the order of the search; any entity with an entity index smaller than the one in previous is skipped over. [confirm]

The following are two equivalent examples and iterate over all entities with the name "entityname":

local ent = null;
while ( ent = Entities.FindByName(ent, "entityname") )
{
  // ...
}
for (local ent; ent = Entities.FindByName(ent, "entityname"); )
{
  // ...
}
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.
  • In every iteration, "ent" is not null.
  • Semicolons are optional, except in the header of the for statement.

Methods

Function Signature Description
CreateByClassname handle CEntities::CreateByClassname(string) Creates an entity by classname
FindByClassname handle CEntities::FindByClassname(handle start_ent, string classname) Find entities by class name. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
FindByClassnameNearest handle CEntities::FindByClassnameNearest(string classname, Vector loc, float radius) Find entities by class name nearest to a point.
FindByClassnameWithin handle CEntities::FindByClassnameWithin(handle start_ent, string classname, Vector loc, float radius) Find entities by class name within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
FindByModel handle CEntities::FindByModel(handle start_ent, string model) Find entities by model name. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
FindByName handle CEntities::FindByName(handle start_ent, string targetname) Find entities by name (including wildcards). Pass 'null' to start an iteration, or reference to a previously found entity to continue a search.
FindByNameNearest handle CEntities::FindByNameNearest(string targetname, Vector loc, float radius) Find entities by name nearest to a point.
FindByNameWithin handle CEntities::FindByNameWithin(handle, string, Vector loc, float radius) Find entities by name within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
FindByTarget handle CEntities::FindByTarget(handle start_ent, string targetname) Find entities with a specific target keyvalue. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
FindInSphere handle CEntities::FindInSphere(handle start_ent, Vector loc, float radius) Find entities within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
First handle CEntities::First() Begin an iteration over the list of entities. Equivalent to Next(null).
Next handle CEntities::Next(handle) Continue an iteration over the list of entities, providing reference to a previously found entity.

CEnvEntityMaker

Extends CBaseEntity ↑

Script handle class for env_entity_maker.

Methods

Function Signature Description
SpawnEntity void CEnvEntityMaker::SpawnEntity() Create an entity at the location of the maker
SpawnEntityAtEntityOrigin void CEnvEntityMaker::SpawnEntityAtEntityOrigin(handle) Create an entity at the location of a specified entity instance
SpawnEntityAtLocation void CEnvEntityMaker::SpawnEntityAtLocation(Vector, Vector) Create an entity at a specified location and orientaton, orientation is Euler angle in degrees (pitch, yaw, roll)
SpawnEntityAtNamedEntityOrigin void CEnvEntityMaker::SpawnEntityAtNamedEntityOrigin(string) Create an entity at the location of a named entity

CLinkedPortalDoor

Extends CBaseAnimating ↑

Script handle class for linked_portal_door.

Methods

Function Signature Description
GetPartnerInstance handle CLinkedPortalDoor::GetPartnerInstance() Get the instance handle of the door's linked partner
GetPartnername string CLinkedPortalDoor::GetPartnername() Returns the partnername of the door.

CPropLinkedPortalDoor

Extends CLinkedPortalDoor ↑

Script handle class for prop_linked_portal_door. Has the same methods as CLinkedPortalDoor.

CLogicScript

Extends CBaseEntity ↑

Script handle class for logic_script.

Functions

Function Signature Description
__AppendToScriptGroup void __AppendToScriptGroup(string name) Internal function used for gathering the entities defined by the entity group keyvalues. It is only briefly defined while the entity is spawning, then it is removed.

Variables

Instance Type Description
EntityGroup array Array containing every entity set by this logic_script's Group keyvalues. This variable is only defined if one or more of those keyvalues have been defined.

CPlayerVoiceListener

Extends CAutoGameSystem

Maintains data about voice communications from various players so that the server can react to it.

Methods

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

CPointTemplate

Extends CBaseEntity ↑

Script handle class for point_template.

Functions

Function Signature Description
__ExecutePreSpawn table|null __ExecutePreSpawn(handle entity) Internal function executed when a spawner on the server is getting ready to prespawn an entity. It calls this function, sending the entity that it's preparing to spawn.

If the PreSpawnInstance hook is defined, this function will run that hook with the provided entity parameter.

__FinishSpawn void __FinishSpawn() Internal function executed after the entity finishes spawning. Sets __EntityMakerResult to null.

Variables

Instance Type Description
__EntityMakerResult table Contains the entity handle for the entity that should spawn. This only exists while an entity is in the process of being spawned (it gets deleted afterwards), meaning this is only accessible in the PreSpawnInstance or PostSpawn hooks.

Hooks

Function Signature Description
PreSpawnInstance 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.
Example
function PreSpawnInstance( entityClass, entityName )
{
	local keyvalues =
	{ 
   		rendercolor = "0 255 0"
   		targetname = "mySpawnedEntity"
	}
	return keyvalues
}
PostSpawn 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.
Example
function PostSpawn( entities )
{
	foreach( name, handle in entities )
	{
		printl( name + ": " + handle )
	}
}
Example

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

m_hSpawnedEntity <- null;
m_KeyValues <- null;

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

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

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

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

Spawn templated entities from any script.

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

printl( ent )

CPortal_Player

Extends CBasePlayer ↑

Script handle class for player entities of Portal.

Methods

Function Signature Description
GetWheatleyMonitorDestructionCount int CPortal_Player::GetWheatleyMonitorDestructionCount() Get number of wheatley monitors destroyed by the player.
IncWheatleyMonitorDestructionCount void CPortal_Player::IncWheatleyMonitorDestructionCount() Set number of wheatley monitors destroyed by the player.
TurnOffPotatos void CPortal_Player::TurnOffPotatos() Turns Off the Potatos material light
TurnOnPotatos void CPortal_Player::TurnOnPotatos() Turns On the Potatos material light

CSceneEntity

Extends CBaseEntity ↑

Methods

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

CScriptKeyValues

Script handle representation of a models $keyvalues block. Sub keys are instances of the same class.

Methods

Function Signature Description
FindKey handle CScriptKeyValues::FindKey(string) Given a KeyValues object and a key name, find a KeyValues object associated with the key name
GetFirstSubKey handle CScriptKeyValues::GetFirstSubKey() Given a KeyValues object, return the first sub key object
GetKeyBool bool CScriptKeyValues::GetKeyBool(string) Given a KeyValues object and a key name, return associated bool value
GetKeyFloat float CScriptKeyValues::GetKeyFloat(string) Given a KeyValues object and a key name, return associated float value
GetKeyInt int CScriptKeyValues::GetKeyInt(string) Given a KeyValues object and a key name, return associated integer value
GetKeyString string CScriptKeyValues::GetKeyString(string) Given a KeyValues object and a key name, return associated string value
GetNextKey handle CScriptKeyValues::GetNextKey() Given a KeyValues object, return the next key object in a sub key group
IsKeyEmpty bool CScriptKeyValues::IsKeyEmpty(string) Given a KeyValues object and a key name, return true if key name has no value
ReleaseKeyValues void CScriptKeyValues::ReleaseKeyValues() Given a root KeyValues object, release its contents

CTriggerCamera

Extends CBaseEntity ↑

Script handle class for point_viewcontrol.

Methods

Function Signature Description
GetFov int CTriggerCamera::GetFov() get camera's current fov setting as integer
SetFov void CTriggerCamera::SetFov(int, float) set camera's current fov in integer degrees and fov change rate as float

Hooks

Function Signature Description
ScriptStartCameraShot void ScriptStartCameraShot(string shotType, handle sceneEntity, handle actor1, handle actor2, float duration) Called from SceneEntity in response to a CChoreoEvent::CAMERA sent from a VCD. [Todo]

CCallChainer

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

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

Methods

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

Members

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

CSimpleCallChainer

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

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

Methods

Function Signature Description
constructor CSimpleCallChainer(string 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. Also automatically exposes two bound global functions to dispatch to this object: DispatchPrecache() and DispatchOnPostSpawn().
PostScriptExecute void CSimpleCallChainer::PostScriptExecute() Begin searching for all non-native functions with matching prefixes, then push them into the chain array.
Call bool CSimpleCallChainer::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

Late binding: allows a table to refer to parts of itself, it's children, it's owner, and then have the references fixed up after it's fully parsed.

Usage example
// Usage:
lateBinder <- LateBinder();
lateBinder.Begin( this );

Test1 <-
{   
   Foo=1
}   

Test2 <-
{   
   FooFoo = "I'm foo foo"
   BarBar="@Test1.Foo"
   SubTable = { boo=[bah, "@Test2.FooFoo", "@Test1.Foo"], booboo2={one=bah, two="@Test2.FooFoo", three="@Test1.Foo"} }
   booboo=[bah, "@Test2.FooFoo", "@Test1.Foo"]
   booboo2={one=bah, two="@Test2.FooFoo", three="@Test1.Foo"}
   bah=wha
}   

lateBinder.End();
delete lateBinder;

When End() is called, all of the unresolved symbols in the tables and arrays will be resolved, any left unresolved will become a string prepended with '~', which later code can deal with.

Methods

Function Signature Description
Begin void LateBinder::Begin(table target, bool log = false) [Todo]
End void LateBinder::End() [Todo]
EstablishDelegation void LateBinder::EstablishDelegation(table parentTable, table childTable) [Todo]
RemoveDelegation void LateBinder::EstablishDelegation(table parentTable, table childTable) [Todo]
HookRootMetamethod void LateBinder::HookRootMetamethod(string name, unknown value) "private" method. [Todo]
UnhookRootMetamethod void LateBinder::UnhookRootMetamethod(string name) [Todo]
Log void LateBinder::Log(string string) [Todo]
Resolve bool LateBinder::Resolve(table lookupTable, table|array subTableOrArray, bool throwException = false ) [Todo]

Members

Instance Type Description
m_bindNamesStack array [Todo]
m_fixupSet array [Todo]
m_log bool [Todo]
m_logIndent int [Todo]
m_targetTable table [Todo]

Vector

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

Methods

Function Signature Description
constructor Vector(float x = 0, float y = 0, float z = 0) Creates a new vector with the specified Cartesian coordiantes.
Cross Vector Vector::Cross(Vector other) Return the vector cross product - this × other.
Dot float Vector::Dot(Vector other) Return the vector dot product - this · other.
Length float Vector::Length() Return the distance from the origin.
Length2D float Vector::Length2D() Return the distance from the origin, ignoring the Z axis.
LengthSqr float Vector::LengthSqr() Return the distance from the origin, but squared. This is faster to compute since a square root isn\'t required.
Length2DSqr float Vector::Length2DSqr() Return the distance from the origin, ignoring the Z axis and squared. This is faster to compute since a square root isn\'t required.
Norm float Vector::Norm() Modify the vector to have a length of 1, and return its original length.
ToKVString string Vector::ToKVString() Return a string in the form "X Y Z".

Metamethods

Function Signature Description
_add Vector Vector::_add(Vector add) Overload for the + operator - Vector + Vector. Adds each value of the provided vector to the current vector.
_sub Vector Vector::_sub(Vector add) Overload for the - operator - Vector - Vector. Subtracts each value of the provided vector from the current vector.
_mul Vector Vector::_mul(float scale) Overload for the * operator - Vector * number. Multiplies each value in the vector by this scale factor.
Note.pngNote:The number must come after the vector.
_typeof string Vector::_typeof() Overload for the typeof operator. Returns "Vector".
_tostring string Vector::_tostring() Overload for string conversion. Returns a string in the form "(vector : (X, Y, Z))".
_nexti string Vector::_nexti() Overload for iteration. [Todo]
_get string Vector::_get() Overload for accessing. [Todo]
_set string Vector::_set() Overload for setting. [Todo]

Members

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

Global functions

Printing and drawing

Function Signature Description
DebugDrawBox void DebugDrawBox(Vector origin, Vector mins, Vector maxs, int r, int g, int b, int alpha, float duration) Draw a debug box, for visualizing code. It's positioned at origin, with the dimensions mins/maxs Developer must be on to show this, and it'll stay around for duration seconds (or 1 frame if -1.0). The color ranges from 0-255.
DebugDrawLine void DebugDrawLine(Vector start, Vector end, int r, int g, int b, bool hitTest, float duration) Draw a debug line, for visualizing code. Developer must be on to show this, and it'll stay around for duration seconds (or 1 frame if -1.0). The color ranges from 0-255.
Msg void Msg(string text) Equivalent to print
printl void printl(string text) Prints the given message to the developer console with newline. Equivalent to print(message + "\n")
ShowMessage void ShowMessage(string) Print a hud message on all clients.
Note.pngNote:Uses localized strings as found in /scripts/titles.txt [confirm]
__DumpScope void __DumpScope(int indentation, table scope) Dumps the contents of scope.

Singleplayer only

These functions can only be used in singleplayer games, and may cause errors if used in multiplayer.

Function Signature Description
GetPlayer handle GetPlayer() Returns the player.
GivePlayerPortalgun void GivePlayerPortalgun() Equips the player with a blue-only portalgun.
PrecacheMovie void PrecacheMovie(string) Precaches a named movie. Only valid to call within the entity's 'Precache' function called on mapspawn.
ScriptShowHudMessageAll void ScriptShowHudMessageAll(string, float) Show center print text message for specified number of seconds.
ScriptSteamShowURL bool ScriptSteamShowURL(string) Bring up the steam overlay and shows the specified URL. (Full address with protocol type is required, e.g. http://www.steamgames.com/)
TryDLC1InstalledOrCatch void TryDLC1InstalledOrCatch() Throws an exception if the Peer Review DLC isn't installed. Useless in the current PC version of the game, as Peer Review will always be present.
UpgradePlayerPortalgun void UpgradePlayerPortalgun() Upgrades the player's portalgun to shoot orange portals.
UpgradePlayerPotatogun void UpgradePlayerPotatogun() Upgrades the player's portalgun to shoot orange portals and have PotatOS impaled on it.

Multiplayer only

These functions can only be used in multiplayer games, and may cause errors if used in singleplayer.

Function Signature Description
AddBranchLevelName void AddBranchLevelName(int, string) Adds a level to the specified branch's list.
Note.pngNote:In co-op maps, this function must be called at least once or players will not be able to move.
AddCoopCreditsName void AddCoopCreditsName(string) Adds a name to the coop credit's list.
AddGladosSpokenFlags void AddGladosSpokenFlags(int, int) Adds bit flags for specific lines that are tracked per session.
CoopGladosBlowUpBots void CoopGladosBlowUpBots() Blows up both robots and prevents respawning.
CoopGetNumPortalsPlaced int CoopGetNumPortalsPlaced() Returns the number of portals the players have placed so far.
CoopGetLevelsCompletedThisBranch int CoopGetLevelsCompletedThisBranch() Returns the number of levels the players have completed in their run of the current branch.
CoopGetBranchTotalLevelCount int CoopGetBranchTotalLevelCount() Returns the number of levels in the current branch.
CoopSetCameFromLastDLCMap void CoopSetCameFromLastDLCMap(bool) Set whether the players came from the last coop DLC map or not.
CoopSetMapRunTime void CoopSetMapRunTime(float runLength) Sets the time to complete a coop map from spawn to completing the puzzle. (Possibly related to the Triple Crown achievement.)
GetBluePlayerIndex int GetBluePlayerIndex() Player index of the blue player.
GetCameFromLastDLCMap bool GetCameFromLastDLCMap() Returns true if coming from the last DLC coop map (as set by CoopSetCameFromLastDLCMap).
GetCoopBranchLevelIndex int GetCoopBranchLevelIndex(int) Given the 'branch' argument, returns the current chosen level.
GetCoopSectionIndex int GetCoopSectionIndex() Section that the coop players have selected to load.
GetGladosSpokenFlags int GetGladosSpokenFlags(int) Returns bit flags for specific lines that are tracked per session.
GetHaveSeenDLCTubesReveal bool GetHaveSeenDLCTubesReveal() Get whether players have seen the DLC tubes reveal this session (as set by SetHaveSeenDLCTubesReveal).
GetHighestActiveBranch int GetHighestActiveBranch() Returns which branches should be available in the hub.
GetNumPlayersConnected int GetNumPlayersConnected() Returns how many players are connected. In normal co-op, this will almost always be 2.
GetOrangePlayerIndex int GetOrangePlayerIndex() Player index of the orange player.
GetPlayerDeathCount int GetPlayerDeathCount(int player) Returns the number of times that a specific player has died in the session.
IsBranchComplete bool IsBranchComplete(int course) Returns true if every level in the course has been completed by either player.
IsLevelComplete bool IsLevelComplete(int course, int level) Returns true if the level in the specified course is completed by either player.
IsLocalSplitScreen bool IsLocalSplitScreen() Returns true if players are in split screen.
IsPlayerBranchComplete bool IsPlayerBranchComplete(int player, int course) Returns true if every level in the course has been completed by the specified player.
IsPlayerLevelComplete bool IsPlayerLevelComplete(int, int, int) Returns true if the level in the specified course is completed by a specific player.
MarkMapComplete void MarkMapComplete(string) Marks a maps a complete for both players.
NotifySpeedRunSuccess void NotifySpeedRunSuccess(int runLength, string mapname) Tells the client that a successful speed run has been completed. (Used for the Triple Crown achievement.)
SaveMPStatsData void SaveMPStatsData() Save the multiplayer stats for the score board.
SetHaveSeenDLCTubesReveal void SetHaveSeenDLCTubesReveal() Set that players have seen the DLC tubes reveal this session.

Developer only

These functions require that the developer level is set to a value above 0. Otherwise these functions are either undefined, or defined to do nothing.

Function Signature Description
Document void Document(table|string symbolOrTable, unknown itemIfSymbol = null, string descriptionIfSymbol = null) If developer < 0, does nothing. [Todo]
PrintHelp void PrintHelp(string string = "*", bool exact = false) If string matches some part of the registered function documentation, prints it. exact specifies whether the search string should be an exact match.
If developer < 0, does nothing.
RegisterFunctionDocumentation void RegisterFunctionDocumentation(unknown func, string name, string signature, string description) If developer < 0, this function is undefined. [Todo]
RetrieveNativeSignature string RetrieveNativeSignature(string nativeFunction) Attempts to retrieve the native function signature for the provided string, however the function references a non-existant index NativeFunctionSignatures, resulting in an error.
If developer < 0, returns "<unnamed>".

Other

Function Signature Description
Assert void Assert(exp, string message = null) Throws an exception if exp equates to false, optionally with message.
CreateProp handle CreateProp(string classname, Vector origin, string modelname, int activity) Create a prop. The class should be a prop_physics style entity.
CreateSceneEntity handle CreateSceneEntity(string) Create a scene entity to play the specified scene.
dummy void dummy() Dummy function. Does nothing.
DoIncludeScript bool DoIncludeScript(string filename, table scope) Execute the script file "scripts/vscripts/" + filename in the scope of scope. The extension .nut can be omitted.
IncludeScript bool IncludeScript(string filename, table scope = null) Execute the script file "scripts/vscripts/" + filename in the scope of scope, this by default. The extension .nut can be omitted.
DoEntFire void DoEntFire(string target, string action, string value, float delay, handle activator, handle caller) Generate an entity I/O event.
EntFire function EntFire(target, action, value, delay, activator) Generate an entity I/O event. Value, delay and activator are optional.
EntFireByHandle void EntFireByHandle(handle target, string action, string value, float delay, handle activator, handle caller) Generate an entity I/O event. First parameter is an entity instance.
FrameTime float FrameTime() Get the time spent on the server in the last frame.
GetDeveloperLevel int GetDeveloperLevel() Gets the level of 'developer'.
GetFunctionSignature string GetFunctionSignature(function function, string name) [Todo]
GetMapIndexInPlayOrder int GetMapIndexInPlayOrder() For workshop maps, determines which index (by order played) this map is. Returns -1 if entry is not found or -2 if this is not a workshop map.
GetMapName string GetMapName() Get the name of the map.
GetNumMapsPlayed int GetNumMapsPlayed() Returns how many workshop maps the player has played through.
GetPlayerSilenceDuration float GetPlayerSilenceDuration(int player_index) Time that the specified player has been silent on the mic.
IsMultiplayer bool IsMultiplayer() Returns true if this is a multiplayer game, or false if singleplayer.
LoopSinglePlayerMaps bool LoopSinglePlayerMaps() Returns true if the cvar loopsingleplayermaps is enabled. Still works in multiplayer.
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
RecordAchievementEvent void RecordAchievementEvent(string name, int player_index) Earns a given achievement or increases progress.
RequestMapRating void RequestMapRating() In workshop maps, pops up the map rating dialog for user input.
SendToConsole void SendToConsole(string command) Send a string to the console as a command. The command is treated as coming from the host in multiplayer.
SetDucking void SetDucking(string, string, float) Set the level of an audio ducking channel.
SetMapAsPlayed int SetMapAsPlayed() For workshop maps, adds the current map to the play order and returns the new index therein. Returns -2 if this is not a workshop map.
Time float Time() Get the current server time
TraceLine float TraceLine(Vector start, Vector end, handle ignored_ent) Given 2 points and an entity to ignore, returns fraction along line that hits the world. Does not hit entities, seemingly making the ignored entity parameter useless.
UniqueString string UniqueString(string suffix = "") 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. Equivalent to DoUniqueString(suffix).
DoUniqueString string DoUniqueString(string suffix) 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.
VSquirrel_OnCreateScope table(?) VSquirrel_OnCreateScope(string name, table(?) outer) Run internally when a new scope is created. [Todo]
VSquirrel_OnReleaseScope void VSquirrel_OnReleaseScope(table(?) scope) Run internally when a scope is released. [Todo]
__ReplaceClosures void __ReplaceClosures(function script, table scope) Internal function called in script_reload_ server commands. [Todo]

Squirrel Standard Library

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

General

Constants

Instance Type Value Description
_charsize_ integer 1 Size in bytes of the internal VM representation for characters.
_intsize_ integer 4 Size in bytes of the internal VM representation for integers.
_floatsize_ integer 4 Size in bytes of the internal VM representation for floats.
_version_ string "Squirrel 2.2.3 stable" String values describing the version of VM and compiler.
Note.pngNote:These are simply global variables, namely table slots in the root table. They can be changed at will, for example ::_charsize_ = 2.

Functions

Function Signature Description
assert assert(bool exp) Throws an exception if exp is evaluated to false.
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. Enables if enable != null, disables if enable == null.
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"
	}
}
print void print(string message) Prints message to console without any line feed after.
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.
type string type(any obj) Return the 'raw' type of an object without invoking the metatmethod _typeof.

Math

The built-in Squirrel math library.

Constants

Instance Type Value Description
PI float 3.141592 The numeric constant pi is the ratio of the circumference of a circle to its diameter.
RAND_MAX integer 32767 The maximum value that can be returned by the rand() function.
Note.pngNote:These are simply global variables, namely table slots in the root table. They can be changed at will, for example ::PI = 3.

Functions

Function Signature Description
abs int abs(float x) Returns the absolute value of x as an integer (|x|).
fabs float fabs(float x) Returns the absolute value of x as a float (|x|).
sin float sin(float x) Returns the sine of x (sin(x)).
cos float cos(float x) Returns the cosine of x (cos(x)).
tan float tan(float x) Returns the tangent of x (tan(x)).
asin float asin(float x) Returns the arcsine of x (sin-1(x), -1 ≤ x ≤ 1.).
acos float acos(float x) Returns the arccosine of x (cos-1(x), -1 ≤ x ≤ 1.).
atan float atan(float x) Returns the arctangent of x (tan-1(x).).
atan2 float atan2(float y, float x) Returns the angle between the ray from the point (0, 0) through (x, y) and the positive x-axis, confined to (−PI, PI] (arctan(y/x), x > 0 ; arctan(y/x)±π, x < 0). Note the order of the parameters x and y!

See also atan2.

floor float floor(float x) Returns a float value representing the largest integer that is less than or equal to x (⌊x⌋).
ceil float ceil(float x) Returns a float value representing the smallest integer that is greater than or equal to x (⌈x⌉).
pow float pow(float x, float y) Returns x raised to the power of y (xy).
exp float exp(float x) Returns the exponential value of x (ex).
log float log(float x) Returns the natural logarithm of x (loge(x) = ln(x)).
log10 float log10(float x) Returns the logarithm base-10 of x (log10(x)).
sqrt float sqrt(float x) Returns the square root of x (√x).
rand int rand() Returns a pseudorandom integer in the range 0 to RAND_MAX (0 ≤ rand() ≤ RAND_MAX).
srand void srand(float seed) Sets the starting point for generating a series of pseudorandom integers.

Strings

The built-in Squirrel string library.

Functions

Function Signature Description
format string format(string format, args...) Returns a formatted string. Same rules as the standard C functions (except * is not supported).
split array split(string str, string separator) Returns an array of strings split at each point where the separator string occurs in str. The separator is not returned as part of any array element.
strip string strip(string str) Removes whitespace at the beginning and end of the given string
lstrip string lstrip(string str) Removes whitespace at the beginning of the given string.
rstrip string rstrip(string str) Removes whitespace at the end of the given string.

Regexp

The built-in Squirrel class for regular expressions.

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

Types

Integer

Function Signature Description
tointeger int tointeger() Returns the value of the integer (dummy function).
tofloat float tofloat() Converts the integer to float and returns it.
tostring string tostring() Converts the integer to string and returns it.
tochar string tochar() Returns a string containing a single character represented by the integer.
weakref int weakref() Dummy function, returns the integer itself.

Float

Function Signature Description
tointeger int tointeger() Converts the float to integer and returns it.
tofloat float tofloat() Returns the value of the float (dummy function).
tostring string tostring() Converts the integer to string and returns it.
tochar string tochar() Returns a string containing a single character represented by the integer part of the float.
weakref float weakref() Dummy function, returns the float itself.

Bool

Function Signature Description
tofloat float tofloat() Returns 1.0 for true and 0.0 for false.
tointeger int tointeger() Returns 1 for true and 0 for false.
tostring string tostring() Returns "true" for true and "false" for false.
weakref bool weakref() Dummy function, returns the bool itself.

String

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

Table

Function Signature Description
clear void clear() Removes all of the items from a table.
len int len() Returns the length of the table, ie. the number of entries it has.
rawdelete any rawdelete(any key) This method deletes the target slot without employing delegation. If the table lacks the target slot, the methods returns null, otherwise it returns the value associated with that slot.
rawget any rawget(any key) Retrieves the value of the specified key without employing delegation.
rawin bool rawin(any key) Checks for the presence of the specified key in the table/class/handle without employing delegation.
rawset table rawset(any key, any value) Sets the value of the specified key without employing delegation. Returns table itself.
tostring string tostring() Tries to invoke the _tostring metamethod. If that fails, returns a string in the form "(table: <pointer>)".
weakref weakref weakref() Returns a weak reference to the object.

Array

Methods

The following belong as member methods of the array object, in other words they must be called with the dot operator on an array, e.g. arr.append(0).

Function Signature Description
append void append(any val) Adds an item to the end of an array.
clear void clear() Removes all of the items from an array.
extend array extend(array other) Combines two arrays into one.
find int find(any element) Looks for the element passed as its parameter, starting at either the beginning of the array. If the element is found, returns the index at which it first occurs, otherwise returns null.
insert void insert(int index, any item) Inserts an item into an array at the specified index.
len int len() Returns the length of the array, ie. the number of elements it has..
push void push(any val) Adds an item to the end of an array.
pop any pop() Returns and removes the value at the end of the array.
remove any remove(int index) Returns and removes an array item at a specified index.
resize void resize(int size, any fill = null) Increases or decreases the size of an array. In case of increasing fills the new spots with fill parameter.
reverse void reverse() Reverses the order of the elements in an array.
slice array slice(int start_index, int end_index = null) Creates a new array from an array. Copies elements from start_index to end_index. The new array includes the element at start_index, but excludes the one at end_index. If end_index is not specified, copies until the last element. If the provided end index is beyond the array, an exception is thrown. If the numbers are negative the count will start from the end of the array (e.g. -2 represents a second last character).
sort void sort(function<a, b> compare_func = null) This method sorts the items within the target array into either a lowest-to-highest order or according to the results of an optional comparison function which may be passed to the method as a parameter. If the items are arrays, blobs, functions, objects and/or tables, they will be sorted by reference not value. The optional comparison function should take two parameters: two values which will be compared in some way. It should return the value -1 if the first value should be placed before the second, or 1 if it should follow the second value. Return 0 if the two values are equivalent. Spaceship operator <=> may come in handy if trying to sort by some field value. E.g.
arr.sort(@(a, b) a.distance <=> b.distance)
top any top() Returns the value at the end of an array.
tostring string tostring() Returns a string in the form "(array: <pointer>)".
weakref weakref weakref() Returns a weak reference to the object.
Functions

The following belong as global array functions, e.g. arr = array(3, 0).

Function Signature Description
array array(int length, any fill = null) Returns a new array of the given length where each element is set to fill.

Function

Function Signature Description
call any call(table env, any args...) Calls the function with a non-default context object.
acall any acall(array array_args) Calls the target function and passes array values into its parameters. First element of the array should be the non-default context object.
pcall any pcall(table env, any args...) Calls the function with a non-default context object, bypassing Squirrel error callbacks.
pacall any pacall(array array_args) Calls the function with an array of parameters, bypassing Squirrel error callbacks. First element of the array should be the non-default context object.
bindenv function bindenv(table env) Clones the target function and binds it to a specified context object. The this parameter of the newly create function will always be set to env.
Note.pngNote:The created function holds a weak reference to its environment object so it cannot be used to control its lifetime.
getinfos table getinfos() Returns a table containing informations about the function, like parameters, name and source name.
Example
//pure squirrel function
{
  native = false
  name = "zefuncname"
  src = "/somthing/something.nut"
  parameters = ["a","b","c"]
  defparams = [1,"def"]
  varargs = 2
}
//native C function
{
  native = true
  name = "zefuncname"
  paramscheck = 2
  typecheck = [83886082,83886384] //this is the typemask (see C defines OT_INTEGER,OT_FLOAT etc...)
}
tostring string tostring() Returns a string in the form "(closure: <pointer>)".
weakref weakref weakref() Returns a weak reference to the object.

Class

Function Signature Description
instance instance instance() Returns a new instance of the class. This function does not invoke the instance constructor. The constructor must be explicitly called (e.g., class_inst.constructor(class_inst)).
getattributes any getattributes(string membername) Returns the attributes of the specified member. If the parameter member is null, the function returns the class-level attributes.
setattributes any setattributes(string membername, any value) Sets the attribute of the specified member and returns the previous attribute value. If the parameter member is null, sets the class-level attributes.
rawin bool rawin(any key) Checks for the presence of the specified key in the class without employing delegation.
tostring string tostring() Returns a string in the form "(class: <pointer>)".
weakref weakref weakref() Returns a weak reference to the object.

Class instance

Function Signature Description
getclass class getclass() Returns the class that created the instance.
rawin bool rawin(any key) Checks for the presence of the specified key in the instance without employing delegation.
tostring string tostring() Tries to invoke the _tostring metamethod. If that fails, returns a string in the form "(instance: <pointer>)".
weakref weakref weakref() Returns a weak reference to the object.

Generator

Function Signature Description
getstatus string getstatus() Returns the status of the generator as string: "running", "dead" or "suspended".
tostring string tostring() Returns a string in the form "(generator: <pointer>)".
weakref weakref weakref() Returns a weak reference to the object.

Thread

Methods

The following belong as member methods of the thread object, in other words they must be called with the dot operator on a thread, e.g. thread.call().

Function Signature Description
call any call(any args...) Starts the thread with the specified parameters. Returns either the first suspend value or the returned value of the function if none suspends were triggered.
getstatus string getstatus() Returns the status of the thread ("idle", "running", "suspended").
tostring string tostring() Returns a string in the form "(thread: <pointer>)".
wakeup any wakeup(any return = null) Wakes up a suspended thread, accepts a optional parameter that will be used as return value for the function that suspended the thread (suspend method). The returned value will be received on the next thread suspension depending on what was passed in the suspend method.
weakref weakref weakref() Returns a weak reference to the object.
Functions

The following belong as global thread functions, e.g. thread = newthread(func).

Function Signature Description
newthread thread newthread(function threadfunc) Creates a new cooperative thread object (coroutine) and returns it.
Warning.pngWarning:Coroutines introduce their own additional overhead and require very specific configuration to avoid server crashes.
PlacementTip.pngWorkaround:Use a generator function instead. Generators can spread expensive functions across multiple frames to avoid stutters/timeouts. Real world TF2 example
suspend any suspend(any return = this) Suspends the coroutine that called this function. Needs to be called inside the thread's function body. Accepts a optional parameter that will be used as return value for the function that woke up the thread (wakeup method). If nothing is passed defaults to this (the scope in which this function was called). The returned value will be received on the next thread wake up depending on what was passed in the wakeup method.

Weak reference

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

Function Signature Description
ref instance ref() Returns the object that the weak reference is pointing at, or null if the object that it was pointing to was destroyed.
tostring string tostring() Returns a string in the form "(weakref: <pointer>)".
weakref weakref weakref() Returns a weak reference to the object.

See also