Skip to content

Enforce Script Cheat Sheet

Home | Cheat Sheet


Single-page quick reference for DayZ Enforce Script. Bookmark this.


Types

TypeDescriptionDefaultExample
int32-bit signed integer0int x = 42;
float32-bit float0.0float f = 3.14;
boolBooleanfalsebool b = true;
stringImmutable value type""string s = "hello";
vector3-component float (x,y,z)"0 0 0"vector v = "1 2 3";
typenameType referencenulltypename t = PlayerBase;
ClassRoot of all reference typesnull
voidNo return

Limits: int.MAX = 2147483647, int.MIN = -2147483648, float.MAX, float.MIN


Array Methods (array<T>)

MethodReturnsNotes
Insert(item)int (index)Append
InsertAt(item, idx)voidInsert at position
Get(idx) / arr[idx]TAccess by index
Set(idx, item)voidReplace at index
Find(item)intIndex or -1
Count()intElement count
IsValidIndex(idx)boolBounds check
Remove(idx)voidUnordered (swaps with last!)
RemoveOrdered(idx)voidPreserves order
RemoveItem(item)voidFind + remove (ordered)
Clear()voidRemove all
Sort() / Sort(true)voidAscending / descending
ShuffleArray()voidRandomize
Invert()voidReverse
GetRandomElement()TRandom pick
InsertAll(other)voidAppend all from other
Copy(other)voidReplace with copy
Resize(n)voidResize (fills defaults)
Reserve(n)voidPre-allocate capacity

Typedefs: TStringArray, TIntArray, TFloatArray, TBoolArray, TVectorArray


Map Methods (map<K,V>)

MethodReturnsNotes
Insert(key, val)boolAdd new
Set(key, val)voidInsert or update
Get(key)VReturns default if missing
Find(key, out val)boolSafe get
Contains(key)boolCheck existence
Remove(key)voidRemove by key
Count()intEntry count
GetKey(idx)KKey at index (O(n))
GetElement(idx)VValue at index (O(n))
GetKeyArray()array<K>All keys
GetValueArray()array<V>All values
Clear()voidRemove all

Set Methods (set<T>)

MethodReturns
Insert(item)int (index)
Find(item)int (index or -1)
Get(idx)T
Remove(idx)void
RemoveItem(item)void
Count()int
Clear()void

Class Syntax

c
class MyClass extends BaseClass
{
    protected int m_Value;                  // field
    private ref array<string> m_List;       // owned ref

    void MyClass() { m_List = new array<string>; }  // constructor
    void ~MyClass() { }                              // destructor

    override void OnInit() { super.OnInit(); }       // override
    static int GetCount() { return 0; }              // static method
};

Access: private | protected | (public by default) Modifiers: static | override | ref | const | out | notnullModded: modded class MissionServer { override void OnInit() { super.OnInit(); } }


Control Flow

c
// if / else if / else
if (a > 0) { } else if (a == 0) { } else { }

// for
for (int i = 0; i < count; i++) { }

// foreach (value)
foreach (string item : myArray) { }

// foreach (index + value)
foreach (int i, string item : myArray) { }

// foreach (map: key + value)
foreach (string key, int val : myMap) { }

// while
while (condition) { }

// switch (falls through without break, like C/C++)
switch (val) { case 0: Print("zero"); break; default: break; }

String Methods

MethodReturnsExample
s.Length()int"hello".Length() = 5
s.Substring(start, len)string"hello".Substring(1,3) = "ell"
s.IndexOf(sub)int-1 if not found
s.LastIndexOf(sub)intSearch from end
s.Contains(sub)bool
s.Replace(old, new)intModifies in-place, returns count
s.ToLower()int (length)In-place!
s.ToUpper()int (length)In-place!
s.TrimInPlace()voidIn-place!
s.Split(delim, out arr)voidSplits into TStringArray
s.Get(idx)stringSingle char
s.Set(idx, ch)voidReplace char
s.ToInt()intParse int
s.ToFloat()floatParse float
s.ToVector()vectorParse "1 2 3"
string.Format(fmt, ...)string%1..%9 placeholders
string.Join(sep, arr)stringJoin array elements

Math Methods

MethodDescription
Math.RandomInt(min, max)[min, max) exclusive max
Math.RandomIntInclusive(min, max)[min, max]
Math.RandomFloat01()[0, 1]
Math.RandomBool()Random true/false
Math.Round(f) / Floor(f) / Ceil(f)Rounding
Math.AbsFloat(f) / AbsInt(i)Absolute value
Math.Clamp(val, min, max)Clamp to range
Math.Min(a, b) / Max(a, b)Min/max
Math.Lerp(a, b, t)Linear interpolation
Math.InverseLerp(a, b, val)Inverse lerp
Math.Pow(base, exp) / Sqrt(f)Power/root
Math.Sin(r) / Cos(r) / Tan(r)Trig (radians)
Math.Atan2(y, x)Angle from components
Math.NormalizeAngle(deg)Wrap to 0-360
Math.SqrFloat(f) / SqrInt(i)Square

Constants: Math.PI, Math.PI2, Math.PI_HALF, Math.DEG2RAD, Math.RAD2DEG

Vector: vector.Distance(a,b), vector.DistanceSq(a,b), vector.Direction(a,b), vector.Dot(a,b), vector.Lerp(a,b,t), v.Length(), v.Normalized()


