Left 4 Dead 2/Scripting/Script Functions

From Valve Developer Community
< Left 4 Dead 2‎ | Scripting
Revision as of 14:45, 19 April 2014 by Rectus (talk | contribs) (Added rest of the stuff documented in script_help (hopefully))
Jump to navigation Jump to search

Squirrel This list contains engine-related Squirrel variables, functions, and constants available for Left 4 Dead 2 Left 4 Dead 2 VScripts. Some can be printed in-game with the scipt_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.

Variables

Instance 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.
DirectorScript table Script scope for Director scripts. Contains the active DirectorOptions table.
Documentation table Contains the printed strings from the script_help command.
Entities CEntities Provides access to currently spawned entities.
g_ClearoutTable table (null)
g_MapScript table Script scope for map specific vscripts. It also contains a lot of utility functions.
g_ModeScript table Script scope for mode specific vscripts. Only fully available in Scripted Mode.
g_RoundState table
g_rr table
NavMesh CNavMesh Provides a method to unblock the rescue vehicle.
print_indent
_PublishedHelp table
ScriptDebugTraceAllOn bool
ScriptDebugTraces table
ScriptDebugText array
ScriptDebugTextFilters table
ScriptDebugTextIndent bool
ScriptDebugWatches array
ScriptEventCallbacks table


Constants

Instance Type Description
_charsize_ integer
_floatsize_ integer
_intsize_ integer
_version_ string The version of squirrel.
_versionnumber_ integer The version of squirrel as an integer.
RAND_MAX integer
SPAWN_FLAGS table

Classes

CBaseAnimating

Extends CBaseEntity

CBaseEntity

This is a script handle for a game entity. All entities in-game are accessible from Entities.

Base Methods

Function Signature Description
__KeyValueFromInt void __KeyValueFromInt(string key,int value) Sets a keyvalue from an integer, the keys available for all __KeyValue are from the DEFINE_KEYFIELD in baseentity.cpp (classname,rendermode, renderfx, etc.).
__KeyValueFromString void __KeyValueFromString(string key,string value) Sets a keyvalue from a string, the keys available for all __KeyValue are from the DEFINE_KEYFIELD in baseentity.cpp (classname,rendermode, renderfx, etc.).
__KeyValueFromVector void __KeyValueFromVector(string key,Vector value) Sets a keyvalue from a vector, the keys available for all __KeyValue are from the DEFINE_KEYFIELD in baseentity.cpp (classname,rendermode, renderfx, etc.).
ApplyAbsVelocityImpulse void ApplyAbsVelocityImpulse(Vector impulse) Apply a Velocity Impulse.
ApplyLocalAngularVelocityImpulse void ApplyLocalAngularVelocityImpulse(Vector impulse) Apply an Ang Velocity 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 event) Removes a connected script function from an I/O event.
FirstMoveChild handle FirstMoveChild()
GetAngles handle QAngle GetAngles() Returns the orientation of the entity in the world.
GetBaseVelocity Vector GetBaseVelocity() Get Base? velocity
GetClassname string GetClassname() Returns the entity class. This includes player and infected.
GetContext unknown GetContext(string) GetContext( name ): looks up a context and returns it if available. May return string, float, or null (if the context isn't found)
GetEntityHandle unknown GetEntityHandle() Get the entity as an EHANDLE.
Todo: What is this?
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()
GetLocalAngularVelocity QAngle GetLocalAngularVelocity() Maybe local angvel
GetLocalVelocity Vector GetLocalVelocity() Get Entity relative velocity
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() Retrieve the unique identifier used to refer to the entity within the scripting system.
GetScriptScope handle GetScriptScope() Retrieve the script-side data associated with an entity.
GetVelocity Vector GetVelocity()
IsPlayer bool IsPlayer() Does this entity belong to the player class.
IsValid bool IsValid() Whether the handle belongs to a valid entity.
Kill void Kill()
NextMovePeer handle NextMovePeer()
OverrideFriction void OverrideFriction(float duration, float friction) Takes duration, value for a temporary override
PrecacheModel void PrecacheModel(string filename)
PrecacheScriptSound void PrecacheScriptSound(string)
Todo: Is this for raw files or soundscripts?
SetAngles void SetAngles(QAngle direction)
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 0 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 0 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)
SetOrigin void SetOrigin(Vector position)
SetVelocity void SetVelocity(Vector velocity) Sets the entity velocity.
ValidateScriptScope bool ValidateScriptScope() Ensure that an entity's script scope has been created.

