KScript documentazione
IT

Lingua

Tradotto automaticamente dall’inglese, che è la versione originale.

Il linguaggio

Espressioni

+ - * / % **, == != (loose: '3' == 3), === !== (strict), < <= > >=, and or not, ??, ?., a ? b : c, in, list [1, 2] and map { name: 'Joan' } literals, $p.name, $list[0] (negative indexes count from the end), ranges 0..10 and 0..100 step 5 (end excluded, also with a step such as 0.1) and 1..=10 (end included), match $x { 1 => 'one', _ => 'other' }, ->method(), |> and fn(x) => …. Write and and or to combine conditions. Prefix ! has the same precedence and truthiness as not, so !$ready, ! $ready and not $ready are equivalent. Use it on a field (!$user.active), a whole condition (if !($ready and $open) { … }), or an interpolation ("{ ! null->is_null() }"). The spelling null->!is_null() negates the method result before the next link in the chain. XML has a word for each comparison as well (lt le gt ge eq ne), for use inside quoted attributes, since XML can't hold a raw < there; the shorthand start tags accept < and > as written. In a .kscript file the words are reported (KS6012) and kscript check --fix writes the symbols.

Quando confronti un numero con una stringa usando <, <=, > o >=, KScript confronta numericamente se la stringa può essere letta come numero. Se la lettura fallisce, il confronto restituisce false. I confronti si concatenano come in matematica, come mostra la sezione Matematica. Due date sono uguali con == solo quando sono lo stesso istante, secondi compresi.

Matematica

La matematica quotidiana ha un simbolo proprio, e ciascuno funziona allo stesso modo in uno script, in un modello e in una query di database. + somma, - sottrae, * moltiplica e / divide, mantenendo la frazione. ~/ divide in numeri interi, arrotondando per difetto. % dà il resto, che conserva il segno del numero a sinistra, %% si avvolge come un orologio, e ** eleva a potenza:

<let name="minutes" value="135" />
<let name="hours" value="$minutes / 60" /> <!-- 2.25 because / keeps the fraction -->
<let name="whole" value="$minutes ~/ 60" /> <!-- 2 because 60 fits into 135 twice -->
<let name="left" value="$minutes % 60" /> <!-- 15 because 135 - 2 * 60 leaves 15 -->
<let name="behind" value="-7 % 3" /> <!-- -1 because % keeps the sign of -7 -->
<let name="area" value="4 ** 2" /> <!-- 16 because 4 * 4 is 16 -->
<let name="kilobyte" value="2 ** 10" /> <!-- 1024 because ten 2s are multiplied -->
$minutes = 135
$hours = $minutes / 60        // 2.25 because / keeps the fraction
$whole = $minutes ~/ 60       // 2 because 60 fits into 135 twice
$left = $minutes % 60         // 15 because 135 - 2 * 60 leaves 15
$behind = -7 % 3              // -1 because % keeps the sign of -7
$area = 4 ** 2                // 16 because 4 * 4 is 16
$kilobyte = 2 ** 10           // 1024 because ten 2s are multiplied

Gli operatori si legano in quest'ordine, dal più stretto, quindi 2 + 3 * 4 vale 14 perché * si lega prima di +:

Livello Operatori Raggruppamento
1 . -> ?. ( ) [ ] da sinistra a destra
2 ** da destra a sinistra: 2 ** 3 ** 2 è 2 ** 9, 512
3 -x +x -2 ** 2 vale -4 perché ** si lega per primo, quindi scrivi -(2 ** 2) o (-2) ** 2 (KS6023)
4 * / ~/ % %% da sinistra a destra
5 + - da sinistra a destra
6 .. ..= step un intervallo per espressione
7 |> da sinistra a destra
8 < <= > >= in una catena in una direzione: 0 <= $n < 10
9 == != === !== uno per confronto: per unirne di più usa and
10 not, and, or, ??, a ? b : c

% e %% differiscono solo quando un segno è negativo. Il resto conserva il segno del lato sinistro, come C# e JavaScript. Il modulo prende il segno del lato destro, quindi si avvolge: un'ora prima di mezzanotte è 23, non -1. Usa %% per gli orologi, i giorni della settimana e le posizioni in una lista che si avvolgono alla fine:

