# L4D2 Vscripts

Left 4 Dead 2 VScripts are server-side scripts that are run in an in-game virtual machine. They are written in Squirrel, a compiled scripting language similar to Lua.

## Uses

### Director Scripts

The most common use of VScripts in Left 4 Dead 2 is to influence the behavior of the AI Director. These scripts can range from simple adjustments of infected spawning and prohibiting boss infected, to custom events like onslaughts and gauntlets, and even complex staged panic events and fully custom finales. Most of the events in the official campaigns are mainly implemented this way.

Director Scripts work mainly by writing overriding values of the various variables used by the Director into a DirectorOptions table.

Only one Director Script can be running at a time. Executing a new one will terminate any previous running one and remove any values it set in DirectorOptions.

### Entity Scripts

Another common use is to attach a script to an entity. The script provides easy access to read and modify many of the entity's properties, and even to write new KeyValues. This allows for controlling entities in ways that would be very complicated or impossible to with the entity I/O system in Hammer.

Any entity is capable of running a script, and has the ability to set a specified think function to run every 0.1 seconds, as well as executing script code as an entity output.

Some entities also have specialized functions for VScripts, with the most prominent being point_script_use_target, which allows for turning other entities into fully programmable timed buttons.

### Global Scripts

Scripts can also be made to run on map load, based on game mode and optionally map name. These scripts are commonly used to create scripting and modify global Director options for mutations, but can also be used in custom maps.

Global scripts can have script hook functions added that get called from the game at certain events, like when players/objects take damage.

There are many utility functions and features readily available for these scripts, including a resource and building system, and custom panic wave spawning. Please see Valve's Expanded Mutation System tutorial for more information.

### Other uses

All scripts can access functions for many features, including spawning entities either from precompiled lists or programmatically, spawning infected, a HUD system, storing data across levels and to disk, and much more.

Please see L4D2 Vscript Examples for more examples and ideas.

## Script files

The scripts are loaded from text files with the file extensions .nut and .nuc, where .nuc denotes encryption of plain text .nut. Custom scripts are read from \left 4 dead 2\left4dead2\scripts\vscripts\, as well as \scripts\vscripts\ when packed into a .vpk file.

### Location

Official .nuc script files are located in scripts/vscripts in multiple locations
Note:Browse and extract VPK files with third-party programs like GCFScape.
April 22, 2010 The Passing update
October 5, 2010 The Sacrifice update
March 22, 2011 Cold Stream Beta / L4D1 Transition Project update
This is where mutations were updated/replaced bi-weekly.
Plaintext versions of many of the scripts introduced in the EMS update.

### Decrypting NUC files

.nuc files are ICE encrypted .nut files. The encryption key is SDhfi878. You can use VICE to decode them.

VScripts are loaded in different ways depending on what they are used for. They can alos be manually loaded with the console command script filename

### Director Scripts

Using the info_director entity using the following inputs
BeginScript <script name>
Executes a generic Director script, for example for onslaught events or changing spawning behavior.
EndScript
Ends the running script and resets the Director options to the map specific values.
BeginScriptedPanicEvent <script name>
Begins a Scripted Panic event.
Note:Scripts used with BeginScriptedPanicEvent will not work if they are in a subdirectory, even though you can use subdirectories in other script contexts. They must reside under the vscripts folder, or they will simply act as a 1 stage 1 second delay.
Finale scripts
The <map name>_finale.nut script is atumatically loaded when a finale map starts. The script is triggered when the trigger_finale is used, either manually by the player, or with the ForceFinaleStart input.
To do: trigger_finale also has an option to specify a finale script, but it doesn't seem to work

All Director Scripts are placed in the script scope DirectorScript

### Entity Scripts

Uses the script set in the Entity Scripts KeyValue of the entity.
Using the RunScriptFile input.

Entity Scripts are placed in the script scope _<unique ID>_<entity name>

### Global Scripts

Mode Specific Scripts
Will automatically run the script with the same name as the game mode. For example, running a map map <map name> mutation12 will automatically load the Realism Versus script, mutation12.nuc.
They are placed in the script scope g_ModeScript
Note:Adding a script for a mode will enable Scripted Mode on it.
Map Specific Scripts (only available in Scripted Mode)
Per-map scripts can be created that run when the map is loaded in the specified game mode, using the syntax <map name>_<mode name>.nut, for example, c1m4_atrium_mutation12.nut.
They are placed in the script scope g_MapScript

## Scripting environment

Please see List of L4D2 Script Functions for built in classes and functions.

To do: Add better description of the script scopes.

### Table structure