Functions

Function Signature Description
OnPostSpawn void OnPostSpawn() If you declare a function OnPostSpawn() in your vscript, when the entity that is using the script is spawned, it will run this function automatically. You could use this to have an entity register itself with a master script or just do whatever needed to be down immediately after spawn.

CTerrorPlayer

Extends CBaseEntity

Class for player entities. Both survivors and special infected belong to this.

Methods

Function Signature Description
Extinguish void Extinguish() Extinguish a burning player.
EyePosition Vector? EyePosition() Try and get the current eye position.
GetActiveWeapon handle GetActiveWeapon() Get the player's active weapon entity.
GetButtonMask int GetButtonMask() Returns a bitfield of currently pressed buttons. Recognized buttons are: IN_ATTACK, IN_ATTACK2, IN_JUMP, IN_DUCK, IN_FORWARD, IN_BACK, IN_USE, IN_MOVELEFT, IN_MOVERIGHT, IN_RELOAD
GetHealthBuffer int GetHealthBuffer() Returns the current temporary health of a survivor.
Todo: Does temp health work on SI?
GetPlayerName string GetPlayerName Get the players name.
GetPlayerUserId int GetPlayerUserId() Get the players userID.
GetPreTemplateName [Todo]
GetSenseFlags int GetSenseFlags() Get the current bits for the bot sense flags: BOT_CANT_SEE, BOT_CANT_HEAR, BOT_CANT_FEEL
GetSurvivorSlot int GetSurvivorSlot() Get the player's slot.
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 currently equipped weapon. Double the value set in amount is added.
GiveItem void GiveItem(string itemname) Give an item/weapon by name. (health, katana, rifle_ak47, etc.)
GiveUpgrade void GiveUpgrade(string upgrade) give a primary weapon upgrade: UPGRADE_INCENDIARY_AMMO, UPGRADE_EXPLOSIVE_AMMO, UPGRADE_LASER_SIGHT
HitWithVomit void HitWithVomit() Target a player with a boomer vomit attack.
IsDead bool IsDead() Returns a bool indicating dead state.
IsDying bool IsDying() Returns a bool indicating dying state.
IsIncapacitated bool IsIncapacitated() Returns a bool indicating incapacitated state.
IsHangingFromLedge bool IsHangingFromLedge() Returns a bool indicating ledge hang state.
IsGhost bool IsGhost() Returns a bool indicating ghost infected state.
IsOnFire bool IsOnFire() Returns a bool indicating if a player is on fire.
IsSurvivor bool IsSurvivor() On the survivor team (Otherwise, infected).
RemoveUpgrade void RemoveUpgrade(string upgrade) Remove a primary weapon upgrade: UPGRADE_INCENDIARY_AMMO, UPGRADE_EXPLOSIVE_AMMO, 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. 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 and effects.
SetSenseFlags void SetSenseFlags(int flags) Set the current bits for the bot sense flags: BOT_CANT_SEE, BOT_CANT_HEAR, BOT_CANT_FEEL
Stagger void Stagger(Vector position) Stagger a player away from a position. Use Vector(0,0,0) to just stagger forward.
TryGetPathableLocationWithin Vector TryGetPathableLocationWithin(int radius) Get a location on the nav the player can path to within the desired radius.
UseAdrenaline void UseAdrenaline(int duration) Causes Adrenaline's speed and visual effect, no change to health.


CCallChainer

Methods

Function Signature Description
constructor [Todo] constructor()
PostScriptExecute [Todo] PostScriptExecute()
Call [Todo] Call()

Members

Instance Type Description
chains null
prefix null
scope null

CDirector

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
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.
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.
GetHoldoutCooldownEndTime [Todo] float? GetHoldoutCooldownEndTime() Get the end time of the cooldown timer.
GetPendingMobCount int GetPendingMobCount() Returns the number of infected waiting to spawn.
HasAnySurvivorLeftSafeArea bool HasAnySurvivorLeftSafeArea() True when one or more survivors have left the starting safe area.
IsAnySurvivorInCombat bool IsAnySurvivorInCombat() Returns true if any survivor recently dealt or took damage.
IsPlayingOnConsole bool IsPlayingOnConsole() Return true if game is running on a console (such as Xbox 360).
IsSinglePlayerGame bool IsSinglePlayerGame() Return true if game is in single player.
IsValid bool IsValid() Whether the handle belongs to a valid entity.
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.
ResetMobTimer void ResetMobTimer() Trigger a mob as soon as possible when in BUILD_UP.
ResetSpecialTimer void ResetSpecialTimer() Reset all special timers (by type and by slot) so that hopefully mobs will spawn asap.
SetHoldoutCooldownEndTime void SetHoldoutCooldownEndTime(float time? [Todo])
UserDefinedEvent1 void UserDefinedEvent1() These trigger the appropriate output from the info_director entity when called.
UserDefinedEvent2 void UserDefinedEvent2()
UserDefinedEvent3 void UserDefinedEvent3()
UserDefinedEvent4 void UserDefinedEvent4()