<let name="hour" value="9 - 12" /> <!-- -3 because 3 hours before 9 -->
<let name="late" value="$hour % 24" /> <!-- -3 because % keeps the sign of -3 -->
<let name="clock" value="$hour %% 24" /> <!-- 21 because %% wraps back round the clock -->
<let name="days" value="['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']" />
<let name="today" value="0" /> <!-- 'mon' is at 0 -->
<let name="yesterday" value="$days[($today - 1) %% 7]" /> <!-- 'sun' because -1 wraps round to the last day -->
<let name="spare" value="-15m %% 1h" /> <!-- 45m because durations wrap the same way -->
$hour = 9 - 12                // -3 because 3 hours before 9
$late = $hour % 24            // -3 because % keeps the sign of -3
$clock = $hour %% 24          // 21 because %% wraps back round the clock
$days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
$today = 0                    // 'mon' is at 0
$yesterday = $days[($today - 1) %% 7] // 'sun' because -1 wraps round to the last day
$spare = -15m %% 1h           // 45m because durations wrap the same way

~/ arrotonda per difetto, non verso zero, quindi si abbina a %%: ($a ~/ $b) * $b + $a %% $b è sempre $a. Funziona anche con durate e denaro, e restituisce un numero semplice:

<let name="balance" value="-7" />
<let name="weeks" value="$balance ~/ 2" /> <!-- -4 because it rounds down, not toward zero -->
<let name="rest" value="$balance %% 2" /> <!-- 1 because -4 * 2 + 1 is -7 -->
<let name="runtime" value="2h10m" />
<let name="episodes" value="$runtime ~/ 25m" /> <!-- 5 because five 25m episodes fit into 2h10m -->
<let name="spare" value="$runtime %% 25m" /> <!-- 5m because 2h10m - 5 * 25m leaves 5m -->
$balance = -7
$weeks = $balance ~/ 2        // -4 because it rounds down, not toward zero
$rest = $balance %% 2         // 1 because -4 * 2 + 1 is -7
$runtime = 2h10m
$episodes = $runtime ~/ 25m   // 5 because five 25m episodes fit into 2h10m
$spare = $runtime %% 25m      // 5m because 2h10m - 5 * 25m leaves 5m

// inizia un commento, quindi non può essere una divisione intera. $hours = $minutes // $per_hour lascia $minutes com'è, e KS6022 lo segnala con una correzione che scrive ~/.

I confronti che vanno nella stessa direzione si concatenano come in matematica, così un controllo di intervallo si legge come si dice. Ogni valore nel mezzo viene calcolato una sola volta, e la catena si ferma al primo confronto falso:

<let name="score" value="42" />
<let name="passed" value="0 &lt;= $score &lt; 100" /> <!-- true because 42 is from 0 up to (not including) 100 -->
<let name="top" value="90 &lt;= $score &lt;= 100" /> <!-- false because 42 is below 90 -->
<let name="falling" value="10 > 7 >= 7 > 1" /> <!-- true because each step goes down or stays the same -->
$score = 42
$passed = 0 <= $score < 100   // true because 42 is from 0 up to (not including) 100
$top = 90 <= $score <= 100    // false because 42 is below 90
$falling = 10 > 7 >= 7 > 1    // true because each step goes down or stays the same

Una catena va in una sola direzione. 1 < $n > 0 è un errore perché non dice nulla su come si confrontano 1 e 0, quindi scrivi 1 < $n and $n > 0. == e != non si concatenano: $a == $b == $c confronterebbe vero o falso con $c, quindi scrivi $a == $b and $b == $c. Le parentesi interrompono una catena, quindi (1 < $n) == true confronta il risultato. Una catena funziona anche in una query di database: Person->where(fn(person) => 18 <= $person.age < 65) richiede age >= 18 AND age < 65. ->between() non esiste più, e il suo errore indica la catena da scrivere.

.. crea un intervallo che termina prima della fine, il che è adatto a contare da 0 e alle posizioni in una lista. ..= include anche la fine, il che è adatto a contare da 1. Passando sopra uno dei due si vede dove l'intervallo inizia e finisce:

<let name="positions" value="0..3" /> <!-- [0, 1, 2] because .. stops before 3 -->
<let name="places" value="1..=3" /> <!-- [1, 2, 3] because ..= takes in 3 -->
<let name="quarters" value="0..=1 step 0.25" /> <!-- [0, 0.25, 0.5, 0.75, 1] because a step lands on 1 -->
<let name="odd" value="1..=10 step 2" /> <!-- [1, 3, 5, 7, 9] because no step lands on 10 -->
<let name="monday" value="'2026-11-30'->to_date()" />
<let name="week" value="$monday..=$monday + 6d" /> <!-- seven dates because ..= takes in the Sunday -->
$positions = 0..3             // [0, 1, 2] because .. stops before 3
$places = 1..=3               // [1, 2, 3] because ..= takes in 3
$quarters = 0..=1 step 0.25   // [0, 0.25, 0.5, 0.75, 1] because a step lands on 1
$odd = 1..=10 step 2          // [1, 3, 5, 7, 9] because no step lands on 10
$monday = '2026-11-30'->to_date()
$week = $monday..=$monday + 6d // seven dates because ..= takes in the Sunday

Come .., un intervallo conta all'indietro quando la fine è minore dell'inizio, quindi 3..=1 equivale a [3, 2, 1] e 1..=0 equivale a [1, 0]. Per contare fino a un valore che può essere 0, come in 1..($count + 1), usa .., che non produce valori quando $count è 0.

^ non è l'elevamento a potenza in KScript (in C# e JavaScript è un operatore bit a bit), quindi 2 ^ 10 è un errore la cui correzione scrive 2 ** 10.

I bit si manipolano con un metodo, ->bits(), invece che con simboli, perché & e | si confondono facilmente con and e or. Agisce un passo alla volta, su numeri interi:

<let name="read" value="4" />
<let name="write" value="2" />
<let name="permissions" value="6" /> <!-- read and write, because 4 + 2 is 6 -->
<let name="can_read" value="$permissions->bits(and: $read) == $read" /> <!-- true because 6 has the 4 bit -->
<let name="with_run" value="$permissions->bits(or: 1)" /> <!-- 7 because or: adds the 1 bit -->
<let name="toggled" value="$permissions->bits(xor: $write)" /> <!-- 4 because xor: flips the 2 bit off -->
<let name="doubled" value="$permissions->bits(shift: 1)" /> <!-- 12 because each bit moves one place left -->
<let name="halved" value="$permissions->bits(shift: -1)" /> <!-- 3 because a negative shift moves right -->
<let name="flipped" value="$permissions->bits(invert)" /> <!-- -7 because every bit flips -->
$read = 4
$write = 2
$permissions = 6              // read and write, because 4 + 2 is 6
$can_read = $permissions->bits(and: $read) == $read // true because 6 has the 4 bit
$with_run = $permissions->bits(or: 1)               // 7 because or: adds the 1 bit
$toggled = $permissions->bits(xor: $write)          // 4 because xor: flips the 2 bit off
$doubled = $permissions->bits(shift: 1)             // 12 because each bit moves one place left
$halved = $permissions->bits(shift: -1)             // 3 because a negative shift moves right
$flipped = $permissions->bits(invert)               // -7 because every bit flips

&, un singolo |, << e >> tra due valori sono errori che indicano la chiamata ->bits() da scrivere, mentre & e | offrono una correzione che scrive and o or, che di solito è ciò che si intendeva.

($hour + 24) % 24 era il vecchio modo per arrotondare un numero. KS6021 suggerisce $hour %% 24, che funziona anche per numeri inferiori a -24.

+=, -=, *=, /=, ~/=, %=, %%=, **= e ??= modificano una variabile sul posto: $total += 5 equivale a $total = $total + 5. Gli spazi attorno a un operatore sono a tua scelta, ma uno spazio al suo interno lo spezza: 2 * * 10 è un errore che indica **, e la correzione rapida rimuove lo spazio.

L'editor elenca le variabili dopo un operatore e uno spazio, prima quelle del tipo del lato sinistro, e passando sopra un operatore si vede cosa fa.

Usa expression as Type per una conversione controllata, ad esempio $text as int. Il tipo di destinazione può anche essere un record, un enum o un tipo raffinato dichiarato. Conversioni controllate