Common Patterns

Safe Downcast

c
PlayerBase player;
if (Class.CastTo(player, obj))
{
    player.DoSomething();
}

Inline Cast

c
PlayerBase player = PlayerBase.Cast(obj);
if (player) player.DoSomething();

Null Guard

c
if (!player) return;
if (!player.GetIdentity()) return;
string name = player.GetIdentity().GetName();

Check IsAlive (Requires EntityAI)

c
EntityAI eai;
if (Class.CastTo(eai, obj) && eai.IsAlive()) { }

Foreach Map Iteration

c
foreach (string key, int value : myMap)
{
    Print(key + " = " + value.ToString());
}

Enum Conversion

c
string name = typename.EnumToString(EDamageState, state);
int val = typename.StringToEnum(EDamageState, "RUINED");  // Returns int, -1 on failure

Bitflags

c
int flags = FLAG_A | FLAG_B;       // combine
if (flags & FLAG_A) { }           // test
flags = flags & ~FLAG_B;          // remove

What Does NOT Exist

Missing FeatureWorkaround
Ternary ? :if/else
do...whilewhile(true) { ... break; }
try/catchGuard clauses + early return
Multiple inheritanceSingle + composition
Operator overloadingNamed methods (except [] via Get/Set)
LambdasNamed methods
nullptrnull / NULL
\\ / \" in stringsAvoid (CParser breaks)
#includeconfig.cpp files[]
NamespacesName prefixes (MyMod_, VPP_)
Interfaces / abstractEmpty base methods
switch fall-throughWorks like C/C++ — use break
#define valuesUse const
Default param expressionsLiterals/NULL only
Variadic paramsstring.Format or arrays
Variable redeclaration in else-ifUnique names per branch

Widget Creation (Programmatic)

c
// Get workspace
WorkspaceWidget ws = GetGame().GetWorkspace();

// Create from layout
Widget root = ws.CreateWidgets("MyMod/gui/layouts/MyPanel.layout");

// Find child widget
TextWidget title = TextWidget.Cast(root.FindAnyWidget("TitleText"));
if (title) title.SetText("Hello World");

// Show/hide
root.Show(true);
root.Show(false);

RPC Pattern

Register (server):

c
// In 3_Game or 4_World init:
GetGame().RPCSingleParam(null, MY_RPC_ID, null, true, identity);  // Engine RPC

// Or with string-routed RPC (MyRPC / CF):
GetRPCManager().AddRPC("MyMod", "RPC_Handler", this, 2);  // CF
MyRPC.Register("MyMod", "MyRoute", this, MyRPCSide.SERVER);  // MyMod

Send (client to server):

c
Param2<string, int> data = new Param2<string, int>("itemName", 5);
GetGame().RPCSingleParam(null, MY_RPC_ID, data, true);

Receive (server handler):

c
void RPC_Handler(CallType type, ParamsReadContext ctx, PlayerIdentity sender, Object target)
{
    if (type != CallType.Server) return;
    if (!sender) return;

    Param2<string, int> data;
    if (!ctx.Read(data)) return;

    string itemName = data.param1;
    int quantity = data.param2;
    // Process...
}

Error Handling

c
ErrorEx("message");                              // Default ERROR severity
ErrorEx("info", ErrorExSeverity.INFO);           // Info
ErrorEx("warning", ErrorExSeverity.WARNING);     // Warning
Print("debug output");                           // Script log
string stack; DumpStackString(stack);             // Get call stack (out param)

File I/O

c
// Paths: "$profile:", "$saves:", "$mission:", "$CurrentDir:"
bool exists = FileExist("$profile:MyMod/config.json");
MakeDirectory("$profile:MyMod");

// JSON
MyConfig cfg = new MyConfig();
JsonFileLoader<MyConfig>.JsonLoadFile(path, cfg);  // Returns VOID!
JsonFileLoader<MyConfig>.JsonSaveFile(path, cfg);

// Raw file
FileHandle fh = OpenFile(path, FileMode.WRITE);
if (fh != 0) { FPrintln(fh, "line"); CloseFile(fh); }

Object Creation

c
// Basic
Object obj = GetGame().CreateObject("AK101", pos, false, false, true);

// With flags
Object obj = GetGame().CreateObjectEx("Barrel_Green", pos, ECE_PLACE_ON_SURFACE);

// In player inventory
player.GetInventory().CreateInInventory("BandageDressing");

// As attachment
weapon.GetInventory().CreateAttachment("ACOGOptic");

// Delete
GetGame().ObjectDelete(obj);

Key Global Functions

c
GetGame()                          // CGame instance
GetGame().GetPlayer()              // Local player (CLIENT only, null on server!)
GetGame().GetPlayers(out arr)      // All players (server)
GetGame().GetWorld()               // World instance
GetGame().GetTickTime()            // Server time (float)
GetGame().GetWorkspace()           // UI workspace
GetGame().SurfaceY(x, z)          // Terrain height
GetGame().IsServer()               // true on server
GetGame().IsClient()               // true on client
GetGame().IsMultiplayer()          // true if multiplayer

Full documentation: DayZ Modding Wiki | Gotchas | Error Handling

Released under CC BY-SA 4.0 | Code examples under MIT License