CEntities

Game Instance: Entities

An interface to find and iterate over the entities in play.

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

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.
FindByModel handle FindByModel(handle previous, string filename) Find entities by model name.
FindByName handle FindByName(handle previous, string name) Find entities by name.
FindByNameNearest handle FindByNameNearest(string name, Vector origin, float radius) Find entities by name nearest to a point.
FindByNameWithin handle FindByNameWithin(handle previous, string name, Vector origin, float radius) Find entities by name within a radius.
FindByTarget handle FindByTarget(handle previous, string targetname) Find entities by its target.
FindInSphere handle FindInSphere(handle previous, Vector origin, float radius) Find entities within a radius.
First handle First() Begin an iteration over the list of entities.
Next handle Next(handle previous) Continue an iteration over the list of entities, providing reference to a previously found entity.
IsValid bool IsValid() Whether the handle belongs to a valid entity.


CEnvEntityMaker

Methods

Function Signature Description
SpawnEntity void SpawnEntity() Create an entity at the location of the maker.
SpawnEntityAtEntityOrigin void SpawnEntityAtEntityOrigin(handle 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.


CNavMesh

Game Instance: NavMesh

Methods

Function Signature Description
IsValid bool IsValid() Whether the handle belongs to a valid entity.
Todo: Does the nav mesh have an entity?
UnblockRescueVehicleNav void UnblockRescueVehicleNav() Unblock the rescue vehicle nav areas so bots can path through them.


Convars

Game Instance: Convars

Provides an interface for getting and setting convars on the server.

Todo: The class for this doesn't seem to be directly available.

Methods

Function Signature Description
GetClientConvarValue string GetClientConvarValue(string name)
Todo: Likely needs another argument.
Returns the convar value for the entindex as a string.
GetStr string GetStr(string name) Returns the convar as a string. May return null if no such convar.
GetFloat float GetStr(string name) Returns the convar as a float. May return 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

Note.pngNote:These functions apparently work with point_template. In other words, designate a vscript in the entity KeyValues and include the function in the script.
  • function PostSpawn( entities )
Called after the entity was spawned, you could use this to connect outputs or do whatever needs to be done after the entity was created.
function PostSpawn( entities )
{
	foreach( k, v in entities ) //name, ent ref
	{
		printl( k + ": " + v );
	}
}
  • function PreSpawnInstance(entityClass, entityName)
If this is defined, it will be called right before the entity is created, any key,values returned will be assigned to the entity.
function PreSpawnInstance( entityClass, entityName )
{
return { 
   rendercolor = "0 255 0"
   targetname = "blah"
};	
}
You could use this to dynamically assign target names, colors, even models. Unfortunately, models don't work like you would think. Yes, you can change that gas tank into a football model, will even keep the weapon_gascan class, but it won't behave like one. Also tested this out on zombie spawners, but unfortunately, they don't use these hooks which is a shame, because how cool would it have been to have 3 tank models in play at once?

CSimpleCallChainer

Seems to have the same members as CCallChainer.


CPointScriptUseTarget

Extends CBaseEntity

Class for the point_script_use_target entity. The real name of the class is unknown.

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.

Decider

Todo:  Seems to be related to response rules

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 handle belongs to a valid entity(?).


regexp

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

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)

QAngle

Squirrel equivalent of the C++ QAngle class.

Represents a three dimensional orientation.


Methods

Function Signature Description
constructor QAngle(float pitch, float yaw, float roll) Creates a new QAngle.
Forward Vector Forward() Returns the Forward Vector of the angles.
Left Vector Left() Returns the left Vector of the angles.
Pitch float Pitch() Returns the pitch angle in degrees.
Roll float Roll() Returns the roll angle in degrees.
ToKVString string ToKVString()
Up Vector Up() Returns the Up Vector of the angles.
Yaw float Yaw() Returns the yaw angle in degrees.


Quaternion

Quarternions[1] are used in 3 dimensional rotations.

Methods

