Skip to content

Scheda di Riferimento Rapido di Enforce Script

Home | Scheda di Riferimento Rapido


Riferimento rapido su una singola pagina per Enforce Script di DayZ. Aggiungilo ai segnalibri.


Tipi

TipoDescrizionePredefinitoEsempio
intIntero con segno a 32 bit0int x = 42;
floatFloat a 32 bit0.0float f = 3.14;
boolBooleanofalsebool b = true;
stringTipo valore immutabile""string s = "hello";
vectorFloat a 3 componenti (x,y,z)"0 0 0"vector v = "1 2 3";
typenameRiferimento al tiponulltypename t = PlayerBase;
ClassRadice di tutti i tipi riferimentonull---
voidNessun valore di ritorno------

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


Metodi Array (array<T>)

MetodoRestituisceNote
Insert(item)int (indice)Aggiunge in coda
InsertAt(item, idx)voidInserisce alla posizione
Get(idx) / arr[idx]TAccesso per indice
Set(idx, item)voidSostituisce all'indice
Find(item)intIndice o -1
Count()intConteggio elementi
IsValidIndex(idx)boolControllo limiti
Remove(idx)voidNon ordinato (scambia con l'ultimo!)
RemoveOrdered(idx)voidPreserva l'ordine
RemoveItem(item)voidTrova + rimuovi (ordinato)
Clear()voidRimuove tutto
Sort() / Sort(true)voidCrescente / decrescente
ShuffleArray()voidMescola casualmente
Invert()voidInverti
GetRandomElement()TScelta casuale
InsertAll(other)voidAggiunge tutti dall'altro
Copy(other)voidSostituisci con copia
Resize(n)voidRidimensiona (riempie con valori predefiniti)
Reserve(n)voidPre-alloca capacita

Typedef: TStringArray, TIntArray, TFloatArray, TBoolArray, TVectorArray


Metodi Map (map<K,V>)

MetodoRestituisceNote
Insert(key, val)boolAggiunge nuovo
Set(key, val)voidInserisce o aggiorna
Get(key)VRestituisce predefinito se mancante
Find(key, out val)boolGet sicuro
Contains(key)boolControlla esistenza
Remove(key)voidRimuove per chiave
Count()intConteggio voci
GetKey(idx)KChiave all'indice (O(n))
GetElement(idx)VValore all'indice (O(n))
GetKeyArray()array<K>Tutte le chiavi
GetValueArray()array<V>Tutti i valori
Clear()voidRimuove tutto

Metodi Set (set<T>)

MetodoRestituisce
Insert(item)int (indice)
Find(item)int (indice o -1)
Get(idx)T
Remove(idx)void
RemoveItem(item)void
Count()int
Clear()void

Sintassi delle classi

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

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

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

Accesso: private | protected | (pubblico per impostazione predefinita) Modificatori: static | override | ref | const | out | notnullModded: modded class MissionServer { override void OnInit() { super.OnInit(); } }


Flusso di controllo

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

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

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

// foreach (indice + valore)
foreach (int i, string item : myArray) { }

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

// while
while (condition) { }

// switch (NESSUN fall-through!)
switch (val) { case 0: Print("zero"); break; default: break; }

Metodi String

MetodoRestituisceEsempio
s.Length()int"hello".Length() = 5
s.Substring(start, len)string"hello".Substring(1,3) = "ell"
s.IndexOf(sub)int-1 se non trovato
s.LastIndexOf(sub)intCerca dalla fine
s.Contains(sub)bool
s.Replace(old, new)intModifica in-place, restituisce il conteggio
s.ToLower()voidIn-place!
s.ToUpper()voidIn-place!
s.TrimInPlace()voidIn-place!
s.Split(delim, out arr)voidDivide in TStringArray
s.Get(idx)stringSingolo carattere
s.Set(idx, ch)voidSostituisce carattere
s.ToInt()intAnalizza int
s.ToFloat()floatAnalizza float
s.ToVector()vectorAnalizza "1 2 3"
string.Format(fmt, ...)stringSegnaposto %1..%9
string.Join(sep, arr)stringUnisce elementi array

Metodi Math

MetodoDescrizione
Math.RandomInt(min, max)[min, max) max escluso
Math.RandomIntInclusive(min, max)[min, max]
Math.RandomFloat01()[0, 1]
Math.RandomBool()true/false casuale
Math.Round(f) / Floor(f) / Ceil(f)Arrotondamento
Math.AbsFloat(f) / AbsInt(i)Valore assoluto
Math.Clamp(val, min, max)Limita all'intervallo
Math.Min(a, b) / Max(a, b)Min/max
Math.Lerp(a, b, t)Interpolazione lineare
Math.InverseLerp(a, b, val)Lerp inverso
Math.Pow(base, exp) / Sqrt(f)Potenza/radice
Math.Sin(r) / Cos(r) / Tan(r)Trigonometria (radianti)
Math.Atan2(y, x)Angolo dalle componenti
Math.NormalizeAngle(deg)Normalizza a 0-360
Math.SqrFloat(f) / SqrInt(i)Elevamento al quadrato

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

Vettori: 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()


Pattern comuni

Downcast sicuro

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

Cast inline

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

Controllo null

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

Controllo IsAlive (richiede EntityAI)

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

Iterazione foreach su Map

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

Conversione Enum

c
string name = typename.EnumToString(EDamageState, state);
int val; typename.StringToEnum(EDamageState, "RUINED", val);

Flag di bit

c
int flags = FLAG_A | FLAG_B;       // combina
if (flags & FLAG_A) { }           // testa
flags = flags & ~FLAG_B;          // rimuovi

Cosa NON esiste

Funzionalita mancanteSoluzione alternativa
Ternario ? :if/else
do...whilewhile(true) { ... break; }
try/catchClausole di guardia + return anticipato
Ereditarieta multiplaSingola + composizione
Overloading operatoriMetodi con nome (tranne [] tramite Get/Set)
LambdaMetodi con nome
nullptrnull / NULL
\\ / \" nelle stringheEvitare (CParser si rompe)
#includeconfig.cpp files[]
NamespacePrefissi di nome (MyMod_, VPP_)
Interfacce / abstractMetodi base vuoti
Switch fall-throughOgni case e indipendente
Valori #defineUsa const
Espressioni parametri predefinitiSolo letterali/NULL
Parametri variadicistring.Format o array
Ridichiarazione variabili in else-ifNomi unici per ramo

Creazione Widget (programmatica)

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

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

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

// Mostrare/nascondere
root.Show(true);
root.Show(false);

Pattern RPC

Registrazione (server):

c
// Nell'init di 3_Game o 4_World:
GetGame().RPCSingleParam(null, MY_RPC_ID, null, true, identity);  // RPC del motore

// Oppure con RPC a routing stringa (MyRPC / CF):
GetRPCManager().AddRPC("MyMod", "RPC_Handler", this, 2);  // CF
MyRPC.Register("MyMod", "MyRoute", this, MyRPCSide.SERVER);  // MyMod

Invio (client al server):

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

Ricezione (handler server):

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;
    // Elabora...
}

