Portal 2/Scripting/Script Functions: Difference between revisions
Mycatismycat (talk | contribs) m (remove unnessacary spaces) |
(→CPlayerVoiceListener: Add information about this) |
||
(3 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
{{ | {{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}}. | |||
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. | |||
== | 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 | |||
|- | |- | ||
|< | <!-- min-width applied to keep the arrow on the same line --> | ||
|< | | <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. | |||
{| class="standard-table" | {| class="standard-table" | ||
! | |- style="position:sticky; z-index:10; top:0" | ||
! | ! Function !! Signature !! Description | ||
! | |||
|- | |- | ||
|< | | <kbd>ConnectOutputs</kbd> || <kbd>void ConnectOutputs(table ''table'')</kbd> | ||
| 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> | |||
| | 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: | ||
{{Expand|<source lang="cpp"> | |||
::__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 ); | |||
} | |||
} | |||
} | |||
</source> | |||
}} | |||
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 | 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=" | {| class="standard-table" | ||
! Function | |- style="position:sticky; z-index:10; top:0" | ||
! Signature | ! Function !! Signature !! Description | ||
! Description | |||
|- | |- | ||
| < | | <kbd>__KeyValueFromInt</kbd><br><kbd>__KeyValueFromFloat</kbd><br><kbd>__KeyValueFromString</kbd><br><kbd>__KeyValueFromVector</kbd> | ||
| < | | <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 [[ | | 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. | |||
|- | |- | ||
| < | | <kbd>ConnectOutput</kbd> || <kbd>void CBaseEntity::ConnectOutput(string output, string func_name)</kbd> | ||
| < | | Adds an I/O connection that will call the named function when the specified output fires. | ||
| | |||
|- | |- | ||
| < | | <kbd>DisconnectOutput</kbd> || <kbd>void CBaseEntity::DisconnectOutput(string output, string func_name)</kbd> | ||
| Removes a connected script function from an I/O event. | |||
| | |||
| | |||
|- | |- | ||
| < | | <kbd>Destroy</kbd> || <kbd>void CBaseEntity::Destroy()</kbd> | ||
| < | | Kills this entity. | ||
| | |||
|- | |- | ||
| < | | <kbd>entindex</kbd> || <kbd>int CBaseEntity::entindex()</kbd> | ||
| < | | Returns the [[Entity_index|entity index]]. | ||
| | |||
|- | |- | ||
| < | | <kbd>EmitSound</kbd> || <kbd>void CBaseEntity::EmitSound(string sound)</kbd> | ||
| < | |||
| Plays a sound from this entity. | | Plays a sound from this entity. | ||
|- | |- | ||
| < | | <kbd>EyePosition</kbd> || <kbd>Vector CBaseEntity::EyePosition()</kbd> | ||
| < | |||
| Get vector to eye position - absolute coords. | | Get vector to eye position - absolute coords. | ||
|- | |- | ||
| < | | <kbd>FirstMoveChild</kbd> || <kbd>handle CBaseEntity::FirstMoveChild()</kbd> | ||
| < | |||
| If in hierarchy, get the first move child. | | If in hierarchy, get the first move child. | ||
|- | |- | ||
| < | | <kbd>GetAngles</kbd> || <kbd>Vector CBaseEntity::GetAngles()</kbd> | ||
| < | |||
| Get entity pitch, yaw, roll as a vector. | | Get entity pitch, yaw, roll as a vector. | ||
|- | |- | ||
| < | | <kbd>GetAngularVelocity</kbd> || <kbd>Vector CBaseEntity::GetAngularVelocity()</kbd> | ||
| < | |||
| Get the local angular velocity - returns a vector of pitch,yaw,roll. | | Get the local angular velocity - returns a vector of pitch,yaw,roll. | ||
|- | |- | ||
| < | | <kbd>GetVelocity</kbd> || <kbd>Vector CBaseEntity::GetVelocity()</kbd> | ||
| < | | 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. | ||
|- | |- | ||
| < | | <kbd>GetBoundingMins</kbd> || <kbd>Vector CBaseEntity::GetBoundingMins()</kbd> | ||
| < | |||
| Get a vector containing min bounds, centered on object. | | Get a vector containing min bounds, centered on object. | ||
|- | |- | ||
| < | | <kbd>GetCenter</kbd> || <kbd>Vector CBaseEntity::GetCenter()</kbd> | ||
| < | |||
| Get vector to center of object - absolute coords. | | Get vector to center of object - absolute coords. | ||
|- | |- | ||
| < | | <kbd>GetClassname</kbd> || <kbd>string CBaseEntity::GetClassname()</kbd> | ||
| < | |||
| Get the classname of this entity. | | Get the classname of this entity. | ||
|- | |- | ||
| < | | <kbd>GetForwardVector</kbd> || <kbd>Vector CBaseEntity::GetForwardVector()</kbd> | ||
| < | |||
| Get the forward vector (+X) of the entity. | | Get the forward vector (+X) of the entity. | ||
|- | |- | ||
| < | | <kbd>GetLeftVector</kbd> || <kbd>Vector CBaseEntity::GetLeftVector()</kbd> | ||
| < | | 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]]. | ||
|- | |- | ||
| < | | <kbd>GetMaxHealth</kbd> || <kbd>int CBaseEntity::GetMaxHealth()</kbd> | ||
| | |||
| < | |||
| Returns the maximum health. | | Returns the maximum health. | ||
|- | |- | ||
| < | | <kbd>GetModelKeyValues</kbd> || <kbd>handle CBaseEntity::GetModelKeyValues()</kbd> | ||
| < | |||
| Get a KeyValue class instance on this entity's model. | | Get a KeyValue class instance on this entity's model. | ||
|- | |- | ||
| < | | <kbd>GetModelName</kbd> || <kbd>string CBaseEntity::GetModelName()</kbd> | ||
| < | |||
| Returns the name of the model. | | Returns the name of the model. | ||
|- | |- | ||
| < | | <kbd>GetMoveParent</kbd> || <kbd>handle CBaseEntity::GetMoveParent()</kbd> | ||
| < | |||
| If in hierarchy, retrieves the entity's parent. | | If in hierarchy, retrieves the entity's parent. | ||
|- | |- | ||
| < | | <kbd>GetName</kbd> || <kbd>string CBaseEntity::GetName()</kbd> | ||
| < | |||
| Get the Targetname of this entity. | | Get the Targetname of this entity. | ||
|- | |- | ||
| < | | <kbd>GetOrigin</kbd> || <kbd>Vector CBaseEntity::GetOrigin()</kbd> | ||
| < | |||
| Returns this entity's local origin. | | Returns this entity's local origin. | ||
|- | |- | ||
| < | | <kbd>GetOwner</kbd> || <kbd>handle CBaseEntity::GetOwner()</kbd> | ||
| < | |||
| Gets this entity's owner. | | Gets this entity's owner. | ||
|- | |- | ||
| < | | <kbd>GetPreTemplateName</kbd> || <kbd>string CBaseEntity::GetPreTemplateName()</kbd> | ||
| < | |||
| Get the entity name stripped of template unique decoration - the &001 suffix. | | Get the entity name stripped of template unique decoration - the &001 suffix. | ||
|- | |- | ||
| < | | <kbd>GetRootMoveParent</kbd> || <kbd>handle CBaseEntity::GetRootMoveParent()</kbd> | ||
| < | |||
| If in hierarchy, walks up the hierarchy to find the root parent | | If in hierarchy, walks up the hierarchy to find the root parent | ||
|- | |- | ||
| < | | <kbd>GetScriptId</kbd> || <kbd>string CBaseEntity::GetScriptId()</kbd> | ||
| < | | Returns the name of the entity's think function. | ||
| | |||
|- | |- | ||
| < | | <kbd>GetScriptScope</kbd> || <kbd>handle CBaseEntity::GetScriptScope()</kbd> | ||
| < | |||
| Retrieve the script-side data associated with an entity. | | Retrieve the script-side data associated with an entity. | ||
|- | |- | ||
| < | | <kbd>GetSoundDuration</kbd> || <kbd>float CBaseEntity::GetSoundDuration(string, string)</kbd> | ||
| < | |||
| Returns float duration of the sound. Takes soundname and optional actormodelname. | | Returns float duration of the sound. Takes soundname and optional actormodelname. | ||
|- | |- | ||
| < | | <kbd>GetTeam</kbd> || <kbd>int CBaseEntity::GetTeam()</kbd> | ||
| < | |||
| Get the team this entity is on. | | Get the team this entity is on. | ||
|- | |- | ||
| < | | <kbd>IsValid</kbd> || <kbd>bool CBaseEntity::IsValid()</kbd> | ||
| | |||
| < | |||
| Returns true if this entity is valid. | | Returns true if this entity is valid. | ||
|- | |- | ||
| < | | <kbd>NextMovePeer</kbd> || <kbd>handle CBaseEntity::NextMovePeer()</kbd> | ||
| < | |||
| Return the next entity in the same movement hierarchy. | | Return the next entity in the same movement hierarchy. | ||
|- | |- | ||
| < | | <kbd>PrecacheSoundScript</kbd> || <kbd>void CBaseEntity::PrecacheSoundScript(string)</kbd> | ||
| < | |||
| 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. | ||
|- | |- | ||
| < | | <kbd>SetAbsOrigin</kbd> || <kbd>void CBaseEntity::SetAbsOrigin(Vector)</kbd> | ||
| < | |||
| Teleport the entity to this world position. | | Teleport the entity to this world position. | ||
|- | |- | ||
| < | | <kbd>SetAngles</kbd> || <kbd>void CBaseEntity::SetAngles(float, float, float)</kbd> | ||
| < | |||
| Set entity pitch, yaw, roll | | Set entity pitch, yaw, roll | ||
|- | |- | ||
| < | | <kbd>SetAngularVelocity</kbd> || <kbd>void CBaseEntity::SetAngularVelocity(float, float, float)</kbd> | ||
| < | |||
| Set the local angular velocity - takes float pitch,yaw,roll velocities | | Set the local angular velocity - takes float pitch,yaw,roll velocities | ||
|- | |- | ||
| < | | <kbd>SetVelocity</kbd> || <kbd>void CBaseEntity::SetVelocity(Vector)</kbd> | ||
| < | | 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. | ||
|- | |- | ||
| < | | <kbd>SetHealth</kbd> || <kbd>void CBaseEntity::SetHealth(int)</kbd> | ||
| < | |||
| Sets the current [[health]]. | | Sets the current [[health]]. | ||
|- | |- | ||
| < | | <kbd>SetMaxHealth</kbd> || <kbd>void CBaseEntity::SetMaxHealth(int)</kbd> | ||
| < | |||
| Sets the maximum health. | | Sets the maximum health. | ||
|- | |- | ||
| < | | <kbd>SetModel</kbd> || <kbd>void CBaseEntity::SetModel(string)</kbd> | ||
| < | |||
| 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. | ||
|- | |- | ||
| < | | <kbd>SetOrigin</kbd> || <kbd>void CBaseEntity::SetOrigin(Vector)</kbd> | ||
| < | |||
| Teleport this entity to the given location. | | Teleport this entity to the given location. | ||
|- | |- | ||
| < | | <kbd>SetOwner</kbd> || <kbd>void CBaseEntity::SetOwner(handle)</kbd> | ||
| < | |||
| Sets this entity's owner. | | Sets this entity's owner. | ||
|- | |- | ||
| < | | <kbd>SetSize</kbd> || <kbd>void CBaseEntity::SetSize(Vector, Vector)</kbd> | ||
| < | |||
| Sets the bounding box size. | | Sets the bounding box size. | ||
|- | |- | ||
| < | | <kbd>SetTeam</kbd> || <kbd>void CBaseEntity::SetTeam(int)</kbd> | ||
| < | |||
| Set the team this entity is on. | | Set the team this entity is on. | ||
|- | |- | ||
| <code> | | <kbd>ValidateScriptScope</kbd> || <kbd>bool CBaseEntity::ValidateScriptScope()</kbd> | ||
| <code> | | Ensure that an entity's script scope has been created. This should be called before assigning to the entity's scope. | ||
| | |} | ||
==== 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}} | |||
|- | |- | ||
| < | | <kbd>OnPostSpawnCallChain</kbd> || <kbd>CSimpleCallChainer</kbd> | ||
| < | | Callchain instance for OnPostSpawn hooks. | ||
| | |||
|- | |- | ||
| < | | <kbd>PrecacheCallChain</kbd> || <kbd>CSimpleCallChainer</kbd> | ||
| < | | Callchain instance for Precache hooks. | ||
| | |||
|} | |} | ||
=== CBaseAnimating === | === CBaseAnimating === | ||
Extends | 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 | |||
|- | |- | ||
| < | | <kbd>GetAttachmentAngles</kbd> || <kbd>Vector CBaseAnimating::GetAttachmentAngles(int id)</kbd> | ||
| < | |||
| Get the attachment id's angles as a p,y,r vector. | | Get the attachment id's angles as a p,y,r vector. | ||
|- | |- | ||
| < | | <kbd>GetAttachmentOrigin</kbd> || <kbd>Vector CBaseAnimating::GetAttachmentOrigin(int id)</kbd> | ||
| < | |||
| Get the attachment id's origin vector | | Get the attachment id's origin vector | ||
|- | |- | ||
| < | | <kbd>GetObjectScaleLevel</kbd> || <kbd>int CBaseAnimating::GetObjectScaleLevel()</kbd> | ||
| < | |||
| The scale size of the entity | | The scale size of the entity | ||
|- | |- | ||
| < | | <kbd>IsSequenceFinished</kbd> || <kbd>bool CBaseAnimating::IsSequenceFinished()</kbd> | ||
| < | |||
| Ask whether the main sequence is done playing | | Ask whether the main sequence is done playing | ||
|- | |- | ||
| < | | <kbd>LookupAttachment</kbd> || <kbd>int CBaseAnimating::LookupAttachment(string)</kbd> | ||
| < | |||
| Get the ID for the named attachment. | | Get the ID for the named attachment. | ||
|- | |- | ||
| < | | <kbd>SetBodygroup</kbd> || <kbd>void CBaseAnimating::SetBodygroup(int group, int index)</kbd> | ||
| < | |||
| 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 | Extends {{↑|CBaseAnimating}} | ||
==== Methods ==== | ==== Methods ==== | ||
{| class="standard-table" style="width: 100%;" | {| class="standard-table" style="width: 100%;" | ||
! Function | ! Function !! Signature !! Description | ||
! Signature | |||
! Description | |||
|- | |- | ||
| < | | <kbd>GetCurrentScene</kbd> || <kbd>handle CBaseFlex::GetCurrentScene()</kbd> | ||
| < | |||
| Returns the instance of the oldest active scene entity (if any). | | Returns the instance of the oldest active scene entity (if any). | ||
|- | |- | ||
| < | | <kbd>GetSceneByIndex</kbd> || <kbd>handle CBaseFlex::GetSceneByIndex(int)</kbd> | ||
| < | |||
| 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 | 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 | |||
|- | |- | ||
| < | | <kbd>IsNoclipping</kbd> || <kbd>bool CBasePlayer::IsNoclipping()</kbd> | ||
| < | |||
| 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}} | ||
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> | ||
local ent = null; | |||
local ent = null; | while ( ent = Entities.FindByName(ent, "entityname") ) | ||
while(ent = Entities.FindByName(ent, "entityname")) | |||
{ | { | ||
//.. | // ... | ||
} | } | ||
</source> | |||
| | |||
for(local ent;ent = Entities.FindByName(ent, "entityname"); | <source lang=cpp> | ||
for (local ent; ent = Entities.FindByName(ent, "entityname"); ) | |||
{ | { | ||
//.. | // ... | ||
} | } | ||
</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 | |||
|- | |- | ||
| < | | <kbd>CreateByClassname</kbd> || <kbd>handle CEntities::CreateByClassname(string)</kbd> | ||
| < | |||
| Creates an entity by classname | | Creates an entity by classname | ||
|- | |- | ||
| < | | <kbd>FindByClassname</kbd> || <kbd>handle CEntities::FindByClassname(handle start_ent, string classname)</kbd> | ||
| < | |||
| 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 | ||
|- | |- | ||
| < | | <kbd>FindByClassnameNearest</kbd> || <kbd>handle CEntities::FindByClassnameNearest(string classname, Vector loc, float radius)</kbd> | ||
| < | |||
| Find entities by class name nearest to a point. | | Find entities by class name nearest to a point. | ||
|- | |- | ||
| < | | <kbd>FindByClassnameWithin</kbd> || <kbd>handle CEntities::FindByClassnameWithin(handle start_ent, string classname, Vector loc, float radius)</kbd> | ||
| < | |||
| 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 | ||
|- | |- | ||
| < | | <kbd>FindByModel</kbd> || <kbd>handle CEntities::FindByModel(handle start_ent, string model)</kbd> | ||
| < | |||
| 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 | ||
|- | |- | ||
| < | | <kbd>FindByName</kbd> || <kbd>handle CEntities::FindByName(handle start_ent, string targetname)</kbd> | ||
| < | |||
| 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. | ||
|- | |- | ||
| < | | <kbd>FindByNameNearest</kbd> || <kbd>handle CEntities::FindByNameNearest(string targetname, Vector loc, float radius)</kbd> | ||
| < | |||
| Find entities by name nearest to a point. | | Find entities by name nearest to a point. | ||
|- | |- | ||
| < | | <kbd>FindByNameWithin</kbd> || <kbd>handle CEntities::FindByNameWithin(handle, string, Vector loc, float radius)</kbd> | ||
| < | |||
| 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 | ||
|- | |- | ||
| < | | <kbd>FindByTarget</kbd> || <kbd>handle CEntities::FindByTarget(handle start_ent, string targetname)</kbd> | ||
| < | |||
| 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 | ||
|- | |- | ||
| < | | <kbd>FindInSphere</kbd> || <kbd>handle CEntities::FindInSphere(handle start_ent, Vector loc, float radius)</kbd> | ||
| < | |||
| 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 | ||
|- | |- | ||
| < | | <kbd>First</kbd> || <kbd>handle CEntities::First()</kbd> | ||
| < | |||
| Begin an iteration over the list of entities. Equivalent to Next(null). | | Begin an iteration over the list of entities. Equivalent to Next(null). | ||
|- | |- | ||
| < | | <kbd>Next</kbd> || <kbd>handle CEntities::Next(handle)</kbd> | ||
| < | |||
| 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 | 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 | |||
|- | |- | ||
| < | | <kbd>SpawnEntity</kbd> || <kbd>void CEnvEntityMaker::SpawnEntity()</kbd> | ||
| < | |||
| Create an entity at the location of the maker | | Create an entity at the location of the maker | ||
|- | |- | ||
| < | | <kbd>SpawnEntityAtEntityOrigin</kbd> || <kbd>void CEnvEntityMaker::SpawnEntityAtEntityOrigin(handle)</kbd> | ||
| < | |||
| Create an entity at the location of a specified entity instance | | Create an entity at the location of a specified entity instance | ||
|- | |- | ||
| < | | <kbd>SpawnEntityAtLocation</kbd> || <kbd>void CEnvEntityMaker::SpawnEntityAtLocation(Vector, Vector)</kbd> | ||
| < | |||
| 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) | ||
|- | |- | ||
| < | | <kbd>SpawnEntityAtNamedEntityOrigin</kbd> || <kbd>void CEnvEntityMaker::SpawnEntityAtNamedEntityOrigin(string)</kbd> | ||
| < | |||
| Create an entity at the location of a named entity | | Create an entity at the location of a named entity | ||
|} | |} | ||
=== CLinkedPortalDoor === | === CLinkedPortalDoor === | ||
{{ | 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 | |||
|- | |- | ||
| < | | <kbd>GetPartnerInstance</kbd> || <kbd>handle CLinkedPortalDoor::GetPartnerInstance()</kbd> | ||
| < | |||
| Get the instance handle of the door's linked partner | | Get the instance handle of the door's linked partner | ||
|- | |- | ||
| < | | <kbd>GetPartnername</kbd> || <kbd>string CLinkedPortalDoor::GetPartnername()</kbd> | ||
| < | |||
| 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 === | ||
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 | |||
|- | |- | ||
| < | | <kbd>GetPlayerSpeechDuration</kbd> || <kbd>float CPlayerVoiceListener::GetPlayerSpeechDuration(int)</kbd> | ||
| < | |||
| Returns the number of seconds the player has been continuously speaking. | | Returns the number of seconds the player has been continuously speaking. | ||
|- | |- | ||
| < | | <kbd>IsPlayerSpeaking</kbd> || <kbd>bool CPlayerVoiceListener::IsPlayerSpeaking(int)</kbd> | ||
| < | |||
| Returns whether the player specified is speaking. | | Returns whether the player specified is speaking. | ||
|} | |} | ||
=== CPointTemplate === | |||
Extends {{↑|CBaseEntity}} | |||
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%;" | {| class="standard-table" style="width: 100%;" | ||
! | ! Instance !! Type !! Description | ||
! | |||
! Description | |||
|- | |- | ||
| <code> | | <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 ==== | |||
{| class="standard-table" style="width: 100%;" | |||
|- style="position:sticky; z-index:10; top:0" | |||
! Function !! Signature !! Description | |||
|- | |- | ||
| < | | <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 = | |||
{ | |||
rendercolor = "0 255 0" | |||
targetname = "mySpawnedEntity" | |||
} | |||
return keyvalues | |||
} | |||
</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; | |||
m_hSpawner <- Entities.CreateByClassname( "env_entity_maker" ); | |||
m_hSpawner.__KeyValueFromString( "EntityTemplate", self.GetName() ); | |||
function PreSpawnInstance( classname, targetname ) | |||
{ | |||
return m_KeyValues; | |||
} | |||
function PostSpawn( entities ) | |||
{ | |||
foreach ( targetname, entity in entities ) | |||
{ | |||
m_hSpawnedEntity = entity; | |||
break; | |||
} | |||
} | |||
::SpawnMyEntity <- function( keyvalues = null ) | |||
{ | |||
m_KeyValues = keyvalues; | |||
m_hSpawner.SpawnEntity(); | |||
return m_hSpawnedEntity; | |||
}.bindenv(this) | |||
</source> | |||
Spawn templated entities from any script. | |||
<source lang="cpp"> | |||
local ent = SpawnMyEntity( { | |||
rendercolor = Vector( RandomInt(0, 255), RandomInt(0, 255), RandomInt(0, 255) ) | |||
} ) | |||
printl( ent ) | |||
</source> | |||
}} | |||
=== | === CPortal_Player === | ||
{{ | 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 | |- | ||
| <kbd>GetWheatleyMonitorDestructionCount</kbd> || <kbd>int CPortal_Player::GetWheatleyMonitorDestructionCount()</kbd> | |||
| Get number of wheatley monitors destroyed by the player. | |||
|- | |||
| <kbd>IncWheatleyMonitorDestructionCount</kbd> || <kbd>void CPortal_Player::IncWheatleyMonitorDestructionCount()</kbd> | |||
| Set number of wheatley monitors destroyed by the player. | |||
|- | |- | ||
| < | | <kbd>TurnOffPotatos</kbd> || <kbd>void CPortal_Player::TurnOffPotatos()</kbd> | ||
| < | | Turns Off the Potatos material light | ||
| | |||
|- | |- | ||
| < | | <kbd>TurnOnPotatos</kbd> || <kbd>void CPortal_Player::TurnOnPotatos()</kbd> | ||
| < | | Turns On the Potatos material light | ||
| | |||
|} | |} | ||
=== CSceneEntity === | === CSceneEntity === | ||
Extends | 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 | |||
|- | |- | ||
| < | | <kbd>AddBroadcastTeamTarget</kbd> || <kbd>void CSceneEntity::AddBroadcastTeamTarget(int)</kbd> | ||
| < | |||
| Adds a team (by index) to the broadcast list | | Adds a team (by index) to the broadcast list | ||
|- | |- | ||
| < | | <kbd>EstimateLength</kbd> || <kbd>float CSceneEntity::EstimateLength()</kbd> | ||
| < | |||
| Returns length of this scene in seconds. | | Returns length of this scene in seconds. | ||
|- | |- | ||
| < | | <kbd>FindNamedEntity</kbd> || <kbd>handle CSceneEntity::FindNamedEntity(string)</kbd> | ||
| < | |||
| 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 | ||
|- | |- | ||
| < | | <kbd>IsPaused</kbd> || <kbd>bool CSceneEntity::IsPaused()</kbd> | ||
| < | |||
| If this scene is currently paused. | | If this scene is currently paused. | ||
|- | |- | ||
| < | | <kbd>IsPlayingBack</kbd> || <kbd>bool CSceneEntity::IsPlayingBack()</kbd> | ||
| < | |||
| If this scene is currently playing. | | If this scene is currently playing. | ||
|- | |- | ||
| < | | <kbd>LoadSceneFromString</kbd> || <kbd>bool CSceneEntity::LoadSceneFromString(string, string)</kbd> | ||
| < | |||
| given a dummy scene name and a vcd string, load the scene | | given a dummy scene name and a vcd string, load the scene | ||
|- | |- | ||
| < | | <kbd>RemoveBroadcastTeamTarget</kbd> || <kbd>void CSceneEntity::RemoveBroadcastTeamTarget(int)</kbd> | ||
| < | |||
| 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 | |||
|- | |- | ||
| < | | <kbd>FindKey</kbd> || <kbd>handle CScriptKeyValues::FindKey(string)</kbd> | ||
| < | |||
| 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 | ||
|- | |- | ||
| < | | <kbd>GetFirstSubKey</kbd> || <kbd>handle CScriptKeyValues::GetFirstSubKey()</kbd> | ||
| < | |||
| Given a KeyValues object, return the first sub key object | | Given a KeyValues object, return the first sub key object | ||
|- | |- | ||
| < | | <kbd>GetKeyBool</kbd> || <kbd>bool CScriptKeyValues::GetKeyBool(string)</kbd> | ||
| < | |||
| Given a KeyValues object and a key name, return associated bool value | | Given a KeyValues object and a key name, return associated bool value | ||
|- | |- | ||
| < | | <kbd>GetKeyFloat</kbd> || <kbd>float CScriptKeyValues::GetKeyFloat(string)</kbd> | ||
| < | |||
| Given a KeyValues object and a key name, return associated float value | | Given a KeyValues object and a key name, return associated float value | ||
|- | |- | ||
| < | | <kbd>GetKeyInt</kbd> || <kbd>int CScriptKeyValues::GetKeyInt(string)</kbd> | ||
| < | |||
| Given a KeyValues object and a key name, return associated integer value | | Given a KeyValues object and a key name, return associated integer value | ||
|- | |- | ||
| < | | <kbd>GetKeyString</kbd> || <kbd>string CScriptKeyValues::GetKeyString(string)</kbd> | ||
| < | |||
| Given a KeyValues object and a key name, return associated string value | | Given a KeyValues object and a key name, return associated string value | ||
|- | |- | ||
| < | | <kbd>GetNextKey</kbd> || <kbd>handle CScriptKeyValues::GetNextKey()</kbd> | ||
| < | |||
| 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 | ||
|- | |- | ||
| < | | <kbd>IsKeyEmpty</kbd> || <kbd>bool CScriptKeyValues::IsKeyEmpty(string)</kbd> | ||
| < | |||
| 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 | ||
|- | |- | ||
| < | | <kbd>ReleaseKeyValues</kbd> || <kbd>void CScriptKeyValues::ReleaseKeyValues()</kbd> | ||
| < | |||
| Given a root KeyValues object, release its contents | | Given a root KeyValues object, release its contents | ||
|} | |} | ||
=== CTriggerCamera === | === CTriggerCamera === | ||
Extends | 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 | |||
|- | |- | ||
| < | | <kbd>GetFov</kbd> || <kbd>int CTriggerCamera::GetFov()</kbd> | ||
| < | |||
| get camera's current fov setting as integer | | get camera's current fov setting as integer | ||
|- | |- | ||
| < | | <kbd>SetFov</kbd> || <kbd>void CTriggerCamera::SetFov(int, float)</kbd> | ||
| < | |||
| 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}} | |||
|} | |||
=== | === CCallChainer === | ||
'''CCallChainer''' objects collect all functions with a matching prefix in a given scope, then inserts it all into the <code>chains</code> table with the prefix removed. All collected unprefixed functions can then be called in a chain using the class's <code>Call()</code> method, given the method's ''event'' argument matches the functions' name. | |||
Whenever a '''CCallChainer''' object is created, a function named <code>Dispatch</code> followed by its given prefix will also be created, which the class binds the environment of its <code>Call()</code> method to. | |||
==== Methods ==== | |||
{| class="standard-table" style="width: 100%;" | {| class="standard-table" style="width: 100%;" | ||
! Function | ! Function !! Signature !! Description | ||
! Signature | |||
! Description | |||
|- | |- | ||
| < | | <kbd>constructor</kbd> || <kbd>CCallChainer(string ''functionPrefix'', table ''scope'' = null)</kbd> | ||
| < | | Creates a CCallChainer object that'll collect functions that have a matching prefix in the given scope. | ||
| | |||
|- | |- | ||
| < | | <kbd>PostScriptExecute</kbd> || <kbd>void CCallChainer::PostScriptExecute()</kbd> | ||
| < | | Search for all non-native functions with matching prefixes, then push them into the <code>chains</code> table. | ||
| | |||
|- | |- | ||
| < | | <kbd>Call</kbd> || <kbd>bool CCallChainer::Call(string ''event'', any ...)</kbd> | ||
| < | | Find an unprefixed function name in the <code>chains</code> table and call it with the given arguments. | ||
| | |} | ||
==== Members ==== | |||
{| class="standard-table" style="width: 100%;" | |||
! Instance !! Type !! Description | |||
|- | |- | ||
| < | | <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 | |||
|- | |- | ||
| < | | <kbd>constructor</kbd> || <kbd>CSimpleCallChainer(string ''functionPrefix'', table ''scope'' = null, exactMatch = false)</kbd> | ||
| < | | Creates a CSimpleCallChainer object that'll collect functions that have a matching prefix in the given scope, unless it seek for an exact name match. Also automatically exposes two bound global functions to dispatch to this object: <code>DispatchPrecache()</code> and <code>DispatchOnPostSpawn()</code>. | ||
| | |||
|- | |- | ||
| < | | <kbd>PostScriptExecute</kbd> || <kbd>void CSimpleCallChainer::PostScriptExecute()</kbd> | ||
| < | | Begin searching for all non-native functions with matching prefixes, then push them into the <code>chain</code> array. | ||
| | |||
|- | |- | ||
| < | | <kbd>Call</kbd> || <kbd>bool CSimpleCallChainer::Call(any ...)</kbd> | ||
| < | | Call all functions inside the <code>chain</code> array with the given arguments. | ||
| | |} | ||
==== Members ==== | |||
{| class="standard-table" style="width: 100%;" | |||
|- style="position:sticky; z-index:10; top:0" | |||
! Instance !! Type !! Description | |||
|- | |- | ||
| < | | <kbd>chain</kbd> || <kbd>array</kbd> | ||
| < | | All functions to be called by the <code>Call()</code> method. | ||
| | |||
|- | |- | ||
| < | | <kbd>exactMatch</kbd> || <kbd>bool</kbd> | ||
| < | | If set, names of non-native functions and <code>prefix</code> must be an exact match. Set by the constructor. | ||
| | |||
|- | |- | ||
| < | | <kbd>prefix</kbd> || <kbd>string</kbd> | ||
| < | | Prefix that functions should have to be added into the <code>chain</code> array. Set by the constructor. | ||
| | |||
|- | |- | ||
| < | | <kbd>scope</kbd> || <kbd>table</kbd> | ||
| <code> | | 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. | |||
{{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 | |||
|- | |||
| <kbd>Begin</kbd> || <kbd> void LateBinder::Begin(table ''target'', bool ''log'' = false)</kbd> | |||
| {{todo}} | |||
|- | |||
| <kbd>End</kbd> || <kbd> void LateBinder::End()</kbd> | |||
| {{todo}} | |||
|- | |||
| <kbd>EstablishDelegation</kbd> || <kbd> void LateBinder::EstablishDelegation(table ''parentTable'', table ''childTable'')</kbd> | |||
| {{todo}} | |||
|- | |- | ||
| < | | <kbd>RemoveDelegation</kbd> || <kbd> void LateBinder::EstablishDelegation(table ''parentTable'', table ''childTable'')</kbd> | ||
| < | | {{todo}} | ||
| | |||
|- | |- | ||
| < | | <kbd>HookRootMetamethod</kbd> || <kbd> void LateBinder::HookRootMetamethod(string ''name'', unknown ''value'')</kbd> | ||
| < | | "private" method. {{todo}} | ||
| | |||
|- | |- | ||
| < | | <kbd>UnhookRootMetamethod</kbd> || <kbd> void LateBinder::UnhookRootMetamethod(string ''name'')</kbd> | ||
| < | | {{todo}} | ||
| | |||
|- | |- | ||
| < | | <kbd>Log</kbd> || <kbd> void LateBinder::Log(string ''string'')</kbd> | ||
| < | | {{todo}} | ||
| | |||
|- | |- | ||
| < | | <kbd>Resolve</kbd> || <kbd> bool LateBinder::Resolve(table ''lookupTable'', table<nowiki>|</nowiki>array ''subTableOrArray'', bool ''throwException'' = false )</kbd> | ||
| < | | {{todo}} | ||
| | |||
|} | |} | ||
==== 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 === | ||
Squirrel equivalent of the C++ [[Vector]] class. A three-dimensional vector with overloaded arithmetic operations for both Vectors and scalar values. | |||
==== Methods ==== | ==== Methods ==== | ||
{| class="standard-table" style="width: 100%;" | {| class="standard-table" style="width: 100%;" | ||
! Function | |- 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. | |||
|- | |- | ||
| < | | <kbd>Cross</kbd> || <kbd>Vector Vector::Cross(Vector other)</kbd> | ||
| < | |||
| Return the vector cross product - <code>this × other</code>. | | Return the vector cross product - <code>this × other</code>. | ||
|- | |- | ||
| < | | <kbd>Dot</kbd> || <kbd>float Vector::Dot(Vector other)</kbd> | ||
| < | |||
| Return the vector dot product - <code>this · other</code>. | | Return the vector dot product - <code>this · other</code>. | ||
|- | |- | ||
| < | | <kbd>Length</kbd> || <kbd>float Vector::Length()</kbd> | ||
| < | |||
| Return the distance from the origin. | | Return the distance from the origin. | ||
|- | |- | ||
| < | | <kbd>Length2D</kbd> || <kbd>float Vector::Length2D()</kbd> | ||
| < | |||
| Return the distance from the origin, ignoring the Z axis. | | Return the distance from the origin, ignoring the Z axis. | ||
|- | |- | ||
| < | | <kbd>LengthSqr</kbd> || <kbd>float Vector::LengthSqr()</kbd> | ||
| < | |||
| 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. | ||
|- | |- | ||
| < | | <kbd>Length2DSqr</kbd> || <kbd>float Vector::Length2DSqr()</kbd> | ||
| < | |||
| 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. | ||
|- | |- | ||
| < | | <kbd>Norm</kbd> || <kbd>float Vector::Norm()</kbd> | ||
| < | |||
| 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. | ||
|- | |- | ||
| < | | <kbd>ToKVString</kbd> || <kbd>string Vector::ToKVString()</kbd> | ||
| < | |||
| 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%;" | {| class="standard-table" style="width: 100%;" | ||
! Function | |- style="position:sticky; z-index:10; top:0" | ||
! Signature | ! Function !! Signature !! Description | ||
! 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. | |||
|- | |- | ||
| <code> | | <kbd>DebugDrawLine</kbd> || <kbd>void DebugDrawLine(Vector start, Vector end, int r, int g, int b, bool hitTest, float duration)</kbd> | ||
| <code>void Assert(''exp'', string ''message'' = null)</ | | 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. | |||
{| class="standard-table" style="width: 100%;" | |||
|- style="position:sticky; z-index:10; top:0" | |||
! Function !! Signature !! 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. | |||
|- | |||
| <kbd>CoopSetCameFromLastDLCMap</kbd> || <kbd>void CoopSetCameFromLastDLCMap(bool)</kbd> | |||
| 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. | ||
|- | |- | ||
| < | | <kbd>CreateProp</kbd> || <kbd>handle CreateProp(string classname, Vector origin, string modelname, int activity)</kbd> | ||
| < | |||
| Create a prop. The class should be a prop_physics style entity. | | Create a prop. The class should be a prop_physics style entity. | ||
|- | |- | ||
| < | | <kbd>CreateSceneEntity</kbd> || <kbd>handle CreateSceneEntity(string)</kbd> | ||
| < | |||
| Create a scene entity to play the specified scene. | | Create a scene entity to play the specified scene. | ||
|- | |- | ||
| < | | <kbd>dummy</kbd> || <kbd>void dummy()</kbd> | ||
| | | Dummy function. Does nothing. | ||
| | |||
| | |||
|- | |- | ||
| < | | <kbd>DoIncludeScript</kbd> || <kbd>bool DoIncludeScript(string ''filename'', table ''scope'')</kbd> | ||
| < | |||
| 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. | ||
|- | |- | ||
| < | | <kbd>IncludeScript</kbd> || <kbd>bool IncludeScript(string ''filename'', table ''scope'' = null)</kbd> | ||
| < | |||
| 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. | ||
|- | |- | ||
| < | | <kbd>DoEntFire</kbd> || <kbd>void DoEntFire(string ''target'', string ''action'', string ''value'', float ''delay'', handle ''activator'', handle ''caller'')</kbd> | ||
| < | |||
| Generate an entity [[I/O]] event. | | Generate an entity [[I/O]] event. | ||
|- | |- | ||
| < | | <kbd>EntFire</kbd> || <kbd>function EntFire(target, action, value, delay, activator)</kbd> | ||
| < | |||
| Generate an entity [[I/O]] event. Value, delay and activator are optional. | | Generate an entity [[I/O]] event. Value, delay and activator are optional. | ||
|- | |- | ||
| < | | <kbd>EntFireByHandle</kbd> || <kbd>void EntFireByHandle(handle target, string action, string value, float delay, handle activator, handle caller)</kbd> | ||
| < | |||
| Generate an entity I/O event. First parameter is an entity instance. | | Generate an entity I/O event. First parameter is an entity instance. | ||
|- | |- | ||
| < | | <kbd>FrameTime</kbd> || <kbd>float FrameTime()</kbd> | ||
| < | |||
| Get the time spent on the server in the last frame. | | Get the time spent on the server in the last frame. | ||
|- | |- | ||
| < | | <kbd>GetDeveloperLevel</kbd> || <kbd>int GetDeveloperLevel()</kbd> | ||
| < | |||
| Gets the level of 'developer'. | | Gets the level of 'developer'. | ||
|- | |- | ||
| < | | <kbd>GetFunctionSignature</kbd> || <kbd>string GetFunctionSignature(function ''function'', string ''name'')</kbd> | ||
| < | | {{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. | ||
|- | |- | ||
| < | | <kbd>GetMapName</kbd> || <kbd>string GetMapName()</kbd> | ||
| < | |||
| Get the name of the map. | | Get the name of the map. | ||
|- | |- | ||
| < | | <kbd>GetNumMapsPlayed</kbd> || <kbd>int GetNumMapsPlayed()</kbd> | ||
| < | |||
| Returns how many workshop maps the player has played through. | | Returns how many workshop maps the player has played through. | ||
|- | |- | ||
| < | | <kbd>GetPlayerSilenceDuration</kbd> || <kbd>float GetPlayerSilenceDuration(int player_index)</kbd> | ||
| < | |||
| Time that the specified player has been silent on the mic. | | Time that the specified player has been silent on the mic. | ||
|- | |- | ||
| < | | <kbd>IsMultiplayer</kbd> || <kbd>bool IsMultiplayer()</kbd> | ||
| < | |||
| Returns true if this is a multiplayer game, or false if singleplayer. | | Returns true if this is a multiplayer game, or false if singleplayer. | ||
|- | |- | ||
| < | | <kbd>LoopSinglePlayerMaps</kbd> || <kbd>bool LoopSinglePlayerMaps()</kbd> | ||
| < | |||
| 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. | ||
|- | |- | ||
| < | | <kbd>RandomFloat</kbd> || <kbd>float RandomFloat(float min, float max)</kbd> | ||
| < | |||
| Generate a random floating point number within a range, inclusive | | Generate a random floating point number within a range, inclusive | ||
|- | |- | ||
| < | | <kbd>RandomInt</kbd> || <kbd>int RandomInt(int min, int max)</kbd> | ||
| < | |||
| Generate a random integer within a range, inclusive | | Generate a random integer within a range, inclusive | ||
|- | |- | ||
| < | | <kbd>RecordAchievementEvent</kbd> || <kbd>void RecordAchievementEvent(string name, int player_index)</kbd> | ||
| < | |||
| Earns a given achievement or increases progress. | | Earns a given achievement or increases progress. | ||
|- | |- | ||
| < | | <kbd>RequestMapRating</kbd> || <kbd>void RequestMapRating()</kbd> | ||
| < | |||
| In workshop maps, pops up the map rating dialog for user input. | | In workshop maps, pops up the map rating dialog for user input. | ||
|- | |- | ||
| < | | <kbd>SendToConsole</kbd> || <kbd>void SendToConsole(string command)</kbd> | ||
| | |||
| < | |||
| 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. | ||
|- | |- | ||
| < | | <kbd>SetDucking</kbd> || <kbd>void SetDucking(string, string, float)</kbd> | ||
| < | |||
| Set the level of an audio ducking channel. | | Set the level of an audio ducking channel. | ||
|- | |- | ||
| < | | <kbd>SetMapAsPlayed</kbd> || <kbd>int SetMapAsPlayed()</kbd> | ||
| < | |||
| 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. | ||
|- | |- | ||
| < | | <kbd>Time</kbd> || <kbd>float Time()</kbd> | ||
| | |||
| < | |||
| Get the current server time | | Get the current server time | ||
|- | |- | ||
| < | | <kbd>TraceLine</kbd> || <kbd>float TraceLine(Vector start, Vector end, handle ignored_ent)</kbd> | ||
| < | |||
| 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. | ||
|- | |- | ||
| < | | <kbd>UniqueString</kbd> || <kbd>string UniqueString(string ''suffix'' = "")</kbd> | ||
| < | |||
| 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>. | ||
|- | |- | ||
| < | | <kbd>DoUniqueString</kbd> || <kbd>string DoUniqueString(string ''suffix'')</kbd> | ||
| < | |||
| 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. | ||
|- | |- | ||
| < | | <kbd>VSquirrel_OnCreateScope</kbd> || <kbd>table(?) VSquirrel_OnCreateScope(string ''name'', table(?) ''outer'')</kbd> | ||
| < | | 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 ==== | |||
=== | {| 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 | ==== 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 | ||
! | |- | ||
| <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>). | |||
|- | |||
| <kbd>sin</kbd> || <kbd> float sin(float ''x'')</kbd> | |||
| Returns the sine of <kbd>''x''</kbd> (<kbd>sin(x)</kbd>). | |||
|- | |||
| <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>⌉). | ||
| Returns the | |||
|- | |- | ||
| < | | <kbd>pow</kbd> || <kbd>float pow(float ''x'', float ''y'')</kbd> | ||
| < | | Returns <kbd>''x''</kbd> raised to the power of <kbd>''y''</kbd> (<kbd>x<sup>y</sup></kbd>). | ||
| | |||
|- | |- | ||
| < | | <kbd>exp</kbd> || <kbd>float exp(float ''x'')</kbd> | ||
| < | | Returns the exponential value of <kbd>''x''</kbd> (<kbd>e<sup>x</sup></kbd>). | ||
| | |||
|- | |- | ||
| < | | <kbd>log</kbd> || <kbd>float log(float ''x'')</kbd> | ||
| < | | Returns the natural logarithm of <kbd>''x''</kbd> (<kbd>log<sub>e</sub>(x) = ln(x)</kbd>). | ||
| | |||
|- | |- | ||
| < | | <kbd>log10</kbd> || <kbd> float log10(float ''x'')</kbd> | ||
| < | | Returns the logarithm base-10 of <kbd>''x''</kbd> (<kbd>log<sub>10</sub>(x)</kbd>). | ||
| | |||
|- | |- | ||
| < | | <kbd>sqrt</kbd> || <kbd>float sqrt(float ''x'')</kbd> | ||
| < | | Returns the square root of <kbd>''x''</kbd> (√<span style="text-decoration:overline"><kbd>x</kbd></span>). | ||
| | |||
|- | |- | ||
| < | | <kbd>rand</kbd> || <kbd>int rand()</kbd> | ||
| < | | Returns a pseudorandom integer in the range 0 to <kbd>RAND_MAX</kbd> (<kbd>0 ≤ rand() ≤ RAND_MAX</kbd>). | ||
| | |||
|- | |- | ||
| < | | <kbd>srand</kbd> || <kbd>void srand(float ''seed'')</kbd> | ||
| < | | Sets the starting point for generating a series of pseudorandom integers. | ||
| | |||
|} | |} | ||
=== | === 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. | |||
|} | |||
==== 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 | |||
|- | |- | ||
| <code> | | <kbd>constructor</kbd> || <kbd>regexp(string ''pattern'')</kbd> | ||
| <code>void | | Creates and compiles a regular expression represented by ''pattern''. | ||
| Adds | {{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. | |||
|- | |||
| <kbd>slice</kbd> || <kbd>string slice(int ''start_index'', int ''end_index'' = null)</kbd> | |||
| 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). | |||
|- | |||
| <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. | |||
|- | |- | ||
| < | | <kbd>bindenv</kbd> || <kbd>function bindenv(table ''env'')</kbd> | ||
| <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''. | ||
| | {{note|The created function holds a weak reference to its environment object so it cannot be used to control its lifetime.}} | ||
|- | |- | ||
| < | | <kbd>getinfos</kbd> || <kbd>table getinfos()</kbd> | ||
| < | | Returns a table containing informations about the function, like parameters, name and source name. | ||
{{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> | |||
}} | |||
|- | |- | ||
| < | | <kbd>tostring</kbd> || <kbd>string tostring()</kbd> | ||
| < | | Returns a string in the form "<kbd>(closure: <''pointer''>)</kbd>". | ||
| | |||
|- | |- | ||
| < | | <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd> | ||
| < | | Returns a weak reference to the object. | ||
| Returns the | |} | ||
==== Class ==== | |||
{| class="standard-table" style="width:100%" | |||
|- style="position:sticky; z-index:10; top:0" | |||
! Function !! Signature !! Description | |||
|- | |- | ||
| < | | <kbd>instance</kbd> || <kbd>instance instance()</kbd> | ||
| < | | 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 | |||
|- | |- | ||
| < | | <kbd>getattributes</kbd> || <kbd>any getattributes(string ''membername'')</kbd> | ||
| < | | Returns the attributes of the specified member. If the parameter member is null, the function returns the class-level attributes. | ||
| Returns the | |||
|- | |- | ||
| < | | <kbd>setattributes</kbd> || <kbd>any setattributes(string ''membername'', any ''value'')</kbd> | ||
| < | | Sets the attribute of the specified member and returns the previous attribute value. If the parameter member is null, sets the class-level attributes. | ||
| | |||
|- | |- | ||
| < | | <kbd>rawin</kbd> || <kbd>bool rawin(any ''key'')</kbd> | ||
| < | | Checks for the presence of the specified key in the class without employing delegation. | ||
| | |||
|- | |- | ||
| < | | <kbd>tostring</kbd> || <kbd>string tostring()</kbd> | ||
| < | | Returns a string in the form "<kbd>(class: <''pointer''>)</kbd>". | ||
| | |||
|- | |- | ||
| < | | <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd> | ||
| < | | Returns a weak reference to the object. | ||
| Returns | |} | ||
==== Class instance ==== | |||
{| class="standard-table" style="width:100%" | |||
|- style="position:sticky; z-index:10; top:0" | |||
! Function !! Signature !! Description | |||
|- | |- | ||
| < | | <kbd>getclass</kbd> || <kbd>class getclass()</kbd> | ||
| < | | Returns the class that created the instance. | ||
| | |||
|- | |- | ||
| < | | <kbd>rawin</kbd> || <kbd>bool rawin(any ''key'')</kbd> | ||
| < | | Checks for the presence of the specified key in the instance without employing delegation. | ||
| | |||
|- | |- | ||
| < | | <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>(instance: <''pointer''>)</kbd>". | ||
| | |||
|- | |- | ||
| < | | <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd> | ||
| < | | Returns a weak reference to the object. | ||
| | |} | ||
==== Generator ==== | |||
{| class="standard-table" style="width:100%" | |||
|- style="position:sticky; z-index:10; top:0" | |||
! Function !! Signature !! Description | |||
|- | |- | ||
| < | | <kbd>getstatus</kbd> || <kbd>string getstatus()</kbd> | ||
| < | | Returns the status of the generator as string: "running", "dead" or "suspended". | ||
| Returns | |||
|- | |- | ||
| < | | <kbd>tostring</kbd> || <kbd>string tostring()</kbd> | ||
| < | | Returns a string in the form "<kbd>(generator: <''pointer''>)</kbd>". | ||
| Returns | |||
|- | |- | ||
| < | | <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd> | ||
| <code> | | 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. <code>thread.call()</code>. | |||
{| class="standard-table" style="width:100%" | |||
|- style="position:sticky; z-index:10; top:0" | |||
! Function !! Signature !! Description | |||
|- | |- | ||
| < | | <kbd>call</kbd> || <kbd>any call(any ''args''...)</kbd> | ||
| < | | 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 | |||
|- | |- | ||
| < | | <kbd>getstatus</kbd> || <kbd>string getstatus()</kbd> | ||
| < | | Returns the status of the thread ("idle", "running", "suspended"). | ||
| Returns | |||
|- | |- | ||
| < | | <kbd>tostring</kbd> || <kbd>string tostring()</kbd> | ||
| < | | Returns a string in the form "<kbd>(thread: <''pointer''>)</kbd>". | ||
| Returns | |||
|- | |- | ||
| < | | <kbd>wakeup</kbd> || <kbd>any wakeup(any ''return'' = null)</kbd> | ||
| < | | 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. | ||
| | |||
|- | |- | ||
| < | | <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd> | ||
| <code> | | Returns a weak reference to the object. | ||
| | |} | ||
===== 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 | |||
|- | |- | ||
| < | | <kbd>newthread</kbd> || <kbd>thread newthread(function ''threadfunc'')</kbd> | ||
| < | | Creates a new cooperative thread object (coroutine) and returns it. | ||
| | {{warning|Coroutines introduce their own additional overhead and require very specific configuration to avoid server crashes. {{workaround|Use a [https://developer.electricimp.com/squirrel/squirrel-guide/functions#generator-functions generator function] instead. Generators can spread expensive functions across multiple frames to avoid stutters/timeouts. | ||
[https://github.com/ficool2/TF2Ware_Ultimate/blob/d698583894b87f5b94f99a0535f40fafd34a98ce/scripts/vscripts/tf2ware_ultimate/main.nut#L416 Real world TF2 example]}}}} | |||
|- | |- | ||
| <code> | | <kbd>suspend</kbd> || <kbd>any suspend(any ''return'' = this)</kbd> | ||
| Suspends the coroutine that called this function. Needs to be called inside the thread's function body. Accepts a optional parameter that will be used as return value for the function that woke up the thread (<code>wakeup</code> method). If nothing is passed defaults to <code>this</code> (the scope in which this function was called). The returned value will be received on the next thread wake up depending on what was passed in the <code>wakeup</code> method. | |||
| | |} | ||
==== Weak reference ==== | |||
Weak references let you reference an object without preventing it from being garbage collected. They're useful when you want to refer to an object, but don't want to increase its reference count and keep it alive unnecessarily. When the object pointed by weak reference is destroyed, the weak reference is automatically set to null. <code>weakref</code> method that returns weak reference to an object exist on every object in squirrel, but primitive types like numbers will return itself since they're stored differently, therefore making this method redundant. Everything else works as expected. | |||
{| class="standard-table" style="width:100%" | |||
|- style="position:sticky; z-index:10; top:0" | |||
! Function !! Signature !! Description | |||
|- | |- | ||
| < | | <kbd>ref</kbd> || <kbd>instance ref()</kbd> | ||
| < | | Returns the object that the weak reference is pointing at, or null if the object that it was pointing to was destroyed. | ||
| | |||
|- | |- | ||
| < | | <kbd>tostring</kbd> || <kbd>string tostring()</kbd> | ||
| < | | Returns a string in the form "<kbd>(weakref: <''pointer''>)</kbd>". | ||
| | |||
|- | |- | ||
| < | | <kbd>weakref</kbd> || <kbd>weakref weakref()</kbd> | ||
| < | | Returns a weak reference to the object. | ||
| | |||
|} | |} | ||
Line 1,080: | Line 1,789: | ||
* [[VScript Fundamentals]] | * [[VScript Fundamentals]] | ||
* {{sq}} [[Squirrel]] | * {{sq}} [[Squirrel]] | ||
* {{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
This list contains all engine-related Squirrel classes, functions, and variables available for VScript in
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.

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. ![]() To re-enable this behavior, define the following in the root table:
Then to use this system, define a function in an entity script with a name of the format |
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.![]() |
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.![]() |
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"); )
{
// ...
}
|

- 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 |
__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.
| |
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
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:
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.
![]() |
_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. ![]() /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. ![]() |
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
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. |

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

::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.
![]() \\ 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.
![]() |
_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.
![]() | |
getinfos | table getinfos() | Returns a table containing informations about the function, like parameters, name and source name.
| |
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.
![]() ![]() |
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. |