Function Signature Description
constructor Quarternion([Todo]) Creates a new Quarternion.
Dot float? Dot(Quarternion factor) The scalar product of two quaternions(?).
Invert Quarternion? Invert()
Norm Quarternion? Norm()
SetPitchYawRoll void SetPitchYawRoll(?)
ToKVString string ToKVString()
ToQAngle QAngle ToQAngle()

Vector

Squirrel equivalent of the C++ Vector class.

Three dimensional vector.

Has overloaded arithmetic operations with both Vectors and scalar values.

Note.pngNote:Example declaration and manipulation of Vector

Methods

Function Signature Description
constructor Vector(float x, float y, float z) 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.
Length2D float Length2D()
Length2DSqr float Length2DSqr()
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.
tostring string tostring() Returns a human readable string.

Vector2D, Vector4D

Methods

Function Signature Description
constructor VectorXD(float x, float y,...) Creates a new vector with the specified Cartesian coordiantes.
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.
Norm float Norm() Seems to also return the vector length.
ToKVString string ToKVString() Returns a string without separations commas.

Other functions

sm_utilities.nut

Available in the g_ModeScript scope, always loaded in.

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.

Function Signature Description
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.


Scripted Mode specific

These hook functions are only available in Scripted Mode, which is enabled for a game mode by adding a mode specific VScript (<mode name>.nut).

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): If you place a function with this name in your script, C++ will 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              // handle of the entity that attacked
	Victim = null                // handle of the entity that was hit
	DamageDone = 0               // how much damage done
	DamageType = -1              // of what type
	Location = Vector(0,0,0)     // where
	Weapon = null                // by what - often Null (say if attacker was a common)
}

If you return "false" 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 field read back by the C++ is DamageDone, so if you want you can use it to change the damage value before it is applied. 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 ).

CanPickupObject

bool CanPickupObject(handle object): Hook function that lets you decide whether a given object should be pickupable.


InterceptChat

void InterceptChat(sting str, handle srcEnt): 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.


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

See L4D2_EMS/Appendix:_Game_Events.


Engine specific