Gestione errori

c
ErrorEx("message");                              // Severita ERROR predefinita
ErrorEx("info", ErrorExSeverity.INFO);           // Info
ErrorEx("warning", ErrorExSeverity.WARNING);     // Avviso
Print("debug output");                           // Log script
string stack = DumpStackString();                // Ottieni stack delle chiamate

I/O File

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

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

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

Creazione oggetti

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

// Con flag
Object obj = GetGame().CreateObjectEx("Barrel_Green", pos, ECE_PLACE_ON_SURFACE);

// Nell'inventario del giocatore
player.GetInventory().CreateInInventory("BandageDressing");

// Come allegato
weapon.GetInventory().CreateAttachment("ACOGOptic");

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

Funzioni globali principali

c
GetGame()                          // Istanza CGame
GetGame().GetPlayer()              // Giocatore locale (SOLO CLIENT, null sul server!)
GetGame().GetPlayers(out arr)      // Tutti i giocatori (server)
GetGame().GetWorld()               // Istanza World
GetGame().GetTickTime()            // Tempo del server (float)
GetGame().GetWorkspace()           // Workspace UI
GetGame().SurfaceY(x, z)          // Altezza del terreno
GetGame().IsServer()               // true sul server
GetGame().IsClient()               // true sul client
GetGame().IsMultiplayer()          // true se multiplayer

Documentazione completa: DayZ Modding Wiki | Insidie | Gestione errori

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