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

List of ​Portal 2​ Script Functions

From Valve Developer Community
< Portal 2‎ | Scripting
Revision as of 23:37, 17 September 2025 by BetweenReality (talk | contribs) (→‎CPlayerVoiceListener: Add information about this)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
English (en)中文 (zh)Translate (Translate)


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

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

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

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

Global variables

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

Global hooks

These hooks only work when defined in the root table.

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

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

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

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

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

Classes

CBaseEntity

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

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

Methods

Function Signature Description
__KeyValueFromInt
__KeyValueFromFloat
__KeyValueFromString
__KeyValueFromVector
bool __KeyValueFromInt(string key, int value)
bool __KeyValueFromFloat(string key, int value)
bool __KeyValueFromString(string key, string value)
bool __KeyValueFromVector(string key, Vector value)
Sets an entity keyvalue from a specific data type. Returns true if successfully set, false if it the key does not exist.

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

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

Metamethods

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

Hooks

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

Function Signature Description
DispatchOnPostSpawn void DispatchOnPostSpawn() Called after the entity spawns.
If both this function and OnPostSpawn() are defined, this one takes precedence and the other never runs.
Note.pngNote:This hook is predefined internally by CSimpleCallChainer ↓ but it won't have any effect until redefined.
DispatchPrecache void DispatchPrecache() This is called during entity spawning and after restore to allow scripts to precache any resources they need.
If both this function and Precache() are defined, this one takes precedence and the other never runs.
Note.pngNote:This hook is predefined internally by CSimpleCallChainer ↓ but it won't have any effect until redefined.
Input<InputName> bool Input<InputName>() Called when the entity receives an I/O input that matches the function's name. The name that follows after Input must match the casing, i.e. InputFireUser1 will catch any "FireUser1" inputs but not "fireuser1" inputs from the ent_fire command.

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

OnPostSpawn void OnPostSpawn() Called after the entity spawns, which is after scripts and players have loaded. This could be used to have an entity register itself with a master script, or adjusting the entity parameters in a programmatic way.
If both this function and DispatchOnPostSpawn() are defined, that one takes precedence and this one never runs.
Precache void Precache() Called after the script executes. Can be used to call precache functions for models and sounds on map load.
If both this function and DispatchPrecache() are defined, that one takes precedence and this one never runs.

Variables

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

CBaseAnimating

Extends CBaseEntity ↑

Script handle class for animating entities such as props.

Methods

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

CBaseFlex

Extends CBaseAnimating ↑

Methods

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

CBasePlayer

Extends CBaseAnimating ↑

Script handle class for player entities.

Methods

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

CEntities

Script instance: Entities

An interface to find and iterate over the script handles for the entities in play. To iterate over a set of entities, pass null to the previous parameter in the appropriate method to start an iteration. A reference to a previously-found entity can be used instead to continue a search. The entity index is used to determine the order of the search; any entity with an entity index smaller than the one in previous is skipped over. [confirm]

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

local ent = null;
while ( ent = Entities.FindByName(ent, "entityname") )
{
  // ...
}
for (local ent; ent = Entities.FindByName(ent, "entityname"); )
{
  // ...
}
Note.pngNote:
  • The variable name ent is arbitrary.
  • Indeed, we mean "=" and not "==" in the loop conditions! The loops end if ent becomes null, which happens when no matching entities have an entity index higher to the one in previous parameter.
  • In every iteration, "ent" is not null.
  • Semicolons are optional, except in the header of the for statement.

Methods

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

CEnvEntityMaker

Extends CBaseEntity ↑

Script handle class for env_entity_maker.

Methods

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

CLinkedPortalDoor

Extends CBaseAnimating ↑

Script handle class for linked_portal_door.

Methods

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

CPropLinkedPortalDoor

Extends CLinkedPortalDoor ↑

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

CLogicScript

Extends CBaseEntity ↑

Script handle class for logic_script.

Functions

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

Variables

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

CPlayerVoiceListener

Extends CAutoGameSystem

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

Methods

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

CPointTemplate

Extends CBaseEntity ↑

Script handle class for point_template.

Functions

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

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

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

Variables

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

Hooks