Function Signature Description
AddThinkToEnt void AddThinkToEnt(handle entity,function FuncName) This will put a think function onto an entity, or pass null to remove it. This is NOT chained, so be careful.
AddToScriptHelp
Assert void Assert(bool value, string optional message) Test value and if not true, throws exception, optionally with message.
CheckForSpecialStage void CheckForSpecialStage(level, stage_list, stage_info) Helper for picking a random special stage based on stage_info table.
CheckOrSetMapCallback void CheckOrSetMapCallback(cb_name, cb_default) Pass a callback and default @ for it, if it doesnt exist in current table, place it there.
ClearGameEventCallbacks void ClearGameEventCallbacks() Empties the tables of game event callback functions.
ClearSavedTables void ClearSavedTables() Removes any tables saved with SaveTable().
ConnectOutputs void ConnectOutputs(table) sets output functions for entity by table [Todo]
DebugDrawBox void DebugDrawBox([Todo] Vector, Vector, Vector, int, int, int, int, float) Draw a debug overlay box.
DebugDrawBoxDirection Draw a debug forward box (cent, min, max, forward, vRgb, a, duration).
DebugDrawCircle Draw a debug circle (center, rad, vRgb, a, ztest, duration)
DebugDrawClear Try to clear all the debug overlay info.
DebugDrawLine void DebugDrawLine(Vector start, Vector end, int red, int green, int blue', bool [Todo], float time) Draw a debug overlay line.
DebugDrawLine_vCol Draw a debug line using color vec (start, end, vRgb, a, ztest, duration)
DebugDrawScreenTextLine Draw text with a line offset.
DebugDrawText Draw text in 3d (origin, text, bViewCheck, duration)
developer bool developer() If developer mode is on.
Document
DoIncludeScript void DoIncludeScript(string file, handle scope) Execute a script (internal)
DoEntFire void DoEntFire(string target, string action, string value, float delay, string activator, string caller) Generate an entity I/O event.
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.
EntFire void EntFire(string target, string action, string value, float delay, string activator) Wrapper for DoEntFire() that sets activator and caller to null.
DoUniqueString string DoUniqueString(string input) Called by UniqueString, prob want to call that instead.
DumpObject void DumpObject(handle object) Dumps information about a class or instance.
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.
StopSoundOn void StopSoundOn(string soundScript, handle entity) Stop named sound on an entity.
EyeAngles QAngle EyeAngles(handle target) Returns a QAngle of where the target is looking.
FileToString string FileToString(string file) Reads a string from file. Returns the string from the file, null if no file or file is too big.
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()
GetCharacterDisplayName Return null if not a survivor, else the survivors 'real name'
GetCurrentFlowDistanceForPlayer float GetCurrentFlowDistanceForPlayer(handle player) Returns the navigation flow distance from the start to the specified player.
GetCurrentFlowPercentForPlayer float GetCurrentFlowPercentForPlayer(handle player) Returns how far in the navigation flow from the start to the end the player is.
GetCurrentFlowDistanceForPosition float GetCurrentFlowDistanceForPosition(Vector position) Returns the navigation flow distance from the start to the specified point.
GetCurrentFlowPercentForPosition float GetCurrentFlowPercentForPosition(Vector position) 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.
GetFrameCount void GetFrameCount() Returns the engine's current frame count.
GetFriction float GetFriction(handle player) Returns the Friction on a player entity, meaningless if not a player.
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.
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 ?) Given a character type, return the entity, or null.
GetPlayerFromUserID handle GetPlayerFromUserID(int ID) Given a user id, return the entity, or null.
HUDManageTimers void HUDManageTimers(int, int, float) See L4D2_EMS/Appendix:_HUD
HUDPlace void HUDPlace(int, float, float, float, float) See L4D2_EMS/Appendix:_HUD
HUDReadTimer float HUDReadTimer(int timer) See L4D2_EMS/Appendix:_HUD
HUDSetLayout void HUDSetLayout(handle) See L4D2_EMS/Appendix:_HUD
IncludeScript void IncludeScript(string file, handle scope = null) Wrapper for DoIncludeScript
IsPlayerABot void IsPlayerABot(handle player) Is this player/entity a bot.
IsWeakref
MakeNamespace
Msg void Msg(string message) Prints message to console without any line feed after.
OnEntText void OnEntText() if ent_text is used on an entity and the function OnEntText() 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.
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 Get a script instance of a player by index.
PrecacheEntityFromTable
printl void printl(string message) Prints message to console with a line feed after.
RandomFloat float RandomFloat() Generate a random floating point number.
RandomFloat float RandomFloat(float min, float max) Generate a random floating point number within a range, inclusive.
RandomInt int RandomInt() Generate a random integer.
RandomInt int RandomInt(int min, int max) Generate a random integer within a range, inclusive.
realPrint
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
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) See L4D2_EMS/Appendix:_Table_Save_Restore.
RetrieveNativeSignature
RotateOrientation Rotate a QAngle by another QAngle.
RotatePosition Rotate a Vector around a point.
rr_AddDecisionRule bool rr_AddDecisionRule(handle rule) Add a rule to the decision database.
rr_CommitAIResponse bool rr_CommitAIResponse(handle entity, handle airesponse) Commit the result of QueryBestResponse back to the given entity to play.
rr_GetResponseTargets table rr_GetResponseTargets() Retrieve a table of all available expresser targets, in the form { name : handle, name: handle }.
rr_QueryBestResponse handle rr_QueryBestResponse(handle entity, handle query) Tests query against entity's response system and returns the best response found (or null if none found).
SaveTable void SaveTable(string identifier, table) See L4D2_EMS/Appendix:_Table_Save_Restore.
Say void Say(handle 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.
ShowMessage void ShowMessage(string message) Print a HUD message on all clients. Doesn't seem to work.
SpawnEntityFromTable handle SpawnEntityFromTable(string name, handle keyvalues) Native function for entity spawning. See L4D2_EMS/Appendix:_Spawning.
SpawnEntityGroupFromTable bool SpawnEntityGroupFromTable(handle entityGroup) Native function for entity group spawning. See L4D2_EMS/Appendix:_Spawning.
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.
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 file, string string) Stores the string into the file.
Time float Time() Get the current server time.
TimeToDisplayString string TimeToDisplayString(disp_time) Convert a # of seconds to a displayable time string form m:ss
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.
UniqueString string UniqueString(string input) Generate a string guaranteed to be unique across the life of the script VM, with an optional root string. Useful for adding data to tables when not sure what keys are already in use in that table.
VSquirrel_OnCreateScope
VSquirrel_OnReleaseScope
__CollectEventCallbacks void __CollectEventCallbacks(scope) Registers callbacks for OnGameEvent_x functions.
__CollectEventCallbacks void __CollectEventCallbacks( scope, prefix, globalTableName, regFunc ) Overloaded function, used by the above one like this: __CollectEventCallbacks( scope, "OnGameEvent_", "GameEventCallbacks",
RegisterScriptGameEventListener )
__DumpScope void __DumpScope(int indentation,handle scope) Dumps contents of everything in the scope.
__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()


