Script Functions
This list contains engine-related Squirrel variables, functions, and constants available for Left 4 Dead 2 VScripts.
Some can be printed in-game with the script_help
command when the game is run in developer mode with the -dev
or -allowdebug
parameters. Others have been found from data mining, for example with script g_ModeScript.DeepPrintTable(getroottable())
, and from the Expanded Mutation System documentation.
For functions and parameters related to theDirectorOptions
table, see the L4D2 Director Scripts page.
Instances
Name | Type | Description |
---|---|---|
Convars |
Convars ↓
|
Provides an interface to read and change the values of console variables. |
Director |
CDirector ↓
|
Provides a limited interface to the Director. |
Entities |
CEntities ↓
|
Allows searching of currently-spawned entities. |
EntityOutputs |
CScriptEntityOutputs ↓
|
Allows reading and changing of entities' output data. |
NavMesh |
CNavMesh ↓
|
An interface to the Navigation Mesh. |
NetProps |
CNetPropManager ↓
|
Allows reading and updating the network properties of an entity. |
ResponseCriteria |
CScriptResponseCriteria ↓
|
Allows reading the response criteria of an entity. |
Script Scopes
Name | Type | Description |
---|---|---|
DirectorScript |
table | Script scope for Director scripts. Contains the active DirectorOptions table. |
g_ClearoutTable |
table (null )
|
NONE |
g_MapScript |
table | Script scope of map-specific vscripts, which also contains utilty functions. |
g_ModeScript |
table | Script scope of mode-specific vscripts like mutations. This scope also has the g_MapScript scope as its environment.
|
g_RoundState |
table | Scope of the start box used in the Holdout or Dash mutation. |
g_rr ↓ |
table | An interface to the Response System. |
Variables
Name | Type | Description |
---|---|---|
Documentation |
table | Contains the printed strings from the script_help command.
|
GameEventCallbacks |
table | Table of registered game event callbacks. |
print_indent |
integer | Spaces to indent prints by except ones from realPrint . Defaults to 0.
|
_PublishedHelp |
table | NONE |
ScriptEventCallbacks |
table | Table of registered script event callbacks. |
Script Debug
Name | Type | Value |
---|---|---|
ScriptDebugDefaultWatchColor |
array | [0, 192, 0] |
ScriptDebugDrawTextEnabled |
bool | true |
ScriptDebugDrawWatchesEnabled |
bool | true |
ScriptDebugInDebugDraw |
bool | false |
ScriptDebugText |
array | NONE |
ScriptDebugTextIndent |
integer | 0 |
ScriptDebugTextFilters |
table | NONE |
ScriptDebugTraces |
table | NONE |
ScriptDebugTraceAllOn |
bool | false |
ScriptDebugWatches |
array | NONE |
Constants
A constant is a variable whose value cannot be altered during program runtime, usually to avoid magic numbers by giving them self-documenting names.
Instance | Type | Value |
---|---|---|
_charsize_ |
integer | 1 |
_floatsize_ |
integer | 4 |
_intsize_ |
integer | 4 |
_version_ |
string | "Squirrel 3.0.4 stable" |
_versionnumber_ |
integer | 304 |
RAND_MAX |
integer | 32767 |
SPAWN_FLAGS |
table | SPAWN = 1
NOSPAWN = 2
TARGETSPAWN = 4
|
PI |
float | 3.14159 |
Classes
CBaseEntity
toc ↑ Extended by: CBaseAnimating ↓ CBaseTrigger ↓ CEnvEntityMaker ↓ CInfoItemPosition ↓ CPointTemplate ↓ CPointScriptTemplate ↓ CPointScriptUseTarget ↓
This is a script handle class for entities. All entities have a script handle using this class, sometimes as one of its subclasses.
An entity's own handle are accessed with:
Entities ↓
instance.- Entity Scripts only - The
self
keyword.
Methods
Function | Signature | Description |
---|---|---|
__KeyValueFromInt __KeyValueFromString __KeyValueFromVector
|
bool __KeyValueFromInt(string key, int value) bool __KeyValueFromString(string key, string value) bool __KeyValueFromVector(string key, Vector value)
|
Sets an entity keyvalue from a specific data type. Returns true if successfully set, false if it the key does not exist.
This simply changes the value without executing any other code that may be needed for the entity to fully process the keyvalue, such as code for updating the entity's internal network state. This can create unexpected side effects on already-spawned entities such as visual changes being delayed for clients. Tip:Use Netprops ↓ and update the keyvalue's corresponding prop instead, as this correctly updates the networking state and results in an immediate update.
Warning:__KeyValueFromFloat doesn't exist
|
ApplyAbsVelocityImpulse |
void ApplyAbsVelocityImpulse(Vector impulse)
|
Apply a Velocity Impulse as a world space impulse vector. |
ApplyLocalAngularVelocityImpulse |
void ApplyLocalAngularVelocityImpulse(Vector impulse)
|
Apply an Angular Velocity Impulse in entity local space. The direction of the input vector is the rotation axis, and the length is the magnitude of the impulse. |
ConnectOutput |
void ConnectOutput(string output, string function)
|
Adds an I/O connection that will call the named function when the specified output fires. |
DisconnectOutput |
void DisconnectOutput(string output, string function)
|
Removes a connected script function from an I/O event. |
FirstMoveChild |
handle FirstMoveChild()
|
Returns the first entity parented to this one. Needs to be used in combination with NextMovePeer to iterate over all children.
Tip:Example usage:
for (local child = entity.FirstMoveChild(); child != null; child = child.NextMovePeer())
|
GetAngles |
QAngle GetAngles()
|
Returns the orientation of the entity in the world. |
GetBaseVelocity |
Vector GetBaseVelocity()
|
Returns any constant velocity currently being imparted onto the entity. This includes being pushed by effects like trigger_push and players standing on moving geometry like elevators. Should always returns a zero vector if the entity is not affected by any movement effects. |
GetCenter |
Vector GetCenter()
|
Get world space center of object - absolute coords. |
GetClassname |
string GetClassname()
|
Returns the entity class. This includesplayer andinfected .
|
GetContext |
variable GetContext(string name)
|
Looks up a response context and returns it if available. May return string, float, or null (if the context isn't found). Bug*:Always returns null for contexts with numeric value Bug*:Can return value for expired contexts |
GetEntityHandle |
unknown GetEntityHandle()
|
Get a C++ EHANDLE reference of the entity. This is an opaque type not directly usable by Squirrel, not a normal script handle. Only necessary for CPointScriptUseTarget functions. ↓ |
GetEntityIndex |
int GetEntityIndex()
|
Returns the entity index. This is the same type of index used in most game events. |
GetForwardVector |
Vector GetForwardVector()
|
Get the forward vector of the entity. |
GetHealth |
int GetHealth()
|
Returns the current health of the entity (does not include survivor temporary health). |
GetLocalAngles |
QAngle GetLocalAngles()
|
Returns the orientation of the entity relative to it's parent or attachment point. |
GetLocalAngularVelocity |
QAngle GetLocalAngularVelocity()
|
Maybe local angvel |
GetLocalOrigin |
Vector GetLocalOrigin()
|
Returns the origin of the entity relative to it's parent or attachment point. |
GetLocalVelocity |
Vector GetLocalVelocity()
|
Get Entity relative velocity |
GetMaxHealth |
int GetMaxHealth()
|
Returns the maximum health of the entity. |
GetModelName |
string GetModelName()
|
Returns the file name of the model used by the entity (if applicable). |
GetMoveParent |
handle GetMoveParent()
|
If in hierarchy, retrieves the entity's parent |
GetName |
string GetName()
|
Returns the targetname of the entity. |
GetOrigin |
Vector GetOrigin()
|
Returns the origin of the entity in the world. |
GetOwnerEntity |
handle GetOwnerEntity()
|
Get the owner entity, if there is one. |
GetPreTemplateName |
string GetPreTemplateName()
|
Get the entity name stripped of template unique decoration. |
GetRootMoveParent |
handle GetRootMoveParent()
|
If in hierarchy, walks up the hierarchy to find the root parent. |
GetScriptId |
string GetScriptId()
|
Returns the name of the entity's think function. Tip:Retrieve the actual script identifier with
NetProps.GetPropString(ent, "m_iszScriptId") |
GetScriptScope |
table GetScriptScope()
|
Retrieve the table storing the Entity Script associated with this entity, null otherwise. |
GetVelocity |
Vector GetVelocity()
|
Returns a local velocity Vector. |
IsPlayer |
bool IsPlayer()
|
Does this entity belong to the player class. |
IsValid |
bool IsValid()
|
Whether the handle still belongs to an entity that's still valid, could become invalid in cases such as the entity, like a destroyed func_breakable.(?) |
Kill |
void Kill()
|
Removes the entity. |
NextMovePeer |
handle NextMovePeer()
|
Returns the next child of this entity's parent. Used to continue iteration from FirstMoveChild(). |
OverrideFriction |
void OverrideFriction(float duration, float friction)
|
Takes duration, value for a temporary override |
PrecacheModel |
int PrecacheModel(string filename)
|
Precache a model after the map has loaded and return index of the model. |
PrecacheScriptSound |
void PrecacheScriptSound(string soundscript)
|
Precache a sound file, used by the specified soundscript. |
SetAngles |
void SetAngles(QAngle direction)
|
Sets the orientation of the entity. |
SetContext |
void SetContext(string name, string value, float duration)
|
Stores any key/value pair in this entity's dialog contexts. Value must be a string. Will last for duration (set -1 to mean 'forever'). |
SetContextNum |
void SetContextNum(string name, float value, float duration)
|
Stores any key/value pair in this entity's dialog contexts. Value must be a number (int or float). Will last for duration (set -1 to mean 'forever'). |
SetForwardVector |
void SetForwardVector(Vector direction)
|
Set the orientation of the entity to have this forward vector. |
SetFriction |
void SetFriction(float friction)
|
Set PLAYER friction, ignored for objects. |
SetGravity |
void SetGravity(float gravity)
|
Set PLAYER gravity, ignored for objects. |
SetHealth |
void SetHealth(int health)
|
Changes the health value of the entity. Does not check whether to kill players. |
SetLocalAngles |
void SetLocalAngles(QAngle direction)
|
Sets the entity orientation relative to it's parent or attachment point. |
SetLocalOrigin |
void SetLocalOrigin(Vector position)
|
Sets the entity position relative to it's parent or attachment point. |
SetMaxHealth |
void SetMaxHealth(int health)
|
Changes the maximum health value of the entity. |
SetModel |
void SetModel(string modelName)
|
Changes the model of the entity (if applicable). |
SetOrigin |
void SetOrigin(Vector position)
|
Sets the world entity position. |
SetVelocity |
void SetVelocity(Vector velocity)
|
Sets the entity velocity. |
TakeDamage |
void TakeDamage(float damage, int damageType, CBaseEntity attacker)
|
Damages the entity. |
TakeDamageEx |
void TakeDamageEx(CBaseEntity inflictor, CBaseEntity attacker, CBaseEntity weapon, Vector vecDamageForce, Vector vecDamagePosition, float damage, int damageType)
|
Damages the entity (extended). |
ValidateScriptScope |
bool ValidateScriptScope()
|
Ensures an entity has a script scope, if it doesn't have one then one is created. Returns true if created successfully. |
Hooks
If one of these functions are declared in an Entity Script, the entity will run this function automatically in the appropriate situation.
Function | Signature | Description |
---|---|---|
Input[InputName] |
bool Input[InputName]()
|
Called when the entity receives an I/O input that matches the function's name. The name that follows after Input must match the casing, i.e. InputFireUser1 will catch any "FireUser1" inputs but not "fireuser1" inputs from the ent_fire command.
Variables |
OnEntText |
string OnEntText()
|
If ent_text is used on an entity and this function exists, it will be called every tick. Returns a string that gets displayed as part of the ent_text overlay. This is a handy feature for displaying script data on objects when you ent_text the object, or running arbitrary code (such as turning on additional debugging visualizations) is using ent_text. NOTE: ent_text_allow_script 1 must be set in order for this feature to be active. |
OnPostSpawn |
void OnPostSpawn()
|
Called after the entity spawns, which is after scripts and players have loaded. This could be used to have an entity register itself with a master script, or adjusting the entity parameters in a programmatic way. |
Precache |
void Precache()
|
Called after the script executes. Can be used to call precache functions for models and sounds on map load. |
CBaseAnimating
toc ↑ Extends CBaseEntity ↑ Extended by: CBaseFlex ↓ CTerrorWeapon ↓
Script handle class for animating entities such as props.
Methods
Function | Signature | Description |
---|---|---|
FindBodygroupByName |
int FindBodygroupByName(string name)
|
Find a bodygroup ID by name. Returns -1 if the bodygroup does not exist. |
GetAttachmentAngles |
QAngle GetAttachmentAngles(int ID)
|
Get the attachment ID's angles as a QAngle. |
GetAttachmentBone |
int GetAttachmentBone(int ID)
|
Get the attachment ID's parent bone index. |
GetAttachmentOrigin |
Vector GetAttachmentOrigin(int ID)
|
Get the attachment ID's origin as a Vector. |
GetBodygroup |
int GetBodygroup(int ID)
|
Get the bodygroup value by bodygroup ID. |
GetBodygroupName |
string GetBodygroupName(int ID)
|
Get the bodygroup ID's name. |
GetBodygroupPartName |
string GetBodygroupPartName(int group, int part)
|
Get name by group and part. |
GetBoneAngles |
QAngle GetBoneAngles(int ID)
|
Get the bone ID's angles as a QAngle. |
GetBoneOrigin |
Vector GetBoneOrigin(int ID)
|
Get the bone ID's origin Vector. |
GetModelScale |
float GetModelScale()
|
Get the model scale. |
GetSequence |
int GetSequence()
|
Get the currently playing sequence ID. |
GetSequenceActivityName |
string GetSequenceActivityName(int ID)
|
Get the activity name for a sequence by sequence ID. |
GetSequenceDuration |
float GetSequenceDuration(int ID)
|
Get a sequence duration in seconds by sequence ID. |
GetSequenceName |
string GetSequenceName(int ID)
|
Get a sequence name by sequence ID. |
IsSequenceFinished |
bool IsSequenceFinished()
|
Returns true if the current sequence has finished playing. |
LookupActivity |
int LookupActivity(string activity)
|
Get the named activity index. Returns -1 if the activity does not exist. |
LookupAttachment |
int LookupAttachment(string name)
|
Get the named attachment index. Returns 0 if the attachment does not exist. |
LookupBone |
int LookupBone(string bone)
|
Get the named bone index. Returns -1 if the bone does not exist. |
LookupSequence |
int LookupSequence(string name)
|
Looks up a sequence by sequence name or activity name. Returns -1 if the sequence does not exist. |
ResetSequence |
void ResetSequence(int ID)
|
Reset a sequence by sequence ID. If the ID is different than the current sequence, switch to the new sequence. |
SetBodygroup |
void SetBodygroup(int ID, int value)
|
Set the bodygroup by ID. |
SetModelScale |
void SetModelScale(float scale, float change_duration)
|
Changes a model's scale over time. Set the change duration to 0.0 to change the scale instantly. |
SetPoseParameter |
float SetPoseParameter(int ID, float value)
|
Sets a pose parameter value. Returns the effective value after clamping or looping. |
SetSequence |
void SetSequence(int ID)
|
Plays a sequence by sequence ID. |
CBaseFlex
toc ↑ Extends CBaseAnimating ↑
Animated characters who have vertex flex capability (e.g., facial expressions).
Methods
Function | Signature | Description |
---|---|---|
GetCurrentScene |
handle GetCurrentScene()
|
Returns the instance of the oldest active scene entity (if any). |
GetSceneByIndex |
handle GetSceneByIndex(int index)
|
Returns the instance of the scene entity at the specified index. |
PlayScene |
float PlayScene(string sceneFile, float delay)
|
Play the specified .vcd file, causing the related characters to speak and subtitles to play. |
CBaseCombatCharacter
toc ↑ Extends CBaseFlex ↑
Combat character. Common and uncommon infected and witches belong to this.
Methods
Function | Signature | Description |
---|---|---|
GetLastKnownArea |
TerrorNavArea GetLastKnownArea()
|
Return the last nav area occupied - NULL if unknown. |
CTerrorPlayer
toc ↑ Extends CBaseCombatCharacter ↑
Script handle class for player entities. Both survivors and special infected belong to this.
Methods
Function | Signature | Description |
---|---|---|
DropItem |
void DropItem(string classname)
|
Make the player drop an item/weapon from their inventory, by classname. |
Extinguish |
void Extinguish()
|
Extinguish a burning player. |
EyeAngles |
QAngle EyeAngles()
|
Returns the direction the player is looking. |
EyePosition |
Vector EyePosition()
|
Returns the players eye position in the world. |
GetActiveWeapon |
handle GetActiveWeapon()
|
Get the player's active weapon entity. |
GetAliveDuration |
float GetAliveDuration()
|
Returns the time the character has been alive (only valid when alive). |
GetButtonMask |
int GetButtonMask()
|
Returns a bitfield of currently pressed buttons. Test against each value to see which button is pressed. Recognized buttons are: 1 - IN_ATTACK 2 - IN_JUMP 4 - IN_DUCK 8 - IN_FORWARD 16 - IN_BACK 32 - IN_USE 2048 - IN_ATTACK2 8192 - IN_RELOAD
|
GetHealthBuffer |
float GetHealthBuffer()
|
Returns the current temporary health of a survivor. |
GetNetworkIDString |
string GetNetworkIDString()
|
Get the player's network (i.e. Steam) ID. |
GetPlayerName |
string GetPlayerName()
|
Get the players name. |
GetPlayerUserId |
int GetPlayerUserId()
|
Get the players userID. |
GetSenseFlags |
int GetSenseFlags()
|
Get the current bot sense flags. Test against each value to see which flag is set. Values: 1 - BOT_CANT_SEE 2 - BOT_CANT_HEAR 4 - BOT_CANT_FEEL
|
GetSpecialInfectedDominatingMe |
CTerrorPlayer GetSpecialInfectedDominatingMe()
|
Get the Special Infected dominating this Survivor. |
GetSurvivorSlot |
int GetSurvivorSlot()
|
Get the player's slot number. |
GetZombieType |
int GetZombieType()
|
If an infected, find out what type. Recognized ZombieTypes are: Smoker = 1, Boomer = 2, Hunter = 3, Spitter = 4, Jockey = 5, Charger = 6, Witch = 7, Tank = 8, Survivor = 9 |
GiveAmmo |
void GiveAmmo(int amount)
|
Adds ammo for the player's primary weapon ammo pool. |
GiveItem |
void GiveItem(string itemname)
|
Give an item/weapon by name. Uses the same names as the give console command(health, katana, rifle_ak47 , etc.). Bug*:Cannot give item to a player that is currently running a chainsaw (same applies to GiveItemWithSkin) |
GiveItemWithSkin |
void GiveItemWithSkin(string classname, int skin)
|
Gives the player a skinned weapon. |
GiveUpgrade |
void GiveUpgrade(int upgradeType)
|
Give a primary weapon upgrade. Possible values: 0 - UPGRADE_INCENDIARY_AMMO 1 - UPGRADE_EXPLOSIVE_AMMO 2 - UPGRADE_LASER_SIGHT
|
HasEverBeenInjured |
bool HasEverBeenInjured(int team)
|
Returns true if the character has ever been injured by a member of the given team. |
HitWithVomit |
void HitWithVomit()
|
Cover the player with a boomer vomit attack. |
IsAdrenalineActive |
bool IsAdrenalineActive()
|
Return true if adrenaline is active. |
IsDead |
bool IsDead()
|
Returns true when a player is dead for more than 5 seconds. Note that taking over a dying bot immediately switches to the dead phase. |
IsDominatedBySpecialInfected |
bool IsDominatedBySpecialInfected()
|
Return true if being dominated by a Special Infected (i.e. held by smoker, charger, jockey or hunter) |
IsDying |
bool IsDying()
|
Returns true when a player has recently died for 5 seconds. Note that taking over a dying bot skips the dying phase. |
IsFiringWeapon |
bool IsFiringWeapon()
|
Return true if player is firing a weapon. |
IsIncapacitated |
bool IsIncapacitated()
|
Returns true if in incapacitated state. |
IsHangingFromLedge |
bool IsHangingFromLedge()
|
Returns true if in ledge hang state. |
IsGettingUp |
bool IsGettingUp()
|
Return true if player is currently getting up. |
IsGhost |
bool IsGhost()
|
Returns true if in ghost infected state. |
IsImmobilized |
bool IsImmobilized()
|
Return true if currently immobilized. Tip:Is true when in getting up animation, punched by tank, flung by charger, caught by charger, smoker or hunter, hanging, incapacitated, dead, being healed, using kit, defibrillator or unpacking an upgrade pack, using timed button, pouring gas can, handing in cola or using minigun (not true when staggering or caught by jockey)
|
IsInCombat |
bool IsInCombat()
|
Return true if currently in combat. |
IsIT |
bool IsIT()
|
Return true if currently IT from bile. |
IsOnFire |
bool IsOnFire()
|
Returns true if a player is on fire, e.g. Standing in fireworks crate explosions. |
IsOnThirdStrike |
bool IsOnThirdStrike()
|
Return true if on third-strike. |
IsStaggering |
bool IsStaggering()
|
Return true if player is staggering. |
IsSuppressingFallingDamage |
bool IsSuppressingFallingDamage()
|
Returns true if falling damage is currently suppressed, which is if the entity received the IgnoreFallDamage or IgnoreFallDamageWithoutReset input, provided that it is still active.
|
IsSurvivor |
bool IsSurvivor()
|
Returns true if entity is on the survivor or l4d1 survivor team (Otherwise, unknown, spectator or infected). |
RemoveUpgrade |
void RemoveUpgrade(int upgradeType)
|
Remove a primary weapon upgrade. Possible values: 0 - UPGRADE_INCENDIARY_AMMO 1 - UPGRADE_EXPLOSIVE_AMMO 2 - UPGRADE_LASER_SIGHT
|
ReviveByDefib |
void ReviveByDefib()
|
Revive a dead player by defib. |
ReviveFromIncap |
void ReviveFromIncap()
|
Revive an incapacitated player. |
SetFriction |
void SetFriction(int friction)
|
Set player friction. |
SetGravity |
void SetGravity(int gravity)
|
Set player gravity. |
SetHealthBuffer |
void SetHealthBuffer(float health)
|
Sets the temporary health of a survivor; No effect for infecteds. Does not incapacitate or kill when set to zero. |
SetReviveCount |
void SetReviveCount(int count)
|
Sets the number of times a survivor has been revived, and updates third-strike state (B&W) and heartbeat sound.
Bug*:Doesn't update the m_isGoingToDie netprop, which controls the dying quotes. |
SetSenseFlags |
void SetSenseFlags(int flags)
|
Set the set of bot sense flags. Combine values to set appropriate flags: 1 - BOT_CANT_SEE 2 - BOT_CANT_HEAR 4 - BOT_CANT_FEEL
|
SnapEyeAngles |
void SnapEyeAngles(QAngle angles)
|
Sets the view angles. Supports rolling the view. |
Stagger |
void Stagger(Vector position)
|
Stagger a player away from a position. Use Vector(0,0,0) to just stagger forward. |
SwitchToItem |
bool SwitchToItem(string classname)
|
Make the player switch to an item/weapon by classname. Returns true if the switch was performed. |
TryGetPathableLocationWithin |
Vector TryGetPathableLocationWithin(float radius)
|
Get a location on the nav the player can path to within the desired radius. |
UseAdrenaline |
void UseAdrenaline(float duration)
|
Causes Adrenaline's speed and visual effect, no change to health. |
CTerrorWeapon
toc ↑ Extends CBaseAnimating ↑.
All weapon entities that are part of a player's inventory, holstered or not, belongs to this. All Clip2
related functions have no gameplay effects (unless weapon scripts are modded), but can be used for your own custom weapon ammunition needs. E.g. A Hunting Rifle with 3 Oxygen Tank throwables.
Clip1
related functions!GetDefaultClip1
is always treated as a single pistol, but GetMaxClip1
will account for dual pistols as well! Methods
Function | Signature | Description |
---|---|---|
Clip1 |
int Clip1()
|
Current amount of ammo in a weapon's clip. |
Clip2 |
int Clip2()
|
Current 'secondary clip' ammo count. Always -1 in default game. |
GetDefaultClip1 |
int GetDefaultClip1()
|
Clip count of a weapon when its newly picked up. |
GetDefaultClip2 |
int GetDefaultClip2()
|
Default 'secondary clip' ammo count. Always -1 in default game; Only a positive value if a custom weapon script has clip2_size set.
|
GetMaxClip1 |
int GetMaxClip1()
|
Max clip count a weapon can hold. Will always return the same value as the GetDefaultClip1 function.
|
GetMaxClip2 |
int GetMaxClip2()
|
Max 'secondary clip' count. Always -1 in default game; Only a positive value if a custom weapon script has clip2_size set. Will always return the same value as the GetDefaultClip2 function.
|
GiveDefaultAmmo |
void GiveDefaultAmmo()
|
Revert both weapons's clip to their default values. |
Reload |
bool Reload()
|
Forces the weapon to reload if it is not full. Returns true if it could start a weapon reload. |
SetClip1 |
void SetClip1(int amount)
|
Sets a weapon's clip count. |
SetClip2 |
void SetClip2(int amount)
|
Sets a weapon's 'secondary clip' count; Works just fine but has no gameplay effect in default game. |
CBaseTrigger
toc ↑ Extends CBaseEntity ↑
Entity class for all entities inheriting CBaseTrigger
Methods
Function | Signature | Description |
---|---|---|
Disable |
void Disable()
|
Disable the trigger. Identical to the Disable input.
|
Enable |
void Enable()
|
Enable the trigger. Identical to the Enable input.
|
IsTouching |
bool IsTouching(handle entity)
|
Checks whether the passed entity is touching the trigger. |
AI_Response
toc ↑ Opaque type representing a return value from the old response system.
Methods
Function | Signature | Description |
---|---|---|
GetMatchScore |
Relative score of this match's quality (based on number of criteria matched)). |
CDirector
toc ↑
Instances ↑ Game Instance: Director
Provides methods for reading information and forcing events in the AI Director. To influence the Director behavior, the DirectorOptions
table is used instead.
Methods
Function | Signature | Description | |
---|---|---|---|
AreAllSurvivorsInBattlefield |
bool AreAllSurvivorsInBattlefield()
|
Returns true if all Survivors are in the battlefield. | |
AreAllSurvivorsInFinaleArea |
bool AreAllSurvivorsInFinaleArea()
|
True when all survivors are within the finale area. | |
AreTeamsFlipped |
bool AreTeamsFlipped()
|
True when teams are flipped in Versus modes. | |
ClearCachedBotQueries |
void ClearCachedBotQueries()
|
Mark all cached bot query results as invalid. | |
ForceNextStage |
void ForceNextStage()
|
Push the ScriptedMode to next stage - i.e. request GNSS be called. | |
GetAveragedSurvivorSpan |
float GetAveragedSurvivorSpan()
|
Get the distance between the lead and trailing survivors, smoothed over time. | |
GetAveragedSurvivorSpeed |
float GetAveragedSurvivorSpeed()
|
Get the rate at which the lead survivor is moving along the flow, smoothed over time. | |
GetClosestActivePipeBomb |
CBaseEntity GetClosestActivePipeBomb(Vector origin)
|
Returns the closest active pipe bomb from this origin. | |
GetClosestCharacterWhoIsIT |
CBaseCombatCharacter GetClosestCharacterWhoIsIT(CBaseCombatCharacter character)
|
Returns the closest character who is IT to the passed character. | |
GetClosestSurvivor |
CTerrorPlayer GetClosestSurvivor(Vector origin, bool bIncludeIncap, bool bIncludeOnRescueVehicle)
|
Returns the closest Survivor from the passed origin, if incapped Survivors are included in search, or on rescue vehicle. | |
GetCommonInfectedCount |
int GetCommonInfectedCount()
|
Returns number for infected currently spawned. | |
GetFurthestSurvivorFlow |
float GetFurthestSurvivorFlow()
|
Get the maximum distance along the flow that the survivors have reached. | |
GetGameMode |
string GetGameMode()
|
Get the current game mode. If called in a mutation, it returns the current mutation, not the base mode. Will only look for the specific game mode/mutation. | |
GetGameModeBase |
string GetGameModeBase()
|
Get the current base game mode. Does not return the current mutation. Example, if looking for survival, it will also count for all game modes using survival as base. Such as Mutation 15 (Survival Versus) | |
GetHighestFlowSurvivor |
CTerrorPlayer GetHighestFlowSurvivor()
|
Returns the Survivor with the highest flow. | |
GetHoldoutCooldownEndTime |
float GetHoldoutCooldownEndTime()
|
Get the end time of the cooldown timer. | |
GetLowestFlowSurvivor |
CTerrorPlayer GetLowestFlowSurvivor()
|
Returns the Survivor with the lowest flow. | |
GetMapName |
string GetMapName()
|
Get the current map name. | |
GetMapNumber |
int GetMapNumber()
|
Return the current map number. | |
GetMissionWipes |
int GetMissionWipes()
|
Returns the current number of mission wipes. | |
GetPendingMobCount |
int GetPendingMobCount()
|
Returns the number of infected waiting to spawn. | |
GetRandomSurvivor |
CTerrorPlayer GetRandomSurvivor()
|
Returns a random alive Survivor. | |
GetSurvivorSet |
int GetSurvivorSet()
|
Get the current survivor set. L4D1 Survivors = 1, L4D2 Survivors = 2. Bug*:Calling this inside mapspawn_addon or response_testbed_addon will give survivor set value of previous loaded map | |
GetTimeSinceSpecialZombieKilled |
float GetTimeSinceSpecialZombieKilled(int zombieType)
|
Returns the time since the passed zombie type was killed. | |
GetTotalElapsedMissionTime |
float GetTotalElapsedMissionTime()
|
Returns the total elapsed mission time. | |
HasAnySurvivorLeftSafeArea |
bool HasAnySurvivorLeftSafeArea()
|
True when one or more survivors have left the starting safe area. | |
IsAnySurvivorBypassingTank |
bool IsAnySurvivorBypassingTank()
|
True when one or more survivors are bypassing the Tank. | |
IsAnySurvivorInCombat |
bool IsAnySurvivorInCombat()
|
Returns true if any survivor recently dealt or took damage. | |
IsAnySurvivorInExitCheckpoint |
bool IsAnySurvivorInExitCheckpoint()
|
True when one or more survivors are in the exit checkpoint. | |
IsAnySurvivorInStartArea |
bool IsAnySurvivorInStartArea()
|
True when one or more survivors are in the starting safe area. | |
IsFinale |
bool IsFinale()
|
True when the finale has started. | |
IsFinaleEscapeInProgress |
bool IsFinaleEscapeInProgress()
|
True when the finale escape is in progress. | |
IsFinaleVehicleReady |
bool IsFinaleVehicleReady()
|
True when the finale vehicle is ready. | |
IsFinaleWon |
bool IsFinaleWon()
|
Returns true if the finale has been won. | |
IsFirstMapInScenario |
bool IsFirstMapInScenario()
|
True if the first map in a scenario. | |
IsL4D1Campaign |
bool IsL4D1Campaign()
|
Return true if the current campaign is originally from L4D1. | |
IsLocationFoggedToSurvivors |
bool IsLocationFoggedToSurvivors(Vector origin)
|
Returns true if the passed location is fogged to Survivors. | |
IsPlayingIntro |
bool IsPlayingIntro()
|
True if the intro is currently playing. | |
IsPlayingOnConsole |
bool IsPlayingOnConsole()
|
Return true if game is running on a console (such as Xbox 360). | |
IsSessionStartMap |
bool IsSessionStartMap()
|
True if the map is the start of the session. | |
IsSinglePlayerGame |
bool IsSinglePlayerGame()
|
Return true if game is in single player. | |
IsValid |
bool IsValid()
|
WhetherDirector belongs to a valid entity. Seems futile to use.
| |
IsTankInPlay |
bool IsTankInPlay()
|
Returns true if any tanks are aggro on survivors. | |
L4D1SurvivorGiveItem |
void L4D1SurvivorGiveItem()
|
Let the L4D1 survivors know that now is a good time to give the players an item. | |
PlayMegaMobWarningSounds |
void PlayMegaMobWarningSounds()
|
Plays a horde scream sound and asks survivors to speak incoming horde lines. | |
RegisterForbiddenTarget |
void RegisterForbiddenTarget(CBaseEntity entity)
|
Registers a target entity as forbidden. | |
ResetMobTimer |
void ResetMobTimer()
|
Trigger a mob as soon as possible when in BUILD_UP .
| |
ResetSpecialTimers |
void ResetSpecialTimers()
|
Reset all special timers (by type and by slot) so that hopefully mobs will spawn asap. | |
SetHoldoutCooldownEndTime |
void SetHoldoutCooldownEndTime(float time)
|
||
UnregisterForbiddenTarget |
void UnregisterForbiddenTarget(CBaseEntity entity)
|
Unregisters a target entity as forbidden. | |
UserDefinedEvent1 UserDefinedEvent2 UserDefinedEvent3 UserDefinedEvent4 |
void UserDefinedEvent1() void UserDefinedEvent2() void UserDefinedEvent3() void UserDefinedEvent4()
|
When called, these trigger the appropriate output of the info_director entity.
|
|
WarpAllSurvivorsToBattlefield |
void WarpAllSurvivorsToBattlefield()
|
Warp all Survivors to the battlefield. | |
WarpAllSurvivorsToCheckpoint |
void WarpAllSurvivorsToCheckpoint()
|
Warp all Survivors to the exit checkpoint. | |
WarpAllSurvivorsToFinale |
void WarpAllSurvivorsToFinale()
|
Warp all Survivors to the finale radio. |
CEntities
toc ↑
Instances ↑ Game Instance: Entities
An interface to find and iterate over the script handles for the entities in play. To iterate over a set of entities, pass null to the previous parameter in the appropriate method to start an iteration. A reference to a previously-found entity can be used instead to continue a search.
The following are two equivalent examples and iterate over all weapons on the map:
local ent = null;
while ( ent = Entities.FindByClassname(ent, "weapon_*") )
{
// ...
}
|
for (local ent; ent = Entities.FindByClassname(ent, "weapon_*"); )
{
// ...
}
|
- The variable name
ent
is arbitrary. - Indeed, we mean "=" and not "==" in the loop conditions! The loops end if
ent
becomesnull
, which happens when no matching entities have an entity index higher to the one in previous parameter. - Semicolons are optional, except in the header of the
for
statement. - The string parameters of the
FindBy...
functions support the wildcard star*
. In the above example,FindByClassname
only returns either a handle of an entity whose classname begins with "weapon_
" or it returnsnull
.
Methods
Function | Signature | Description |
---|---|---|
FindByClassname |
handle FindByClassname(handle previous, string class)
|
Find entities by class name. |
FindByClassnameNearest |
handle FindByClassnameNearest(string class, Vector origin, float radius)
|
Find the entity with the given class name nearest to the specified point. |
FindByClassnameWithin |
handle FindByClassnameWithin(handle previous, string class, Vector origin, float radius)
|
Find entities by class name within a radius, while within a set radius. |
FindByModel |
handle FindByModel(handle previous, string filename)
|
Find entities by a model path name. |
FindByName |
handle FindByName(handle previous, string name)
|
Find entities by targetname. Special ones including !bill will work.
|
FindByNameNearest |
handle FindByNameNearest(string name, Vector origin, float radius)
|
Find entities by targetname nearest to a point, while within a set radius. Special ones including !bill will work.
|
FindByNameWithin |
handle FindByNameWithin(handle previous, string name, Vector origin, float radius)
|
Find entities by targetname within a radius. Special ones including !bill will work.
|
FindByTarget |
handle FindByTarget(handle previous, string targetname)
|
Find entities by its target. |
FindInSphere |
handle FindInSphere(handle previous, Vector origin, float radius)
|
Returns entities within a set radius. |
First |
handle First()
|
The first entity that spawned (Always worldspawn ). Can be used to begin an iteration for a list of entities.
|
Next |
handle Next(handle previous)
|
At the given reference of a previously-found entity, returns the next one after it in the list. |
IsValid |
bool IsValid()
|
Whether the handle for Entities is a valid handle.
|
CEnvEntityMaker
toc ↑ Extends CBaseEntity ↑
Script handle class for env_entity_maker.
Methods
Function | Signature | Description |
---|---|---|
SpawnEntity |
void SpawnEntity()
|
Create an entity at the location of the maker. |
SpawnEntityAtEntityOrigin |
void SpawnEntityAtEntityOrigin(CBaseEntity entity)
|
Create an entity at the location of a specified entity instance. |
SpawnEntityAtLocation |
void SpawnEntityAtLocation(Vector origin, QAngle orientation)
|
Create an entity at a specified location and orientation. |
SpawnEntityAtNamedEntityOrigin |
void SpawnEntityAtNamedEntityOrigin(string name)
|
Create an entity at the location of a named entity. |
CInfoItemPosition
toc ↑ Extends CBaseEntity ↑
Script handle class for info_item_position.
Methods
Function | Signature | Description |
---|---|---|
GetGroup |
Get the group number for this item position | |
GetRarity |
Get the rarity for this item position. | |
GetReplaceParm |
Get a replacement parameter by index. | |
SetGroup |
Set the group number for this item position. | |
SetRarity |
Set the rarity for this item position. |
toc ↑
Instances ↑ Game Instance: NavMesh
An interface to the Navigation Mesh.
Methods
Function | Signature | Description |
---|---|---|
FindLadderAlongRay |
CNavLadder FindLadderAlongRay(Vector startpos, Vector endpos, TerrorNavArea ignoreArea)
|
Get nav ladder from ray. |
FindNavAreaAlongRay |
TerrorNavArea FindNavAreaAlongRay(Vector startpos, Vector endpos, TerrorNavArea ignoreArea)
|
Get nav area from ray. |
GetAllAreas |
void GetAllAreas(table)
|
Fills a passed in table of all nav areas. |
GetAllLadders |
void GetAllLadders(table)
|
Fills a passed in table of all nav ladders. |
GetAreasWithAttributes |
void GetAreasWithAttributes(int bits, table)
|
Fills a passed in table of all nav areas that have the specified attributes. |
GetLadderByID |
CNavLadder GetLadderByID(int id)
|
Get nav ladder by ID. |
GetLadderCount |
int GetLadderCount()
|
Return total number of nav ladders. |
GetNavArea |
TerrorNavArea GetNavArea(Vector origin, float flBeneath)
|
Given a position in the world, return the nav area that is closest and at the same height, or beneath it. |
GetNavAreaByID |
TerrorNavArea GetNavAreaByID(int id)
|
Get nav area by ID. |
GetNavAreaCount |
int GetNavAreaCount()
|
Return total number of nav areas. |
GetNavAreasFromBuildPath |
bool GetNavAreasFromBuildPath(TerrorNavArea startArea, TerrorNavArea endArea, Vector goalPos, float flMaxPathLength, int teamID, bool ignoreNavBlockers, table)
|
Fills table with areas from a path. Returns whether a path was found. If 'endArea' is NULL, will compute a path as close as possible to 'goalPos'. |
GetNavAreasInRadius |
void GetNavAreasInRadius(Vector origin, float radius, table)
|
Fills a passed in table of nav areas within radius. |
GetNavAreasOverlappingEntityExtent |
void GetNavAreasOverlappingEntityExtent(CBaseEntity entity, table)
|
Fills passed in table with areas overlapping entity's extent. |
GetNearestNavArea |
TerrorNavArea GetNearestNavArea(Vector origin, float maxDist, bool checkLOS, bool checkGround)
|
Given a position in the world, return the nav area that is closest and at the same height, or beneath it. |
GetObstructingEntities |
void GetObstructingEntities(table)
|
Fills a passed in table of all obstructing entities. |
IsValid |
bool IsValid()
|
Whether the handle belongs to a valid entity. Redundant as navigation meshes are not entity related. |
NavAreaBuildPath |
bool NavAreaBuildPath(TerrorNavArea startArea, TerrorNavArea endArea, Vector goalPos, float flMaxPathLength, int teamID, bool ignoreNavBlockers)
|
Returns true if a path exists. If 'endArea' is NULL, will compute a path as close as possible to 'goalPos'. |
NavAreaTravelDistance |
float NavAreaTravelDistance(TerrorNavArea startArea, TerrorNavArea endArea, float flMaxPathLength)
|
Compute distance between two areas. Return -1 if can't reach 'endArea' from 'startArea'. |
RegisterAvoidanceObstacle |
void RegisterAvoidanceObstacle(CBaseEntity entity)
|
Registers an entity as an avoidance obstacle. |
UnblockRescueVehicleNav |
void UnblockRescueVehicleNav()
|
Unblock the rescue vehicle nav areas so bots can path through them. |
UnregisterAvoidanceObstacle |
void UnregisterAvoidanceObstacle(CBaseEntity entity)
|
Unregisters an entity as an avoidance obstacle. |
toc ↑ This is a script handle class for nav areas. Nav areas may also have attributes applied on them.
Methods
Function | Signature | Description |
---|---|---|
AddIncomingConnection |
void AddIncomingConnection(TerrorNavArea area, int dir)
|
Add areas that connect TO this area by a ONE-WAY link. |
ComputeDirection |
int ComputeDirection(Vector point)
|
Return direction from this area to the given point. |
ConnectTo |
void ConnectTo(TerrorNavArea area, int dir)
|
Connect this area to given area in given direction. If you set direction to -1, it will be automatically applied. |
ConnectToLadder |
void ConnectToLadder(CNavLadder ladder)
|
Connect this area to given ladder. |
Contains |
bool Contains(TerrorNavArea area)
|
Return true if other area is on or above this area, but no others. |
ContainsOrigin |
bool ContainsOrigin(Vector point)
|
Return true if given point is on or above this area, but no others. |
DebugDrawFilled |
void DebugDrawFilled(int r, int g, int b, int a, float duration, bool noDepthTest)
|
Draw area as a filled rectangle of the given color. |
Disconnect |
void Disconnect(TerrorNavArea area)
|
Disconnect this area from given area. |
DisconnectLadder |
void DisconnectLadder(CNavLadder ladder)
|
Disconnect this area from given ladder. |
FindRandomSpot |
Vector FindRandomSpot()
|
Get random origin within extent of area. |
GetAdjacentArea |
TerrorNavArea GetAdjacentArea(int dir, int nAreas)
|
Return the n'th adjacent area in the given direction. |
GetAdjacentAreas |
void GetAdjacentAreas(int dir, table)
|
Fills a passed in table with all adjacent areas in the given direction. |
GetAdjacentCount |
int GetAdjacentCount(int dir)
|
Get the number of adjacent areas in the given direction. |
GetAttributes |
int GetAttributes()
|
Get area attribute bits. |
GetAvoidanceObstacleHeight |
float GetAvoidanceObstacleHeight()
|
Returns the maximum height of the obstruction above the ground. |
GetCenter |
Vector GetCenter()
|
Get center origin of area. |
GetCorner |
Vector GetCorner(int corner)
|
Get corner origin of area. |
GetDistanceSquaredToPoint |
float GetDistanceSquaredToPoint(Vector pos)
|
Return shortest distance between point and this area. |
GetDoor |
CBaseEntity GetDoor()
|
Returns the door entity above the area. |
GetElevator |
CBaseEntity GetElevator()
|
Returns the elevator if in an elevator's path. |
GetElevatorAreas |
void GetElevatorAreas(table)
|
Fills a passed in table with a collection of areas reachable via elevator from this area. |
GetID |
int GetID()
|
Get area ID. |
GetIncomingConnections |
void GetIncomingConnections(int dir, table)
|
Fills a passed in table with areas connected TO this area by a ONE-WAY link (ie: we have no connection back to them). |
GetLadders |
void GetLadders(int dir, table)
|
Fills a passed in table of ladders in direction. |
GetParent |
TerrorNavArea GetParent()
|
Returns the area just prior to this one in the search path. |
GetParentHow |
int GetParentHow()
|
Returns how we get from parent to us. |
GetPlaceName |
string GetPlaceName()
|
Get place name, null if no name. |
GetPlayerCount |
int GetPlayerCount(int team)
|
Return number of players of given team currently within this area (team of zero means any/all). |
GetRandomAdjacentArea |
TerrorNavArea GetRandomAdjacentArea(int dir)
|
Return a random adjacent area in the given direction. |
GetSizeX |
float GetSizeX()
|
Return the area size along the X axis. |
GetSizeY |
float GetSizeY()
|
Return the area size along the Y axis. |
GetSpawnAttributes |
int GetSpawnAttributes()
|
Get spawn attribute bits. |
GetTimeSinceCleared |
float GetTimeSinceCleared()
|
Returns the time since the area was cleared. |
GetZ |
float GetZ(Vector pos)
|
Returns the height of the area at the specified point. |
HasAttributes |
bool HasAttributes(int bits)
|
Has area attribute bits. |
HasAvoidanceObstacle |
bool HasAvoidanceObstacle(float maxHeight)
|
Returns true if there's a large, immobile object obstructing this area. |
HasSpawnAttributes |
bool HasSpawnAttributes(int bits)
|
Has spawn attribute bits. |
IsBlocked |
bool IsBlocked(int team, bool affectsFlow)
|
Return true if team is blocked in this area. |
IsBottleneck |
bool IsBottleneck()
|
Returns true if area is a bottleneck. |
IsCleared |
bool IsCleared(CTerrorPlayer player)
|
Returns true if this area has been cleared for the player. |
IsCompletelyVisibleToTeam |
bool IsCompletelyVisibleToTeam(int team)
|
Return true if given area is completely visible from somewhere in this area by someone on the team. |
IsConnected |
bool IsConnected(TerrorNavArea area, int dir)
|
Return true if this area is connected to other area in given direction. (If you set direction to -1 or 4, it will automatically check all directions for a connection) |
IsConnectedLadder |
bool IsConnectedLadder(CNavLadder ladder, int dir)
|
Return true if this area is connected to ladder in given direction. |
IsCoplanar |
bool IsCoplanar(TerrorNavArea area)
|
Return true if this area and given area are approximately co-planar. |
IsDamaging |
bool IsDamaging()
|
Return true if continuous damage (ie: fire) is in this area. |
IsDegenerate |
bool IsDegenerate()
|
Return true if this area is badly formed. |
IsEdge |
bool IsEdge(int dir)
|
Return true if there are no bi-directional links on the given side. |
IsFlat |
bool IsFlat()
|
Return true if this area is approximately flat. |
IsOverlapping |
bool IsOverlapping(TerrorNavArea area)
|
Return true if 'area' overlaps our 2D extents. |
IsOverlappingOrigin |
bool IsOverlappingOrigin(Vector pos, float tolerance)
|
Return true if 'pos' is within 2D extents of area. |
IsPotentiallyVisibleToTeam |
bool IsPotentiallyVisibleToTeam(int team)
|
Return true if any portion of this area is visible to anyone on the given team. |
IsRoughlySquare |
bool IsRoughlySquare()
|
Return true if this area is approximately square. |
IsSpawningAllowed |
bool IsSpawningAllowed()
|
Returns true if spawning is allowed in this area. |
IsUnderwater |
bool IsUnderwater()
|
Return true if area is underwater. |
IsValid |
bool IsValid()
|
Whether the handle belongs to a valid area. |
IsValidForWanderingPopulation |
bool IsValidForWanderingPopulation()
|
Returns true if area is valid for wandering population. |
IsVisible |
bool IsVisible(Vector point)
|
Return true if area is visible from the given point. |
MarkAreaCleared |
void MarkAreaCleared(CTerrorPlayer player)
|
Mark this area as cleared for the player. |
MarkAreaNotCleared |
void MarkAreaNotCleared()
|
Mark this area as not cleared. |
MarkAsBlocked |
void MarkAsBlocked(int team)
|
Mark this area as blocked for team. |
MarkAsDamaging |
void MarkAsDamaging(float duration)
|
Mark this area is damaging for the next 'duration' seconds. |
MarkObstacleToAvoid |
void MarkObstacleToAvoid(float height)
|
Marks the obstructed status of the nav area. |
RemoveAttributes |
void RemoveAttributes(int bits)
|
Removes area attribute bits. |
RemoveOrthogonalConnections |
void RemoveOrthogonalConnections(int dir)
|
Removes all connections in directions to left and right of specified direction. |
RemoveSpawnAttributes |
void RemoveSpawnAttributes(int bits)
|
Remove spawn attribute bits. |
SetAttributes |
void SetAttributes(int bits)
|
Set area attribute bits. |
SetPlaceName |
void SetPlaceName(string name)
|
Set place name. If you pass null, the place name will be set to nothing. |
SetSpawnAttributes |
void SetSpawnAttributes(int bits)
|
Set spawn attribute bits. |
UnblockArea |
void UnblockArea()
|
Unblocks this area. |
toc ↑ This is a script handle class for nav ladders.
Methods
Function | Signature | Description |
---|---|---|
ConnectTo |
void ConnectTo(TerrorNavArea area)
|
Connect this ladder to given area. |
Disconnect |
void Disconnect(TerrorNavArea area)
|
Disconnect this ladder from given area. |
GetBottomArea |
TerrorNavArea GetBottomArea()
|
Area of the bottom of the ladder. |
GetBottomOrigin |
Vector GetBottomOrigin()
|
World coords of the bottom of the ladder. |
GetDir |
int GetDir()
|
Return the way the ladder faces (ie: surface normal of climbable side). |
GetID |
int GetID()
|
Get ladder ID. |
GetLadderEntity |
CBaseEntity GetLadderEntity()
|
Returns the ladder entity. |
GetLength |
float GetLength()
|
Return the length of the ladder. |
GetPosAtHeight |
Vector GetPosAtHeight(float height)
|
Return x,y coordinate of the ladder at a given height. |
GetTopArea |
TerrorNavArea GetTopArea()
|
Area of the top of the ladder. |
GetTopOrigin |
Vector GetTopOrigin()
|
World coords of the top of the ladder. |
GetWidth |
float GetWidth()
|
Return the width of the ladder. |
IsConnected |
bool IsConnected(TerrorNavArea area, int dir)
|
Return true if given ladder is connected in given direction. |
IsInUse |
bool IsInUse(CBaseEntity ignore)
|
Return true if someone is on this ladder (other than 'ignore'). |
IsUsableByTeam |
bool IsUsableByTeam(int teamID)
|
Returns true if ladder is usable for team. |
IsValid |
bool IsValid()
|
Whether the handle belongs to a valid ladder. |
CNetPropManager
Instances ↑ Game Instance: NetProps
Allows reading and updating the network properties of an entity.
If the entity has multiple netprops with the same name, the data table name can be prepended with a dot to specify which one to use. i.e. m_itTimer.m_timestamp
.
Methods
Function | Signature | Description |
---|---|---|
GetPropArraySize |
int GetPropArraySize(CBaseEntity entity, string propertyName)
|
Returns the size of an netprop array, or -1. |
GetPropEntity |
CBaseEntity GetPropEntity(CBaseEntity entity, string propertyName)
|
Reads an EHANDLE-valued netprop (21 bit integer). Returns the script handle of the entity. |
GetPropEntityArray |
CBaseEntity GetPropEntityArray(CBaseEntity entity, string propertyName, int arrayElement)
|
Reads an EHANDLE-valued netprop (21 bit integer) from an array. Returns the script handle of the entity. |
GetPropFloat |
float GetPropFloat(CBaseEntity entity, string propertyName)
|
Reads a float-valued netprop. |
GetPropFloatArray |
float GetPropFloatArray(CBaseEntity entity, string propertyName, int arrayElement)
|
Reads a float-valued netprop from an array. |
GetPropInt |
int GetPropInt(CBaseEntity entity, string propertyName)
|
Reads an integer-valued netprop. |
GetPropIntArray |
int GetPropIntArray(CBaseEntity entity, string propertyName, int arrayElement)
|
Reads an integer-valued netprop from an array. |
GetPropString |
string GetPropString(CBaseEntity entity, string propertyName)
|
Reads an string-valued netprop. |
GetPropStringArray |
string GetPropStringArray(CBaseEntity entity, string propertyName, int arrayElement)
|
Reads an string-valued netprop from an array. |
GetPropType |
string GetPropType(CBaseEntity entity, string propertyName)
|
Returns the name of the netprop type as a string. |
GetPropVector |
Vector GetPropVector(CBaseEntity entity, string propertyName)
|
Reads a 3D vector-valued netprop. Todo: Does it work for other dimensions too?
|
GetPropVectorArray |
Vector GetPropVectorArray(CBaseEntity entity, string propertyName, int arrayElement)
|
Reads a 3D vector-valued netprop from an array. |
HasProp |
bool HasProp(CBaseEntity entity, string propertyName)
|
Checks if a netprop exists. |
SetPropEntity |
void SetPropEntity(CBaseEntity entity, string propertyName, CBaseEntity value)
|
Sets an EHANDLE-valued netprop (21 bit integer) to reference the specified entity. |
SetPropEntityArray |
void SetPropEntityArray(CBaseEntity entity, string propertyName, CBaseEntity value, int arrayElement)
|
Sets an EHANDLE-valued netprop (21 bit integer) from an array to reference the specified entity. |
SetPropFloat |
void SetPropFloat(CBaseEntity entity, string propertyName, float value)
|
Sets a netprop to the specified float. |
SetPropFloatArray |
void SetPropFloatArray(CBaseEntity entity, string propertyName, float value, int arrayElement)
|
Sets a netprop from an array to the specified float. |
SetPropInt |
void SetPropInt(CBaseEntity entity, string propertyName, int value)
|
Sets a netprop to the specified integer. |
SetPropIntArray |
void SetPropIntArray(CBaseEntity entity, string propertyName, int value, int arrayElement)
|
Sets a netprop from an array to the specified integer. |
SetPropString |
void SetPropString(CBaseEntity entity, string propertyName, string value)
|
Sets a netprop to the specified string. |
SetPropStringArray |
void SetPropStringArray(CBaseEntity entity, string propertyName, string value, int arrayElement)
|
Sets a netprop from an array to the specified string. |
SetPropVector |
void SetPropVector(CBaseEntity entity, string propertyName, Vector value)
|
Sets a netprop to the specified vector. |
SetPropVectorArray |
void SetPropVectorArray(CBaseEntity entity, string propertyName, Vector value, int arrayElement)
|
Sets a netprop from an array to the specified vector. |
CScriptEntityOutputs
toc ↑
Instances ↑ Game Instance: EntityOutputs
Allows reading and changing of entities' output data.
Methods
Function | Signature | Description |
---|---|---|
AddOutput |
void AddOutput(CBaseEntity entity, string outputName, string targetName, string inputName, string parameter, float delay, int timesToFire)
|
Adds a new output to the entity. |
GetNumElements |
int GetNumElements(CBaseEntity entity, string outputName)
|
Returns the number of array elements. |
GetOutputTable |
void GetOutputTable(CBaseEntity entity, string outputName, table, int arrayElement)
|
Fills the passed table with output information. |
HasAction |
bool HasAction(CBaseEntity entity, string outputName)
|
Returns true if an action exists for the output. |
HasOutput |
bool HasOutput(CBaseEntity entity, string outputName)
|
Returns true if the output exists. |
RemoveOutput |
void RemoveOutput(CBaseEntity entity, string outputName, string targetName, string inputName, string parameter)
|
Removes an output from the entity. |
CScriptResponseCriteria
Instances ↑ Game Instance: ResponseCriteria
Allows reading the response rules of an entity.
Methods
Function | Signature | Description |
---|---|---|
GetTable |
void GetTable(CBaseEntity entity, table)
|
Fills the passed table with all criteria. |
GetValue |
string GetValue(CBaseEntity entity, string criteriaName)
|
Returns a string. |
HasCriterion |
bool HasCriterion(CBaseEntity entity, string criteriaName)
|
Returns true if the criterion exists. |
Convars
toc ↑
Instances ↑ Game Instance: Convars
An interface to manipulate the convars on the server.
Methods
Function | Signature | Description |
---|---|---|
GetClientConvarValue |
string GetClientConvarValue(string name, int entindex)
|
Returns the convar value for the entindex as a string. Only works on client convars with the FCVAR_USERINFO flag. Convars without FCVAR_USERINFO or non-existent ones return empty string |
GetStr |
string GetStr(string name)
|
Returns the convar as a string. Returns null if no such convar. |
GetFloat |
float GetFloat(string name)
|
Returns the convar as a float. Returns null if no such convar. |
SetValue |
void SetValue(string name, value)
|
Sets the value of the convar. Supported types are bool, int, float, string. |
CPointTemplate
toc ↑ Extends CBaseEntity ↑
Script handle class for point_template.
Hooks
table PreSpawnInstance(string entityClass, string entityName)
- If this is defined, it will be called right before the entity is created, and any KeyValues returned will be assigned to the entity.
- This could be used to dynamically assign target names, colors, even models. Unfortunately, models don't work like one would think. Yes, it is possible to change that gas tank into a football model, will even keep the weapon_gascan class, but it won't behave like one.
function PreSpawnInstance( entityClass, entityName )
{
return
{
rendercolor = "0 255 0"
targetname = "mySpawnedEntity"
}
}
void PostSpawn(table entities)
- Called after the entities are spawned. A table with the handles of the spawned entities indexed by name is passed to the function. Could use this to connect outputs or do whatever needs to be done after the entity was created.
function PostSpawn( entities )
{
foreach( name, handle in entities )
{
printl( name + ": " + handle )
}
}
CPointScriptTemplate
toc ↑ Extends CBaseEntity ↑
Script handle class for point_script_template.
Methods
Function | Signature | Description |
---|---|---|
AddTemplate |
void AddTemplate(string, handle)
|
Add an entity to the template spawner. |
SetGroupSpawnTables |
void SetGroupSpawnTables(handle, handle)
|
Cache the group spawn tables. |
CPointScriptUseTarget
toc ↑ Extends CBaseEntity ↑
Script handle class for the point_script_use_target entity.
Methods
Function | Signature | Description |
---|---|---|
CanShowBuildPanel |
void CanShowBuildPanel(bool showPanel)
|
Sets if the UI panel for the button is shown. |
GetUseModelName |
string GetUseModelName()
|
Get the entity name of the prop bound to this button. |
SetProgressBarText |
void SetProgressBarText(string text)
|
Sets the use text for the button UI. |
SetProgressBarSubText |
void SetProgressBarText(string text)
|
Sets the subtext below the progress bar for the button UI. |
SetProgressBarFinishTime |
void SetProgressBarFinishTime(float time)
|
Sets the total time the button takes to use. If '0', no progress bar will be displayed. |
SetProgressBarCurrentProgress |
void SetProgressBarCurrentProgress(float time)
|
Sets the current use progress. It can be used to save the use progress when the user releases the use key. |
StopUse |
void StopUse()
|
Stop the current use action. |
Members
These variables are only available in the Entity Script after the entity has spawned. They're a custom C++ class, CHandles which also is sometimes referred as EHANDLEs (Entity Handles). These can't be used or modified like the usual script handles, and really is only meant for verifications with comparing the output of theCBaseEntity ↑::GetEntityHandle()
method.
Instance | Type | Description |
---|---|---|
UseModelEntity |
[C++] CHandle<CBaseEntity>
|
The Use Model prop associated with this entity. |
PlayerUsingMe |
[C++] CHandle<CBaseEntity>
|
The current using player. Todo: Recheck on this old info: Is it not 0 / null if not being used? .
|
Hooks
These VScript methods are called on the script set in the Entity Scripts keyvalue for the point_script_use_target.
Function | Signature | Description |
---|---|---|
OnUseFinished |
void OnUseFinished()
|
Called when the player has used this button for at least 'FinishTime' seconds. |
OnUseStart |
bool OnUseStart()
|
This breaks point_script_use_target when declared. Use ConnectOutput() and hook a function to the OnUseStarted output instead.
|
OnUseStop |
void OnUseStop(float timeUsed)
|
Called when the player stops using this button. Passes the time this button has been used (time between StartUse and now). |
Precache |
void Precache()
|
Called by the game engine when the entity first spawns, immediately after this script is run. |
Decider
toc ↑ An isolated instance of a rulescript database.
Methods
Function | Signature | Description |
---|---|---|
constructor |
||
AddRule |
bool AddRule(handle CRule)
|
Add a CRule object (defined in rulescript_base.nut) |
FindAllMatches |
handle FindAllMatches(handle query, float leeway)
|
Returns an array of all matching responses. If leeway is nonzero, all results scoring within 'leeway' of the best score return. |
FindBestMatch |
handle FindBestMatch(handle query)
|
Query the database and return the best result found. If multiple of equal score found, an arbitrary one returns. |
IsValid |
bool IsValid()
|
Whether the object belongs to a valid entity(?). |
regexp
toc ↑ The built-in Squirrel class for regular expressions.
Methods
Function | Signature | Description |
---|---|---|
constructor |
regexp()
|
|
capture |
[table] capture(str, [start])
|
Returns an array of tables containing two indexes ("begin" and "end") of the first match of the regular expression in the string str. An array entry is created for each captured sub expressions. If no match occurs returns null. The search starts from the index start of the string, if start is omitted the search starts from the beginning of the string. |
match |
bool match(str)
|
Returns a true if the regular expression matches the string str, otherwise returns false. |
search |
table search(str, [start])
|
Returns a table containing two indexes ("begin" and "end") of the first match of the regular expression in the string str, otherwise if no match occurs returns null. The search starts from the index start of the string, if start is omitted the search starts from the beginning of the string. |
subexpcount |
CCallChainer
toc ↑
CCallChainer objects collect all functions with a matching prefix in a given scope, then inserts it all into the chains
table with the prefix removed. All collected unprefixed functions can then be called in a chain using the class's Call()
method, given the method's event argument matches the functions' name.
Whenever a CCallChainer object is created, a function named Dispatch
followed by its given prefix will also be created, which the class binds the environment of its Call()
method to.
Methods
Function | Signature | Description |
---|---|---|
constructor |
CCallChainer(string functionPrefix, table scope = null)
|
Creates a CCallChainer object that'll collect functions that have a matching prefix in the given scope. |
PostScriptExecute |
void PostScriptExecute()
|
Search for all non-native functions with matching prefixes, then push them into the chains table.
|
Call |
bool Call(string event, any ...)
|
Find an unprefixed function name in the chains table and call it with the given arguments.
|
Members
Instance | Type | Description |
---|---|---|
chains |
table
|
Contains names of unprefixed functions, each with an array of functions to call. |
prefix |
string
|
Prefix that functions should have to be added into the chains table. Set by the constructor.
|
scope |
table
|
If set, seek functions in this scope instead. Set by the constructor. |
CSimpleCallChainer
toc ↑
Intended to be simpler to use than CCallChainer ↑, the class CSimpleCallChainer holds only a single chain of functions inside an array instead of multiple inside a table. As such, its Call()
method does not need a function's name.
This class is also used internally by these CBaseEntity ↑ hooks: Precache()
and OnPostSpawn()
.
Methods
Function | Signature | Description |
---|---|---|
constructor |
CSimpleCallChainer(string functionPrefix, table scope = null, exactMatch = false)
|
Creates a CSimpleCallChainer object that'll collect functions that have a matching prefix in the given scope, unless it seek for an exact name match. |
PostScriptExecute |
void PostScriptExecute()
|
Begin searching for all non-native functions with matching prefixes, then push them into the chain array.
|
Call |
bool Call(any ...)
|
Call all functions inside the chain array with the given arguments.
|
Members
Instance | Type | Description |
---|---|---|
chain |
array
|
All functions to be called by the Call() method.
|
exactMatch |
bool
|
If set, names of non-native functions and prefix must be an exact match. Set by the constructor.
|
prefix |
string
|
Prefix that functions should have to be added into the chain array. Set by the constructor.
|
scope |
table
|
If set, seek functions in this scope instead. Set by the constructor. |
LateBinder
Methods
Function | Signature | Description |
---|---|---|
Begin |
||
End |
||
EstablishDelegation |
||
HookRootMetamethod |
||
UnhookRootMetamethod |
||
RemoveDelegation |
||
Resolve |
Members
Instance | Type | Description |
---|---|---|
m_bindNamesStack |
array
|
|
m_fixupSet |
array
|
|
m_log |
bool
|
|
m_logIndent |
int
|
|
m_targetTable |
table?(null)
|
Data Types
Vector
toc ↑ Squirrel equivalent of the C++ Vector class. It is a three-dimensional vector with overloaded arithmetic operations for both Vectors and scalar values.
Methods
Function | Signature | Description |
---|---|---|
constructor |
Vector(float x = 0, float y = 0, float z = 0)
|
Creates a new vector with the specified Cartesian coordiantes. |
Cross |
float Cross(Vector factor)
|
The vector product of two vectors. Returns a vector orthogonal to the input vectors. |
Dot |
float Dot(Vector factor)
|
The scalar product of two vectors. |
Length |
float Length()
|
Magnitude of the vector. |
LengthSqr |
float LengthSqr()
|
The magnitude of the vector squared. Faster than the above method. |
Length2D |
float Length2D()
|
Returns the magnitude of the vector on the x-y plane. Meant to be used when working with the client's HUD. |
Length2DSqr |
float Length2DSqr()
|
Returns the square of the magnitude of the vector on the x-y plane. Faster than the above method. |
Norm |
float Norm()
|
Seems to also return the vector length. |
Scale |
Vector Scale(float factor)
|
Scales the vector magnitude. |
ToKVString |
string ToKVString()
|
Returns a string without separations commas. Note:Not required for the
SpawnEntityWithTable function, as it understands the Vector data type. |
tostring |
string tostring()
|
Returns a human readable string. |
Members
Instance | Type | Description |
---|---|---|
x |
float
|
Cartesian X axis. |
y |
float
|
Cartesian Y axis. |
z |
float
|
Cartesian Z axis. |
Operations
Operation | Return Type | Description |
---|---|---|
Vector + Vector |
Vector
|
Returns the sum of both classes's members (XYZ). |
Vector - Vector |
Vector
|
Returns the subtraction of both classes's members (XYZ). |
Vector * int |
Vector
|
Returns the multiplication of a Vector against a scalar. |
Vector * float
|
QAngle
toc ↑ Squirrel equivalent of the C++ QAngle class. Represents a three-dimensional orientation as Euler angles.
Has overloaded arithmetic operations with both QAngles and scalar values.
Methods
Function | Signature | Description |
---|---|---|
constructor |
QAngle(float pitch = 0, float yaw = 0, float roll = 0)
|
Creates a new QAngle. |
Forward |
Vector Forward()
|
Returns the Forward Vector of the angles. |
Left |
Vector Left()
|
Returns the left Vector of the angles. Bug*:Returns right Vector instead |
Pitch |
float Pitch()
|
Returns the pitch angle in degrees. |
Roll |
float Roll()
|
Returns the roll angle in degrees. |
ToKVString |
string ToKVString()
|
Returns a string with the values separated by one space. Tip:Use this with the
angles key when using the SpawnEntityWithTable function. |
ToQuat |
Quaternion ToQuat()
|
Returns a quaternion representaion of the orientation. |
Up |
Vector Up()
|
Returns the Up Vector of the angles. |
Yaw |
float Yaw()
|
Returns the yaw angle in degrees. |
Members
Instance | Type | Description |
---|---|---|
x |
float
|
Pitch in degrees. |
y |
float
|
Yaw in degrees. |
z |
float
|
Roll in degrees. |
Operations
Operation | Return Type | Description |
---|---|---|
QAngle + QAngle |
QAngle
|
Sum of both classes's members (XYZ). |
QAngle - QAngle |
QAngle
|
Subtraction of both classes's members (XYZ). |
QAngle * int |
QAngle
|
QAngle multiplied by a number. |
QAngle * float
|
Vector2D, Vector4D
toc ↑ Two and four-dimensional equivalents of the Vector data type. Has the same overloaded operators.
Methods
Function | Signature | Description |
---|---|---|
constructor |
Vector2D(float x = 0, float y = 0)
|
Creates a new 2D vector with the specified Cartesian coordinates. |
constructor |
Vector4D(float x = 0, float y = 0, float z = 0, float w = 0)
|
Creates a new 4D vector with the given coordinate numbers. |
Dot |
float Dot(VectorXD factor)
|
The scalar product of two vectors. |
Length |
float Length()
|
Magnitude of the vector. |
LengthSqr |
float LengthSqr()
|
The magnitude of the vector squared. Faster than the above method. |
Norm |
float Norm()
|
Seems to also return the vector length. |
ToKVString |
string ToKVString()
|
Returns a string without separations commas. |
Members
Instance | Type | Description |
---|---|---|
x |
float
|
Cartesian X axis. |
y |
float
|
Cartesian Y axis. |
z |
float
|
Cartesian Z axis. Vector4D only. |
w |
float
|
Component for possibly creating homogeneous coordinates? Vector4D only. |
Operations
Operation | Return Type | Description |
---|---|---|
Vector2D + Vector2D Vector4D + Vector4D |
Vector2D Vector4D
|
Returns the sum of both classes's members (XYZ). |
Vector2D - Vector2D Vector4D - Vector4D |
Vector2D Vector4D
|
Returns the subtraction of both classes's members (XYZ). |
Vector2D * int Vector4D * int |
Vector2D Vector4D
|
Returns the multiplication of the given Vector variant against a scalar. |
Vector2D * float Vector4D * float
|
Quaternion
toc ↑ A Quaternion represents rotations in three-dimensional space.
Methods
Function | Signature | Description |
---|---|---|
constructor |
Quaternion()
|
Creates a new identity quaternion. |
constructor |
Quaternion(float x = 0,float y = 0,float z = 0,float w = 0)
|
Creates a new quaternion of the form: w + xi + yj + zk .
|
Dot |
float Dot(Quaternion factor)
|
The 4D scalar product of two quaternions. represents the angle between the quaternions in the range [1, 0]. |
Invert |
Quaternion Invert()
|
Returns a quaternion with the complimentary rotation. |
Norm |
Quaternion Norm()
|
Normalizes the 4D vector length. Todo: What effect does this have in quaternions?
|
SetPitchYawRoll |
void SetPitchYawRoll(float pitch, float yaw, float roll)
|
Recomputes the quaternion from the supplied Euler angles. |
ToKVString |
string ToKVString()
|
Returns a string with the values separated by one space. |
ToQAngle |
QAngle ToQAngle()
|
Returns the angles resulting from the rotation. |
Members
Instance | Type | Description |
---|---|---|
x |
float
|
Vector component along the i axis. |
y |
float
|
Vector component along the j axis. |
z |
float
|
Vector component along the k axis. |
w |
float
|
Scalar part. |
Operations
Operation | Return Type | Description |
---|---|---|
Quaternion + Quaternion |
Quaternion
|
Sum of the two Quaternions. |
Quaternion - Quaternion |
Quaternion
|
Subtraction of the two Quaternions. |
Quaternion * int |
Quaternion
|
Quaternion multiplied by a number. |
Quaternion * float
|
Scripted Mode
toc ↑ Enabling Scripted Mode makes a large amount of features like cm_ director options and various hooks available. Scripted Mode is enabled if a script (<current_mode_name>.nut) is present.
Scripted Mode data are stored under the g_ModeScript
scope.
sm_utilities.nut
toc ↑ sm_utilities contains many wrapper functions for manipulating different features. Only a few of them are listed here, see the EMS tutorial for more examples. These functions are inside g_MapScript scope.
Function | Signature | Description |
---|---|---|
CheckOrSetMapCallback |
void CheckOrSetMapCallback(cb_name, cb_default)
|
Pass a callback and default @ for it, if it doesnt exist in current table, place it there. |
DeepPrintTable |
void DeepPrintTable(handle table, string prefix = "")
|
Print out a table (and subtables) to the console. This works with classes as well (not instances). |
DuplicateTable |
table DuplicateTable(table source)
|
This returns a deep copy of the passed in table. |
InjectTable |
void InjectTable(table override, table base)
|
Inject the override data into the base table - i.e. add any new ones, overwrite dupes. |
SpawnStartBox |
handle SpawnStartBox(centerobjname, useFloating, width, depth, barriermodel, min_gap)
|
Auto-create a startbox that will give you a callback when the first player exits it. |
TeleportPlayersToStartPoints |
void TeleportPlayersToStartPoints(string spawnpointName)
|
Teleport players to start entities named by the argument - must have 4 spawnpoints. |
Ticker_AddToHud |
void Ticker_AddToHud(table hudTable, string strInit, bool blink)
|
Adds ticker data to a passed in HUDTable. |
Ticker_NewStr |
void Ticker_NewStr(string newStr, float newTimeout)
|
Sets the current Ticker string, w/an optional timeout value. |
TimeToDisplayString |
string TimeToDisplayString(float disp_time)
|
Convert a # of seconds to a displayable time string form m:ss |
Hooks
toc ↑ Scripted mode provides hook functions, used by simply adding a function with the same name and arguments to the script, and are called back by the C++ code at the appropriate moments.
OnShutdown
void OnShutdown()
: Called as the mutation is shutdown, happens for multiple scenarios, such as map change or a mission being lost. To retrieve the reason, use such a code:
function OnShutdown()
{
local reason = SessionState.ShutdownReason
local nextmap = SessionState.NextMap
printl("Mutation shut down under reason " + reason.tostring() + ", next map is " + nextmap)
}
OnActivate
void OnActivate()
: Called after OnGameplayStart. Unknown anything else about it, comes likely from EMS and pulled via console command "script g_ModeScript.DeepPrintTable(getroottable())"
OnGameplayStart
void OnGameplayStart()
: Called whenever the gameplay starts.
AllowBash
int AllowBash(handle basher, handle bashee)
: called whenever melee bash is used. Returns these values:
- ALLOW_BASH_ALL - normal melee behavior
- ALLOW_BASH_NONE - do nothing at all
- ALLOW_BASH_PUSHONLY - applies physics push but deals no damage (including prevention of insta-kill ambush behavior)
AllowTakeDamage
bool AllowTakeDamage(table damageTable)
: Adding a function with this name in the script causes C++ to call it on all damage events. The damageTable is actually defined in scriptedmode.nut and filled in as appropriate before each call.
ScriptedDamageInfo <-
{
Attacker = null // hscript of the entity that attacked
Victim = null // hscript of the entity that was hit
Inflictor = null // hscript of the entity that was the inflictor
DamageDone = 0 // copyback variable for how much damage done
DamageType = -1 // copyback variable for what type of damage
Location = Vector(0,0,0) // where
Weapon = null // by what - often Null (say if attacker was a common)
}
Returning "false" causes the damage will be stopped and nothing will be done to the target (though animation/bloodstains/decals will probably still happen, sorry about that). The only fields read back by the C++ is DamageDone, so it can be used to change the damage value before it is applied, and DamageType, so it can be used to change the type of damage. The Type field is a bitfield, of which several key #def's are exported to script (DMG_HEADSHOT, DMG_BULLET, DMG_BUCKSHOT, DMG_MELEE, DMG_STUMBLE, DMG_BLAST, DMG_BLAST_SURFACE, DMG_BURN ). Some situations will trigger this event still and deal zero damage while reporting a normal damage value: 1. Falling from a slope that gives immunity to fall damage ( Dark Carnival First Chapter )
2. A tank rock hits you after a smoker grabbed you.
BotQuery
bool BotQuery(int queryflag, handle entity, bool defaultvalue)
: Hook to control survivor bot behavior. Only one known flag is supported.
BOT_QUERY_NOTARGET
- Fired when a bot wants to bash a prop. Returningfalse
disallows the bashing.
CanPickupObject
bool CanPickupObject(handle object)
: Hook function for deciding whether a given prop should be pickupable (HL2 style). Returning true
makes the players able to pick up the object. Only functional for server side props. If this is defined it must return true in order the PickupObject() function to work.
InterceptChat
void InterceptChat(string message, CTerrorPlayer speaker)
: If you put a function with this name in your script, C++ will call it on all chat messages. Passing in the (annotated) chat string and the handle of the speaker. If the function returns false, it will prevent other players from seeing the chat message except for the player who entered it.
SetupModeHUD
[Todo]
UserConsoleCommand
void UserConsoleCommand(handle playerScript, arg)
: when a user does a scripted_user_func argument
at console (or bound to a key) this function is called (if it exists). The playerscript is which players console it came from. You can pass strings or whatever, of course. So could do a switch statement off arg
to give players special controls, etc.
OnGameEvent_x
void OnGameEvent_x(table params)
: A callback that is called when the game event x is fired. See resource\gameevents.res
, resource\serverevents.res
and resource\modevents.res
for valid events. The callback functions can be registered independently from Scripted Mode, using: __CollectGameEventCallbacks(this)
See EMS Appendix - Game Events for more information.
Global Functions
Printing and Drawing
toc ↑ Functions for printing out messages or drawing elements in the world, mostly for debugging reasons.
Debug
prefix requires the cvar developer
be enabled and the game unpaused.They also do not appear in multiplayer, only on a local server.
Function | Signature | Description | |
---|---|---|---|
__DumpScope |
void __DumpScope(int indentation, table scope)
|
Dumps a scope's contents and expands all tables and arrays; this is what the ent_script_dump command uses.
Tip:You can use this to print tables/arrays.
| |
ClientPrint |
void ClientPrint(CTerrorPlayer player, int destination, string message)
|
Print a client message. If you pass null instead of a valid player, the message will be sent to all clients. | |
DebugDrawBox |
void DebugDrawBox(Vector origin, vector min, vector max, int r, int g, int b, int alpha, float duration)
|
Draw a debug overlay box. | |
DebugDrawBoxAngles |
void DebugDrawBoxAngles(Vector origin, Vector min, Vector max, QAngle direction, Vector rgb, int alpha, float duration)
|
Draw a debug oriented box (cent, min, max, angles(p,y,r), vRgb, a, duration). | |
DebugDrawBoxDirection |
void DebugDrawBoxDirection(Vector center, Vector min, Vector max, Vector forward, Vector rgb, float alpha, float duration)
|
Draw a debug forward box. | |
DebugDrawCircle |
void DebugDrawCircle(Vector center, Vector rgb, float alpha, float radius, bool ztest, float duration)
|
Draw a debug circle. | |
DebugDrawClear |
void DebugDrawClear()
|
Try to clear all the debug overlay info. | |
DebugDrawLine |
void DebugDrawLine(Vector start, Vector end, int red, int green, int blue', bool zTest, float time)
|
Draw a debug overlay line. | |
DebugDrawLine_vCol |
void DebugDrawLine_vCol(Vector start, vector end, vector rgb, bool ztest, float duration)
|
Draw a debug line using color vec. | |
DebugDrawScreenTextLine |
void DebugDrawScreenTextLine(float x, float y, int lineOffset, string text, int r, int g, int b, int a, float duration)
|
Draw text with a line offset. | |
DebugDrawText |
void DebugDrawText(Vector origin, string text, bool useViewCheck, float duration)
|
Draw text on the screen, starting on the position of origin. | |
DumpObject |
void DumpObject(handle object)
|
Dumps information about a class or instance. | |
HUDManageTimers |
void HUDManageTimers(int timerID, int command, float value)
|
Manages the HUD timers. Valid command enumerations are: TIMER_DISABLE, TIMER_COUNTUP, TIMER_COUNTDOWN, TIMER_STOP, TIMER_SET | |
HUDPlace |
void HUDPlace(int slot, float x, float y, float width, float height)
|
Sets the position of a HUD element. See L4D2_EMS/Appendix:_HUD | |
HUDReadTimer |
float HUDReadTimer(int timerID)
|
Returns the value of a HUD timer. See L4D2_EMS/Appendix:_HUD | |
HUDSetLayout |
void HUDSetLayout(table HUDTable)
|
Applies a HUD to the screen. See L4D2_EMS/Appendix:_HUD Important:Scriptedmode feature, usable properly in mutations only
| |
Msg |
void Msg(string message)
|
Prints message to console without any line feed after. | |
print |
void print(string message)
|
Prints message to console without any line feed after. Identical to Msg() .
| |
printl |
void printl(string message)
|
Prints message to console with a line feed after. | |
realPrint |
void realPrint(string message)
|
Identical to print. print seems to be a wrapper for this. | |
ShowMessage |
void ShowMessage(string message)
|
Print a HUD message on all clients. Bug*:Non-functional. | |
Say |
void Say(CTerrorPlayer player, string message, bool teamOnly)
|
Calling this will have the specified player send the message to chat, either to teamOnly (true) or to everyone. | |
SendToConsole |
void SendToConsole(string command)
|
Send a string to the console as a command. | |
SendToServerConsole |
void SendToServerConsole(string command)
|
Send a string to the server console as a command. |
Hooks
DebugTick
void DebugTick()
: Called every tick, if a function with this name is in your script.
Update
void Update()
: Called every second, including the first, if a function with this name is in your script when it runs for the first time. Gives easy control over the flow of a game.
Entity Manipulation
Function | Signature | Description |
---|---|---|
AddThinkToEnt |
void AddThinkToEnt(handle entity, string FuncName)
|
Sets a function in the entity's script to rerun by itself constantly. |
CommandABot |
bool CommandABot(table commandTable)
|
Issues commands to bots based on a table configuration. |
ConnectOutputs |
void ConnectOutputs(table)
|
sets output functions for entity by table [Todo] |
DoEntFire |
void DoEntFire(string target, string action, string value, float delay, handle activator, handle caller)
|
Adds entity I/O event to the event queue to be processed at appropriate time based on specified delay. The caller and activator argument takes a CBaseEntity script handle, and entities assigned can receive inputs with target set to !self, or !activator / !caller. |
EntFire |
void EntFire(string target, string action, string value = null, float delay = 0, handle activator = null)
|
Wrapper for DoEntFire() . If called from an entity's script scope it sets caller to self. Bug*:Using value 0 mistakenly converts it to empty string. Use "0" as value to prevent that |
DropFire |
void DropFire(Vector location)
|
Drop a fire pool from the specified Vector location. |
DropSpit |
void DropSpit(Vector location)
|
Drop a spit pool from the specified Vector location. |
EmitAmbientSoundOn |
void EmitAmbientSoundOn(string soundName, float volume, int soundlevel, int pitch, handle entity)
|
Play named sound on an entity that has similar configurations to ambient_generic. |
EmitSoundOnClient |
void EmitSoundOnClient(string soundScript, handle player)
|
Play named sound only on the client for the specified player. |
EmitSoundOn |
void EmitSoundOn(string soundScript, handle entity)
|
Play named sound on an entity. |
EntIndexToHScript |
CBaseEntity EntIndexToHScript(int entIndex)
|
Returns the script handle for the given entity index. |
FindRescueAreaTrigger |
CBaseTrigger FindRescueAreaTrigger()
|
Returns the trigger entity for the rescue area. |
GetListenServerHost |
handle GetListenServerHost()
|
Get the host player on a listen server. |
GetFriction |
float GetFriction(CTerrorPlayer player)
|
Returns the Friction on a player entity, meaningless if not a player. |
GetInvTable |
void GetInvTable(CTerrorPLayer player,table invTable)
|
Fills invTable with the specified player's inventory. |
GetPhysVelocity |
Vector GetPhysVelocity(handle entity)
|
Returns the velocity of the entity. |
GetPhysAngularVelocity |
Vector GetPhysAngularVelocity(handle entity)
|
Returns the Angular velocity of the entity. |
GetPlayerFromCharacter |
handle GetPlayerFromCharacter(int characterType)
|
Given a character type, return the entity, or null. |
GetPlayerFromUserID |
handle GetPlayerFromUserID(int ID)
|
Given a user id, return the entity, or null. |
IsPlayerABot |
bool IsPlayerABot(handle player)
|
Is this player/entity a bot. |
PickupObject |
void PickupObject(handle player, handle entity)
|
Object from world is put into the "Held" slot of the player. Warning: it will smoothly interpolate from where it is to the players hand - which is a bit goofy if it is on other side of level. |
PlayerInstanceFromIndex |
CTerrorPlayer PlayerInstanceFromIndex(int index)
|
Get a script handle of a player using the player index. |
PrecacheEntityFromTable |
bool PrecacheEntityFromTable(table keyvalues)
|
Precache an entity from KeyValues in a table. |
RotateOrientation |
QAngle RotateOrientation(QAngle, QAngle)
|
Rotate a QAngle by another QAngle. |
RotatePosition |
Vector RotatePosition(Vector origin, QAngle rotation, Vector input)
|
Rotate the input Vector around an origin. |
SetFakeClientConVarValue |
void SetFakeClientConVarValue(handle bot, string cvar, string value)
|
Sets a USERINFO client ConVar for a fakeclient. |
SpawnEntityFromTable |
handle SpawnEntityFromTable(string classname, table keyvalues)
|
Native function for entity spawning. See L4D2_EMS/Appendix:_Spawning. |
SpawnEntityGroupFromTable |
bool SpawnEntityGroupFromTable(table entityGroup)
|
Native function for entity group spawning. See L4D2_EMS/Appendix:_Spawning. |
StopAmbientSoundOn |
void StopAmbientSoundOn(string soundName, handle entity)
|
Stop named sound on an entity that has similar configurations to ambient_generic. |
StopSoundOn |
void StopSoundOn(string soundScript, handle entity)
|
Stop named sound on an entity. |
ZSpawn |
bool ZSpawn(table spawnTable)
|
Spawn an infected of liking, with a choice. |
Response Rules
Theg_rr
table is used to create and/or override responses and their rules, allowing custom concepts to be dynamically made without altering existing talker files.
Function | Signature | Description |
---|---|---|
rr_ProcessRules |
void rr_ProcessRules(handle rulesArray)
|
Processes and adds the given rulesArray table to the talker system. This is an incomplete implementation of custom talker concepts for VScript, but it is mostly functional. |
rr_PlaySoundFile |
unknown rr_PlaySoundFile(CTerrorPlayer speaker, unknown query, unknown soundfile, unknown context, unknown contextToWorld, unknown volume, unknown func)
|
|
rrDebugPrint |
void rrDebugPrint(string message)
|
Print function that works similarly to printl() but prepends RR_TESTBED: to the start of the message.
|
rr_ProcessResponse |
unknown rr_ProcessResponse(unknown resp)
|
|
PrintTable |
void PrintTable(handle table)
|
Print a table without searching through subtables to the console. Works with classes as well (not instances). |
rr_ProcessCriterion |
unknown rr_ProcessCriterion(unknown crit)
|
|
rr_EmitSound |
unknown rr_EmitSound(CTerrorPlayer speaker, unknown query, unknown soundName, unknown context, unknown contextToWorld, unknown func)
|
|
rr_CharacterSpeak |
unknown rr_CharacterSpeak(CTerrorPlayer speaker, unknown query)
|
|
rr_ApplyContext |
unknown rr_ApplyContext(CTerrorPlayer speaker, unknown query, unknown contextData, unknown contextToWorld, unknown func)
|
|
rrPrintTable |
void rrPrintTable(handle table, prefix = "\t")
|
Prints a table (non-recursive) |
Other
Function | Signature | Description |
---|---|---|
AddToScriptHelp |
||
Assert |
void Assert(bool value, string msg = null)
|
Test value and if not true, throws an exception string "Assertion failed".
If msg parameter is set, then an exception string will be "Assertion failed: your message". |
CheckForSpecialStage |
void CheckForSpecialStage(level, stage_list, stage_info)
|
Helper for picking a random special stage based on stage_info table. |
ClearGameEventCallbacks |
void ClearGameEventCallbacks()
|
Empties the tables of game event callback functions. |
ClearSavedTables |
void ClearSavedTables()
|
Removes any tables saved with SaveTable() .
|
developer |
int developer()
|
The current level of the developer console variable.
|
Document |
void Document(unknown symbolOrTable, unknown itemIfSymbol = null, string descriptionIfSymbol = null)
|
|
DoIncludeScript |
bool DoIncludeScript(string file, handle/table scope)
|
Execute a script. and put all its content for the argument passed to the scope parameter. (internal)
|
IncludeScript |
bool IncludeScript(string file, handle scope = null)
|
Wrapper for DoIncludeScript. |
DoUniqueString |
string DoUniqueString(string/null input)
|
Generate a string guaranteed to be unique across the life of the script VM. This function requires a string or a null value as an input, otherwise throws an error.
You should use |
Ent |
handle Ent(string/int idxorname)
|
Wrapper function. If a string is provided, it'll find the entity by name using the string. But if an integer is provided, it'll be converted to a Script Handle before verifying the entity exists. |
FileToString |
string FileToString(string path)
|
Reads the file located in left4dead2/ems/path and returns its contents as a string. path supports folders and special names "." and "..", which indicate "current folder" and "parent folder" respectfully.
If file does not exist, a null value will be returned. If file is longer than 16384 bytes, it will return a null value and print an error "File ems/path (from path) is len [actual file length here] too long for a ScriptFileRead". Warning: if path contains folders, these folders will be created, if missing. Check carefully what you are reading, since there is no way to remove files/folders using VScript. |
FireGameEvent |
string FireGameEvent(string event, table params)
|
Fire a game event to a listening callback function in script. Parameters are passed in a squirrel table. |
FireScriptEvent |
void FireScriptEvent(event, params)
|
Wrapper for __RunEventCallbacks()
|
ForceScavengeStart |
void ForceScavengeStart()
|
Starts the scavenge round, even if the setup timer hasn't elapsed. |
ForceSurvivalStart |
void ForceSurvivalStart()
|
Starts the survival round, even if the survivors haven't activated the radio. |
ForceVersusStart |
void ForceVersusStart()
|
Starts the versus round, even if the survivors haven't left the safe room. |
GetCharacterDisplayName |
string GetCharacterDisplayName(CTerrorPlayer player)
|
Return null if not a survivor, else the survivor's chosen character's name. This does not work with team 4 survivors.
|
GetCurrentFlowDistanceForPlayer |
float GetCurrentFlowDistanceForPlayer(CTerrorPlayer player)
|
Returns the navigation flow distance from the start to the specified player. |
GetCurrentFlowPercentForPlayer |
float GetCurrentFlowPercentForPlayer(CTerrorPlayer player)
|
Returns how far in the navigation flow from the start to the end the player is. |
GetFlowDistanceForPosition |
float GetFlowDistanceForPosition(Vector position)
|
Returns the navigation flow distance from the start to the specified point. |
GetFlowPercentForPosition |
float GetFlowPercentForPosition(Vector position, bool unknown)
|
Returns how far in the navigation flow from the start to the end the position is. |
GetMaxFlowDistance |
float GetMaxFlowDistance()
|
Returns the navigation flow distance from the start to the end of the level. |
GetAverageSurvivorFlowDistance |
float GetAverageSurvivorFlowDistance()
|
Returns the navigation flow distance from the start to the survivors position averaged. |
GetDifficulty |
int GetDifficulty()
|
Returns the current difficulty as a numeric value. Easy = 0, Normal = 1, Advanced = 2, Expert = 3. |
GetDifficultyString |
string GetDifficultyString()
|
Returns the current difficulty as a string. Difficulty names are in z_difficulty cvar style: Easy, Normal, Hard, Impossible. |
GetFrameCount |
void GetFrameCount()
|
Returns the engine's current frame count. |
GetFunctionSignature |
||
GetInfectedStats |
void GetInfectedStats(table statTable)
|
Fills statTable with some infected counts/etc... Right now the list is Witches, Tanks, Specials, Commons, though we may add more as requested going forward. |
GetModelIndex |
int GetModelIndex(string filename)
|
Returns index of model by name. |
GetScavengeItemsGoal |
int GetScavengeItemsGoal()
|
Returns number of Scavenge items needed. |
GetScavengeItemsRemaining |
int GetScavengeItemsRemaining()
|
Returns number of Scavenge items remaining. |
GetSoundDuration |
float GetSoundDuration(string soundname, string actormodel)
|
Returns float duration of the sound. Takes soundname and optional actormodelname. |
HasConfigurableDifficultySetting |
bool HasConfigurableDifficultySetting()
|
Returns true if the mode has more than a single difficulty. |
HasPlayerControlledZombies |
bool HasPlayerControlledZombies()
|
Returns true if the current mode supports player controlled zombies. |
IsMissionFinalMap |
bool IsMissionFinalMap()
|
True if the current map is the final map of the campaign. Independent of trigger_finale existence. |
IsDedicatedServer |
bool IsDedicatedServer()
|
Returns true if this is a dedicated server. |
IsModelPrecached |
bool IsModelPrecached(string modelname)
|
Checks if the modelname is precached. |
IsSoundPrecached |
bool IsSoundPrecached(string soundname)
|
Checks if the soundname is precached. |
IsWeakref |
bool IsWeakref(table, key)
|
Returns true/false based on whether table[key] is a weak reference |
LocalTime |
void LocalTime(table)
|
Fills out a table with the local time (second, minute, hour, day, month, year, dayofweek, dayofyear, daylightsavings). |
MakeNamespace |
||
PrecacheModel |
int PrecacheModel(string filename)
|
Precache a model and return index of the model. |
PrecacheSound |
void PrecacheSound(string soundName)
|
Precache a sound. |
QueueSpeak |
void QueueSpeak(handle entity, string concept, float delay, string criteria)
|
Queue a speech concept. |
RandomFloat |
float RandomFloat(float min, float max)
|
Generate a random floating-point number within a range, inclusive. |
RandomInt |
int RandomInt(int min, int max)
|
Generate a random integer within a range, inclusive. |
ReapplyInfectedFlags |
ReapplyInfectedFlags(int flags, handle infected)
|
Apply Infected Flags from DirectorOptions . Applies to all common (spawned and unspawned) unless a handle to a specific infected is specified.
|
RegisterFunctionDocumentation |
void RegisterFunctionDocumentation(unknown func, string name, string signature, string description)
|
|
RegisterScriptGameEventListener |
void RegisterScriptGameEventListener(string eventName)
|
Register as a listener for a game event from script. It's what __CollectGameEventCallbacks() uses to register event callbacks to the C++ code.
|
ReloadMOTD |
void ReloadMOTD()
|
Reloads the MotD file. |
RestoreTable |
void RestoreTable(string identifier, table)
|
Restores table data and deletes it. See L4D2_EMS/Appendix:_Table_Save_Restore. |
RetrieveNativeSignature |
unknown RetrieveNativeSignature(string nativeFunction)
|
|
rr_AddDecisionRule |
bool rr_AddDecisionRule(RRule rule)
|
Add a rule to the decision database. Takes a RRule object from rulescript_base.nut. |
rr_CommitAIResponse |
bool rr_CommitAIResponse(handle entity, table airesponse)
|
Supposed to commit the result of QueryBestResponse back to the given entity to play. Takes a table needing the keys response with a ResponseSingle object (defined in response_testbed.nut) and orig_query with an unknown content. |
rr_GetResponseTargets |
table rr_GetResponseTargets()
|
Retrieve a table of all available expresser targets, in the form { name : handle, name: handle }. |
rr_QueryBestResponse |
unknown rr_QueryBestResponse(handle entity, table query)
|
Tests query against entity's response system and returns the best response found (or null if none found). Returns a pointer with a null type, that is apparently not usable anywhere. Possibly supposed to return a AI_Response object. |
RushVictim |
void RushVictim(handle hVictim, float range)
|
Make all common zombies in range rush the victim. (If hVictim isn't set, a random survivor will be chosen.) |
SaveTable |
void SaveTable(string identifier, table)
|
See L4D2_EMS/Appendix:_Table_Save_Restore. |
ScreenFade |
void ScreenFade(handle player, int red, int green, int blue, int alpha, float fadeTime, float fadeHold, int flags)
|
Start a screenfade with the following parameters. |
ScreenShake |
void ScreenShake(Vector vecCenter, float flAmplitude, float flFrequency, float flDuration, float flRadius, int eCommand, bool bAirShake)
|
Start a screenshake with the following parameters. |
SetScavengeItemsGoal |
void SetScavengeItemsGoal(int count)
|
Set the number of Scavenge items needed. |
SetScavengeItemsRemaining |
void SetScavengeItemsRemaining(int count)
|
Set the number of Scavenge items remaining. |
StageInfo_Execute |
void StageInfo_Execute(stageInfo, stageDefaults)
|
Execute a stage table, i.e. move parameters to DirectorOptions, do callbacks and so on. |
StartAssault |
void StartAssault()
|
Tells all existing nextbots to swap into assault mode and not hide/dither/loiter. |
StringToFile |
void StringToFile(string path, string string)
|
Stores the string into the file located at left4dead2/ems/path. Path can contain folders -- in that case folders will be automatically created. Also path supports special names "." and "..", which indicate "current folder" and "parent folder" respectfully.
Things to consider:
|
Time |
float Time()
|
Get the current server time. |
TraceLine |
bool TraceLine(table traceTable)
|
Uses a configuration table to do a raytrace, puts return information into the table for return usage. |
UniqueString |
string UniqueString(string input="")
|
Generate a string guaranteed to be unique across the life of the script VM, with an optional root string. Input will be converted to a string by calling tostring() member function of that input, before passing it to DoUniqueString function. Useful for adding data to tables when not sure what keys are already in use in that table. Throws error on null value.
|
VSquirrel_OnCreateScope |
table VSquirrel_OnCreateScope(value, table scope)
|
Creates a new scope with the name of value in the submitted table (includes unique params). |
VSquirrel_OnReleaseScope |
void VSquirrel_OnReleaseScope(table createdScope)
|
Removes a scope created via VSquirrel_OnCreateScope. |
__CollectGameEventCallbacks |
void __CollectGameEventCallbacks(scope)
|
Wrapper that registers callbacks for both OnGameEvent_x ↑ and OnScriptEvent_ functions. Done using the __CollectEventCallbacks function.
|
__CollectEventCallbacks |
void __CollectEventCallbacks(scope, prefix, globalTableName, regFunc)
|
Overloaded function, used by the above one like this: __CollectEventCallbacks(scope, "OnGameEvent_", "GameEventCallbacks", ::RegisterScriptGameEventListener)
|
__ExecutePreSpawn |
||
__FinishSpawn |
||
__ReplaceClosures |
void __ReplaceClosures(script, scope)
|
|
__RunEventCallbacks |
void __RunEventCallbacks(event, params, prefix, globalTableName, bWarnIfMissing)
|
Call all functions in the callback array for the given game event. |
__RunGameEventCallbacks |
void __RunGameEventCallbacks(event, params
|
Wrapper for __RunEventCallbacks()
|
Squirrel Standard Library
List of functions that come from Squirrel's built-in functions and standard library. Not all functions from the linked documentations are present in VScript, such as the blob
library.
Function | Signature | Description | |
---|---|---|---|
array |
array(int size, any fill = null)
|
Create and returns array of a specified size where each element is set to fill .
| |
assert |
assert(bool exp)
|
Throws an exception if exp is evaluated to false. | |
callee |
function callee()
|
Returns the currently running closure. | |
collectgarbage |
int collectgarbage()
|
Runs the garbage collector and returns the number of reference cycles found(and deleted) This function only works on garbage collector builds. | |
compilestring |
function compilestring(string string, string buffername = null)
|
Compiles a string containing a squirrel script into a function and returns it. | |
enabledebuginfo |
void enabledebuginfo(any enable)
|
Enable/disable the debug line information generation at compile time. enable != null enables . enable == null disables. | |
error |
void error(string x)
|
Prints x in the standard error output. | |
getconsttable |
table getconsttable()
|
Returns the const table of the VM. | |
getroottable |
table getroottable()
|
Returns the root table of the VM. | |
getstackinfos |
table getstackinfos(int stacklevel)
|
Returns the stack frame informations at the given stack level (0 is the current function 1 is the caller and so on). If the stack level doesn't exist the function returns null.
| |
newthread |
coroutine newthread(function threadfunc)
|
Creates a new cooperative thread object(coroutine) and returns it | |
print |
void print(string message)
|
Prints message to console without any line feed after. | |
resurrectunreachable |
array resurrectunreachable()
|
Runs the garbage collector and returns an array containing all unreachable object found. If no unreachable object is found, null is returned instead. This function is meant to help debugging reference cycles. This function only works on garbage collector builds. | |
setconsttable |
table setconsttable(table consttable)
|
Sets the const table of the VM which also returns the previous const table. | |
seterrorhandler |
void seterrorhandler(function func)
|
Sets the runtime error handler . | |
setroottable |
table setroottable(table roottable)
|
Sets the root table of the VM which also returns the previous root table. | |
suspend |
void suspend(any ret)
|
Suspends the coroutine that called this function. | |
type |
string type(any obj)
|
Return the 'raw' type of an object without invoking the metatmethod '_typeof'. |
Math
The built-in Squirrel math library.
Function | Signature | Description |
---|---|---|
abs |
int abs(float x)
|
Returns the absolute value of x as an integer.
|
acos |
float acos(float x)
|
Returns the arccosine of x .
|
asin |
float asin(float x)
|
Returns the arcsine of x .
|
atan |
float atan(float x)
|
Returns the arctangent of x .
|
atan2 |
float atan2(float x, float y)
|
Returns the arctangent of x/y .
|
ceil |
float ceil(float x)
|
Returns a float value representing the smallest integer that is greater than or equal to x .
|
cos |
float cos(float x)
|
Returns the cosine of x .
|
exp |
float exp(float x)
|
Returns the exponential value (e^x ) of the float parameter x .
|
fabs |
float fabs(float x)
|
Returns the absolute value of x as a float.
|
floor |
float floor(float x)
|
Returns a float value representing the largest integer that is less than or equal to x .
|
log |
float log(float x)
|
Returns the natural logarithm of x .
|
log10 |
float log10(float x)
|
Returns the logarithm base-10 of x .
|
pow |
float pow(float x, float y)
|
Returns x raised to the power of y .
|
rand |
int rand()
|
Returns a pseudorandom integer in the range 0 to RAND_MAX .
|
sin |
float sin(float x)
|
Returns the sine of x .
|
sqrt |
float sqrt(float x)
|
Returns the square root of x .
|
srand |
void srand(float seed)
|
Sets the starting point for generating a series of pseudorandom integers. |
tan |
float tan(float x)
|
Returns the tangent of x .
|
Strings
The built-in Squirrel string library.
Function | Signature | Description |
---|---|---|
format |
string format(string format, args...)
|
Returns a formatted string. Same rules as the standard C functions (except * is not supported). |
lstrip |
string lstrip(string str)
|
Removes whitespace characters at the beginning of the given string. |
rstrip |
string rstrip(string str)
|
Removes whitespace characters at the end of the given string. |
split |
array split(string str, string separator)
|
Returns an array of strings split at each point where a separator character occurs in str. The separator is not returned as part of any array element. the parameter separators is a string that specifies the characters as to be used for the splitting. |
strip |
string strip(string str)
|
Removes whitespace characters at both the beginning and end of the given string. |
Script Debug
toc ↑ Functions for interacting with the debugger. Some of them are documented here.
Function | Signature | Description |
---|---|---|
BeginScriptDebug |
void BeginScriptDebug()
|
|
EndScriptDebug |
void EndScriptDebug()
|
|
ScriptDebugAddTextFilter |
void ScriptDebugAddTextFilter()
|
|
ScriptDebugAddTrace |
void ScriptDebugAddTrace()
|
|
ScriptDebugAddWatch |
void ScriptDebugAddWatch()
|
|
ScriptDebugAddWatches |
void ScriptDebugAddWatches()
|
|
ScriptDebugAddWatchPattern |
void ScriptDebugAddWatchPattern()
|
|
ScriptDebugClearTraces |
void ScriptDebugClearTraces()
|
|
ScriptDebugClearWatches |
void ScriptDebugClearWatches()
|
|
ScriptDebugDefaultWatchColor |
void ScriptDebugDefaultWatchColor()
|
|
ScriptDebugDraw |
void ScriptDebugDraw()
|
|
ScriptDebugDrawWatches |
void ScriptDebugDrawWatches()
|
|
ScriptDebugDumpKeys |
void ScriptDebugDumpKeys()
|
|
ScriptDebugHook |
void ScriptDebugHook()
|
|
ScriptDebugIterateKeys |
void ScriptDebugIterateKeys()
|
|
ScriptDebugIterateKeysRecursive |
void ScriptDebugIterateKeysRecursive()
|
|
ScriptDebugRemoveTextFilter |
void ScriptDebugRemoveTextFilter()
|
|
ScriptDebugRemoveTrace |
void ScriptDebugRemoveTrace()
|
|
ScriptDebugRemoveWatch |
void ScriptDebugRemoveWatch()
|
|
ScriptDebugRemoveWatches |
void ScriptDebugRemoveWatches()
|
|
ScriptDebugRemoveWatchPattern |
void ScriptDebugRemoveWatchPattern()
|
|
ScriptDebugText |
void ScriptDebugText()
|
|
ScriptDebugTextDraw |
void ScriptDebugTextDraw()
|
|
ScriptDebugTextPrint |
void ScriptDebugTextPrint()
|
|
ScriptDebugTextTrace |
void ScriptDebugTextTrace()
|
|
ScriptDebugTraceAll |
void ScriptDebugTraceAll()
|
|
ScriptDebugWatches |
void ScriptDebugWatches()
|
|
__VScriptServerDebugHook |
__VScriptServerDebugHook()
|