Function Signature Description
PreSpawnInstance table PreSpawnInstance(string entityClass, string entityName) If this is defined, it will be called right before the entity is created, and any KeyValues returned will be assigned to the entity.
Example
function PreSpawnInstance( entityClass, entityName )
{
	local keyvalues =
	{ 
   		rendercolor = "0 255 0"
   		targetname = "mySpawnedEntity"
	}
	return keyvalues
}
PostSpawn void PostSpawn(table entities) Called after the entities are spawned. A table with the handles of the spawned entities indexed by name is passed to the function. Could use this to connect outputs or do whatever needs to be done after the entity was created.
Example
function PostSpawn( entities )
{
	foreach( name, handle in entities )
	{
		printl( name + ": " + handle )
	}
}
Example

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

m_hSpawnedEntity <- null;
m_KeyValues <- null;

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

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

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

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

Spawn templated entities from any script.

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

printl( ent )

CPortal_Player

Extends CBasePlayer ↑

Script handle class for player entities of Portal.

Methods

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

CSceneEntity

Extends CBaseEntity ↑

Methods

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

CScriptKeyValues

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

Methods

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

CTriggerCamera

Extends CBaseEntity ↑

Script handle class for point_viewcontrol.

Methods

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

Hooks

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

CCallChainer

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

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

Methods

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

Members

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

CSimpleCallChainer

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

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

Methods

Function Signature Description
constructor CSimpleCallChainer(string functionPrefix, table scope = null, exactMatch = false) Creates a CSimpleCallChainer object that'll collect functions that have a matching prefix in the given scope, unless it seek for an exact name match. Also automatically exposes two bound global functions to dispatch to this object: DispatchPrecache() and DispatchOnPostSpawn().
PostScriptExecute void CSimpleCallChainer::PostScriptExecute() Begin searching for all non-native functions with matching prefixes, then push them into the chain array.
Call bool CSimpleCallChainer::Call(any ...) Call all functions inside the chain array with the given arguments.

Members

Instance Type Description
chain array All functions to be called by the Call() method.
exactMatch bool If set, names of non-native functions and prefix must be an exact match. Set by the constructor.
prefix string Prefix that functions should have to be added into the chain array. Set by the constructor.
scope table If set, seek functions in this scope instead. Set by the constructor.

LateBinder

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

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

Test1 <-
{   
   Foo=1
}   

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

lateBinder.End();
delete lateBinder;

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

Methods

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

Members

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

Vector

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

Methods

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

Metamethods

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

Members

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

Global functions

Printing and drawing

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

Singleplayer only

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

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

Multiplayer only

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

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

Developer only

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

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

Other

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

Squirrel Standard Library

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

General

Constants

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

Functions

Function Signature Description
assert assert(bool exp) Throws an exception if exp is evaluated to false.
collectgarbage int collectgarbage() Runs the garbage collector and returns the number of reference cycles found(and deleted) This function only works on garbage collector builds.
compilestring function compilestring(string string, string buffername = null) Compiles a string containing a squirrel script into a function and returns it.
enabledebuginfo void enabledebuginfo(any enable) Enable/disable the debug line information generation at compile time. Enables if enable != null, disables if enable == null.
getconsttable table getconsttable() Returns the const table of the VM.
getroottable table getroottable() Returns the root table of the VM.
getstackinfos table getstackinfos(int stacklevel) Returns the stack frame informations at the given stack level (0 is the current function 1 is the caller and so on). If the stack level doesn't exist the function returns null.
Example
{
	func="DoStuff",	//function name
	
	src="test.nut",	//source file
	
	line=10,		//line number
	
	locals = {		//a table containing the local variables
		
		a=10,
		
		testy="I'm a string"
	}
}
print void print(string message) Prints message to console without any line feed after.
setconsttable table setconsttable(table consttable) Sets the const table of the VM which also returns the previous const table.
seterrorhandler void seterrorhandler(function func) Sets the runtime error handler .
setroottable table setroottable(table roottable) Sets the root table of the VM which also returns the previous root table.
type string type(any obj) Return the 'raw' type of an object without invoking the metatmethod _typeof.

Math

The built-in Squirrel math library.

Constants

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

Functions

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

See also atan2.

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

Strings

The built-in Squirrel string library.

Functions

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

Regexp

The built-in Squirrel class for regular expressions.

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

Types

Integer

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

Float

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

Bool

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

String

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

Table

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

Array

Methods

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

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

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

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

Function

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

Class

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

Class instance

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

Generator

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

Thread

Methods

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

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

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

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

Weak reference

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

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

See also