CommandABot

bool CommandABot(table commandTable): Issues commands to bots based on a table configuration.

Inputs:
.cmd - required field, must specify one of these commands: BOT_CMD_ATTACK, BOT_CMD_MOVE, BOT_CMD_RETREAT, BOT_CMD_RESET
NOTE: in order to use the BOT_CMD enums you must be operating in the mode script scope. If you aren't you can pass an integer instead of the enum (e.g., set cmd to 1 instead of BOT_CMD_MOVE)
.pos - a position, used only in BOT_CMD_MOVE
.bot - which bot you are commanding (or NULL for all bots)
.target - for attack and retreat - what entity is the target of the attack or retreat.

Here is an example of how to create a table that commands all bots to run to position 0,0,0:

commands <-
{
	cmd = 1 // BOT_CMD_MOVE
	pos = Vector( 0,0,0 )
}
----
CommandABot( commands )

Alternatively, you could send the data inline, like so:

 CommandABot( { cmd = 1, pos = Vector( 0,0,0 ) } )


GetInvTable

void GetInvTable(handle player,table invTable): Fills invTable with the player's inventory.

The table is structured:

 key: SlotX      value: Entity in slot (0-4, i think? Main Weap/Hand/Thrown/HealthPack/Pills)
 key: Held       value: Entity being carried, otherwise Held will not be in the table


TraceLine

bool TraceLine(table traceTable): uses a configuration table to do a raytrace, puts return information into the table for return usage. Returns a bool indicating that the trace was successful.

Inputs:

   key: start       value: start vector for the trace
   key: end         value: end vector for the trace
   key: ignore      value: entity handle to ignore as part of the trace
   key: mask        value: optional masks: TRACE_MASK_VISIBLE_AND_NPCS (default), TRACE_MASK_ALL, TRACE_MASK_VISION, TRACE_MASK_SHOT, TRACE_MASK_PLAYER_SOLID, TRACE_MASK_NPC_SOLID

Outputs:

   key: hit          value: did we hit something
   key: pos          value: where the traceline ended
   key: fraction     value: where the hit occurred
   key: enthit       value:  handle for entity hit if there is one
   key: startsolid   value: did we start in solid

The only required information to make the trace is providing the start and end point.

Example:

traceTable <-
{
	start = Vector( 0,0,0 )
	end =  Vector( 0,0,256 )
}


ZSpawn

bool ZSpawn(table spawnTable): This is essentially the z_spawn console command, except (a) you pass a table and (b) no raycast, you give it the position vector. The table entries used are:

   key: type       value: ZOMBIE_WITCH, etc - or the special ZSPAWN_MOB, or WITCHBRIDE, etc
   key: pos        value: Vector position at which to spawn
   key: ang        value: QAngle for spawn, optional (defaults to 0,0,0)


Debugging functions

Functions for interacting with the debugger. Some of them are documented here.

  • BeginScriptDebug
  • EndScriptDebug
  • ScriptDebugAddTextFilter
  • ScriptDebugAddTrace
  • ScriptDebugAddWatch
  • ScriptDebugAddWatches
  • ScriptDebugAddWatchPattern
  • ScriptDebugClearTraces
  • ScriptDebugClearWatches
  • ScriptDebugDraw
  • ScriptDebugDrawWatches
  • ScriptDebugDumpKeys
  • ScriptDebugHook
  • ScriptDebugIterateKeys
  • ScriptDebugIterateKeysRecursive
  • ScriptDebugRemoveTextFilter
  • ScriptDebugRemoveTrace
  • ScriptDebugRemoveWatch
  • ScriptDebugRemoveWatches
  • ScriptDebugRemoveWatchPattern
  • ScriptDebugTextDraw
  • ScriptDebugTextPrint
  • ScriptDebugTextTrace
  • ScriptDebugTraceAll
  • __VScriptServerDebugHook

Standard Squirrel library

SquirrelStandard Squirrel library functions (consult official Squirrel language league for more details):

Function
abs
acos
array
asin
assert
atan
atan2
ceil
collectgarbage
compilestring
cos
exp
fabs
floor
format
getconsttable
getroottable
getstackinfos
log
log10
lstrip
pow
print
rand
rstrip
setconsttable
seterrorhandler
setroottable
type
sin
split
sqrt
srand
strip
suspend
tan

See also