DirectorScript = 			//Director scripts get loaded here.
{
DirectorOptions 		//Active when a director script is, and during scripted events and finales(?).
MapScript =  			//Reference to g_MapScript. Contains initial values.
{
BaseScriptedDOTable 	//Hardcoded DirectorOptions.
ChallengeScript = 	//Reference to g_ModeScript. Contains initial values.
{
MutationState 	//Populated with the the mode and map names.
}
LocalScript =
{
DirectorOptions //Current DirectorOptions(?).
}
}
}
g_MapScript = 				//Map specific scripts get loaded here.
{
MapOptions 			//Initial values for SessionOptions.
MapState 			//Initial values for SessionState.
}
g_ModeScript = 				//Mode specific scripts get loaded here (Scripted mode only).
{
DirectorOptions 		//Current Director options, outside scripted events.
MutationState 			//Initial values for SessionState.
MutationOptions 		//Initial values for SessionOptions.
}
g_rr
g_RoundState
SessionOptions 				//Global Director options (Scripted mode only).
SessionState  				//State variables for game modes (Scripted mode only).

### Delegation

Some of the tables have delegation set up, so that if a key isn't present in it, any operation done to done to the value, including creating the slot, is done to its parent-table instead.

DirectorOptions
DirectorScript.DirectorOptions < g_MapScript.DirectorOptions < g_MapScript.LocalScript.DirectorOptions < g_ModeScript.DirectorOptions

## Entity Scripts

Use script scope _<unique ID>_<entity name>

Adding a script to the Entity Scripts KeyValue of a server-side entity loads the script as an Entity Script. The script is executed when the entity spawns, and loads into a unique script scope made up of an unique identifier followed by the entity name or class name.

A think function can be set with the thinkfunction KeyValue, the specified script function every 0.1 seconds. While it has the potential to become expensive, a programmer is able to limit the amount of code executed. Functions can also be manually called through the I/O system with the input RunScriptCode function_name(argument, ...).

Entity Scripts have a self reference to their owning entity handle, allowing the script easy access to control the entity through its class methods. There are also hook functions available depending on the entity class. Both methods and hooks are documented here.

Some entities have additional script functionality:

The script can be reloaded with console command ent_fire <name of entity> runscriptfile <relative vscript path>. This is useful for quick script reloading.

### I/O system interaction

Any script can use the EntFire() and DoEntFire() functions to fire outputs to map entities. Since the activator and caller arguments in DoEntFire() take a script handle, it can be used to fire an output to an entity using the "!self" or "!activator" keyword, even without having to know its name, as long as the entity handle is available.

EntFire( "church_bell_relay", "Trigger", 0 ); // Fires an output to the Trigger input of the named entity.

player <- null;
while(player = Entities.FindByClassname(player, "player"))   // Iterate through the script handles of the players.
{
DoEntFire("!self", "speakresponseconcept", "PlayerLaugh", 0, null, player); // Make each player laugh.
}

Conversely, the CBaseEntity::ConnectOutput() and DisconnectOutput() functions can be used to call a script function when the specified entity output fires. In addition, arbitrary VScript code can be run from the I/O system, using the RunScriptCode input available in all entities. The code will run in the current entities script scope.

Warning:Never use double-quotation marks in any Hammer Output, since it will corrupt the map file. This means that strings cannot be passed with RunScriptCode.

## Global Scripts

Naming a script file with a game mode name a mode specific script, and makes it execute every time a map is loaded in the specified mode. If a Mode Script exists, a map specific script with the map name followed by an underscore and the mode name can also be loaded.

### Scripted Mode

Adding a Mode Script will enable Scripted Mode for the game mode. This works on the base game modes included in the game as well.

Scripted Mode loads utility functions into the g_ModeScript scope, disables the hardcoded setting of 2 on the MaxSpecials Director Option, and enables game event callbacks and script hook functions. It also seems to break the finale tank music in Dark Carnival.

To do: Does enabling Scripted Mode have any other consequences?

### Shared Tables

SessionState
A table for storing session specific variables. Not preserved across level transitions.
SessionOptions
Base Director Options for the game mode.

### Available Functions

To do: Document the available utility features.

### Mode Scripts

Use script scope g_ModeScript

#### Tables

MutationState
Initial values for the SessionState table.
MutationOptions
Initial values for the SessionOptions table.

### Map Scripts

Use script scope g_MapScript

#### Tables

MapState
Map specific values for the SessionState table.
MapOptions
Map specific values for the SessionOptions table.

## Glossary

DirectorOptions
A table of named variables that override the AI Director behavior.
Entity handle
Also known as EHANDLE. To do: Looks like some sort of pointer reference to an entity.
Script handle
An entity instance with accessors and mutators to the C++ entity object. Also known as HScript.
Script scope
The table where the variables, functions and classes of a VScript are placed.

## Director options

Please see L4D2 Director Scripts for a table of available options.

## Third party tools

### VSLib

VSLib (VScript Library) is a simple, lightweight library for L4D2's VScript mutation system. It greatly simplifies coding VScripts by taking care of a lot of tedious work for you. It is used in several popular mods like Rayman1103's Admin System and Stranded. Read more about VSLib.