KScript documentación
ES

Idioma

Traducido automáticamente del inglés, que es la versión original.

Campos y métodos de number

Números enteros y decimales.

Un número se escribe tal como se lee: 42, 3.5, -7. Los números enteros se mantienen exactos por grandes que sean, así que 2 ** 100 muestra todos los dígitos, y los números con punto decimal funcionan con unas 15 cifras significativas.

Los métodos de número devuelven un número nuevo y nunca cambian una variable, así que guarda el resultado: $total = $total->round(digits: 2).

Un signo menos escrito pegado a un número forma parte de él, así que -5->abs() equivale a 5. Con una variable, el signo menos se aplica a toda la cadena: -$change->abs() es menos el tamaño del cambio, y (-$change)->abs() lo agrupa antes.

Para comprobar que un número está dentro de un rango, encadena comparaciones como en matemáticas. Ambos extremos cuentan con <=:

<let name="age" value="18" />
<echo value="13 &lt;= $age &lt;= 19" /> <!-- true because 18 is a teenage age -->
<echo value="0 &lt;= $age &lt;= 17" /> <!-- false because 18 is past 17 -->
$age = 18
echo 13 <= $age <= 19   // true because 18 is a teenage age
echo 0 <= $age <= 17    // false because 18 is past 17

Redondear: round · floor · ceil · to_int

Comparar y limitar: min · max · clamp · abs · is_even · is_odd

Bits: bits

Contar: increment · decrement · times

Convertir en otra cosa: format · to_date · to_number

Un campo es un dato fijo sobre el valor, que se lee con un punto y sin corchetes: $value.name. Un método recibe argumentos o realiza una acción, y se llama con ->: $value->name(arguments), o con el valor encadenado: $value |> name(arguments).

Desde KScript.Core

#number->abs() → number

Sin su signo.

->abs() devuelve el número sin su signo menos: la distancia que hay hasta cero. Es útil para una diferencia en la que te importa su tamaño, pero no su sentido:

<let name="change" value="4 - 9" />
<echo value="$change" /> <!-- -5 -->
<echo value="$change->abs()" /> <!-- 5 because the sign is dropped -->
<echo value="-5->abs()" /> <!-- 5 because -5 is one number, and its size is 5 -->
$change = 4 - 9
echo $change          // -5
echo $change->abs()   // 5 because the sign is dropped
echo -5->abs()        // 5 because -5 is one number, and its size is 5
Ejemplo
<echo>{ -5->abs() }</echo>
echo -5->abs()

#number->bits(and?: number, or?: number, xor?: number, shift?: number, invert?: bool) → number

Trabaja sobre los bits del número, como entero: and: conserva los bits que tienen ambos (12->bits(and: 10) es 8), or: los bits que tiene cualquiera de los dos (15), xor: los bits que tiene solo uno (6), shift: los desplaza a la izquierda, o a la derecha si el valor es negativo (1->bits(shift: 4) es 16), e invert invierte todos los bits (5->bits(invert) es -6). De uno en uno.

->bits(and|or|xor|shift: number) o ->bits(invert) trabaja sobre los dígitos binarios de un entero, un paso por llamada. Es útil para flags empaquetados en un solo número, donde cada bit significa una cosa:

<let name="read" value="4" />
<let name="write" value="2" />
<let name="permissions" value="6" /> <!-- read and write, because 4 + 2 is 6 -->
<echo value="$permissions->bits(and: $read) == $read" /> <!-- true because 6 has the 4 bit set -->
<echo value="$permissions->bits(or: 1)" /> <!-- 7 because or: turns the 1 bit on -->
<echo value="$permissions->bits(xor: $write)" /> <!-- 4 because xor: flips the 2 bit off -->
<echo value="$permissions->bits(shift: 1)" /> <!-- 12 because every bit moves one place left -->
<echo value="$permissions->bits(shift: -1)" /> <!-- 3 because a negative shift moves right -->
<echo value="$permissions->bits(invert)" /> <!-- -7 because every bit flips -->
$read = 4
$write = 2
$permissions = 6                              // read and write, because 4 + 2 is 6
echo $permissions->bits(and: $read) == $read // true because 6 has the 4 bit set
echo $permissions->bits(or: 1)               // 7 because or: turns the 1 bit on
echo $permissions->bits(xor: $write)         // 4 because xor: flips the 2 bit off
echo $permissions->bits(shift: 1)            // 12 because every bit moves one place left
echo $permissions->bits(shift: -1)           // 3 because a negative shift moves right
echo $permissions->bits(invert)              // -7 because every bit flips
ParámetroRecibe
and optionalnumber
or optionalnumber
xor optionalnumber
shift optionalnumber
invert optionalun flag: invert o not invert

Los argumentos pueden tener nombre: ->bits(…, or: …, xor: …).

Ejemplo
<echo>{ 12->bits(and: 10) }</echo>
echo 12->bits(and: 10)

#number->ceil() → number

Redondeado hacia arriba.

->ceil() redondea hacia arriba al siguiente entero, o deja como está un entero. Es útil para contar lo que necesitas para contenerlo todo:

<let name="people" value="23" />
<echo value="($people / 4)->ceil()" /> <!-- 6 because 23 / 4 is 5.75, and 5 tables of 4 would leave 3 people standing -->
<echo value="6->ceil()" /> <!-- 6 because it is already whole -->
<echo value="-2.5->ceil()" /> <!-- -2 because up means towards the larger number -->
$people = 23
echo ($people / 4)->ceil()   // 6 because 23 / 4 is 5.75, and 5 tables of 4 would leave 3 people standing
echo 6->ceil()               // 6 because it is already whole
echo -2.5->ceil()          // -2 because up means towards the larger number
Ejemplo
<echo>{ 3.2->ceil() }</echo>
echo 3.2->ceil()

#number->clamp(min: number, max: number) → number

El número limitado al rango min..max.

->clamp(min, max) mantiene el número dentro de min..max. Por debajo de min devuelve min, por encima de max devuelve max, y entre ambos devuelve el número:

<echo value="150->clamp(0, 100)" /> <!-- 100 because 150 is above the top -->
<echo value="-20->clamp(0, 100)" /> <!-- 0 because -20 is below the bottom -->
<echo value="42->clamp(0, 100)" /> <!-- 42 because it is already in range -->
echo 150->clamp(0, 100)   // 100 because 150 is above the top
echo -20->clamp(0, 100) // 0 because -20 is below the bottom
echo 42->clamp(0, 100)    // 42 because it is already in range
ParámetroRecibe
min requirednumber
max requirednumber

Los argumentos pueden tener nombre: ->clamp(…, max: …).

Ejemplo
<echo>{ 150->clamp(0, 100) }</echo>
echo 150->clamp(0, 100)

#number->decrement() → number

El número menos 1.

->decrement() es el número menos 1. ->increment() suma 1:

<let name="lives" value="3" />
<set name="lives" value="$lives->decrement()" />
<echo value="$lives" /> <!-- 2 -->
$lives = 3
$lives = $lives->decrement()
echo $lives   // 2
Ejemplo
<echo>{ 43->decrement() }</echo>
echo 43->decrement()

#number->floor() → number

Redondeado hacia abajo.

->floor() redondea hacia abajo al entero inferior, o deja como está un entero. Es útil para contar cuántas cosas enteras caben:

<let name="budget" value="20" />
<echo value="($budget / 3)->floor()" /> <!-- 6 because 20 / 3 is 6.67, and only 6 whole tickets at £3 fit in £20 -->
<echo value="3.99->floor()" /> <!-- 3 because the decimals are always dropped downwards -->
<echo value="-2.5->floor()" /> <!-- -3 because down means towards the smaller number -->
$budget = 20
echo ($budget / 3)->floor()   // 6 because 20 / 3 is 6.67, and only 6 whole tickets at £3 fit in £20
echo 3.99->floor()            // 3 because the decimals are always dropped downwards
echo -2.5->floor()          // -3 because down means towards the smaller number
Ejemplo
<echo>{ 3.7->floor() }</echo>
echo 3.7->floor()

#number->format(pattern?) → string

Formatea el número (formato .NET, N0 por defecto: 1,234).

->format(pattern?) convierte el número en texto para que lo lean las personas. Sin patrón devuelve un entero con comas cada tres cifras. Un patrón elige otro formato: N2 mantiene dos decimales, P0 muestra una proporción como porcentaje, y 0.00 o 000 rellenan con ceros:

<echo value="1234567->format()" /> <!-- '1,234,567' because the commas split it into thousands -->
<echo value="1234.567->format('N2')" /> <!-- '1,234.57' because N2 keeps two decimal places, rounded -->
<echo value="0.075->format('P1')" /> <!-- '7.5 %' because P shows a share of 1 as a percentage -->
<echo value="7->format('000')" /> <!-- '007' because each 0 is a digit that must be shown -->
echo 1234567->format()           // '1,234,567' because the commas split it into thousands
echo 1234.567->format('N2')      // '1,234.57' because N2 keeps two decimal places, rounded
echo 0.075->format('P1')         // '7.5 %' because P shows a share of 1 as a percentage
echo 7->format('000')            // '007' because each 0 is a digit that must be shown
Ejemplo
<echo>{ 1234567.891->format('N2') }</echo>
echo 1234567.891->format('N2')

#number->increment() → number

El número más 1.

->increment() es el número más 1. ->decrement() resta 1:

<let name="visits" value="41" />
<set name="visits" value="$visits->increment()" />
<echo value="$visits" /> <!-- 42 -->
$visits = 41
$visits = $visits->increment()
echo $visits   // 42
Ejemplo
<echo>{ 41->increment() }</echo>
echo 41->increment()

#number->is_even() → bool

Verdadero cuando el número es par.

->is_even() es verdadero para un entero que 2 divide exactamente. Un número con decimales no es ni par ni impar:

<echo value="10->is_even()" /> <!-- true -->
<echo value="7->is_even()" /> <!-- false because 7 leaves 1 over when shared into twos -->
<echo value="-4->is_even()" /> <!-- true because negative numbers can be even too -->
<echo value="2.5->is_even()" /> <!-- false because it isn't a whole number -->
echo 10->is_even()        // true
echo 7->is_even()         // false because 7 leaves 1 over when shared into twos
echo -4->is_even()      // true because negative numbers can be even too
echo 2.5->is_even()       // false because it isn't a whole number
Ejemplo
<echo>{ 10->is_even() }</echo>
echo 10->is_even()

#number->is_odd() → bool

Verdadero cuando el número es impar.

->is_odd() es verdadero para un entero que deja resto 1 al dividirlo entre 2. Es útil para alternar el color de las filas:

<let name="rows" value="['tea', 'milk', 'juice']" />
<echo value="$rows->map(fn(drink, index) => $index->is_odd() ? 'grey' : 'white')" /> <!-- ['white', 'grey', 'white'] because rows 0 and 2 are even -->
<echo value="2.5->is_odd()" /> <!-- false because it isn't a whole number -->
$rows = ['tea', 'milk', 'juice']
echo $rows->map(fn(drink, index) => $index->is_odd() ? 'grey' : 'white')   // ['white', 'grey', 'white'] because rows 0 and 2 are even
echo 2.5->is_odd()   // false because it isn't a whole number
Ejemplo
<echo>{ 10->is_odd() }</echo>
echo 10->is_odd()

#number->max(other: number) → number

El mayor de los dos.

->max(other) devuelve el mayor entre el número y other. Es útil para establecer un mínimo: el resultado nunca estará por debajo de other:

<let name="balance" value="-12" />
<echo value="$balance->max(0)" /> <!-- 0 because 0 is larger than -12, so the shown balance never goes below 0 -->
<echo value="30->max(0)" /> <!-- 30 -->
$balance = -12
echo $balance->max(0)   // 0 because 0 is larger than -12, so the shown balance never goes below 0
echo 30->max(0)         // 30
ParámetroRecibe
other obligatorionumber
Ejemplo
<echo>{ 3->max(10) }</echo>
echo 3->max(10)

#number->min(other: number) → number

El menor de los dos.

->min(other) devuelve el menor entre el número y other. Es útil para establecer un máximo: el resultado nunca estará por encima de other:

<let name="wanted" value="12" />
<let name="in_stock" value="10" />
<echo value="$wanted->min($in_stock)" /> <!-- 10 because you can't sell more than the 10 there are -->
$wanted = 12
$in_stock = 10
echo $wanted->min($in_stock)   // 10 because you can't sell more than the 10 there are
ParámetroRecibe
other obligatorionumber
Ejemplo
<echo>{ 12->min(10) }</echo>
echo 12->min(10)

#number->round(digits?: number) → number

Redondeado a un número de decimales (0 por defecto).

->round(digits?) redondea al entero más cercano, o a digits decimales. Un número exactamente a medio camino se redondea alejándose de cero, como se haría en papel:

<echo value="3.14159->round(digits: 2)" /> <!-- 3.14 because the next digit, 1, rounds down -->
<echo value="2.5->round()" /> <!-- 3 because halfway rounds away from zero -->
<echo value="-2.5->round()" /> <!-- -3 because halfway rounds away from zero on the negative side too -->
<echo value="9.996->round(digits: 2)" /> <!-- 10 because 9.996 is nearer 10.00 than 9.99 -->
echo 3.14159->round(digits: 2)   // 3.14 because the next digit, 1, rounds down
echo 2.5->round()                // 3 because halfway rounds away from zero
echo -2.5->round()             // -3 because halfway rounds away from zero on the negative side too
echo 9.996->round(digits: 2)     // 10 because 9.996 is nearer 10.00 than 9.99
ParámetroRecibe
digits optionalnumber
Ejemplo
<echo>{ 3.14159->round(digits: 2) }</echo>
echo 3.14159->round(digits: 2)

#number->times(fn(i)) → list

Llama a fn(i) para i desde 0 hasta el número, y devuelve los resultados.

->times(fn(i)) llama a la función una vez por cada entero desde 0 hasta uno menos que el número, y devuelve una lista con lo que ha devuelto. Es útil para construir una lista de longitud fija:

<echo value="3->times(fn(i) => $i * $i)" /> <!-- [0, 1, 4] because i is 0, then 1, then 2 -->
<echo value="4->times(fn(i) => &quot;Seat { $i + 1 }&quot;)->last()" /> <!-- 'Seat 4' because i stops at 3 -->
<echo value="0->times(fn(i) => $i)" /> <!-- [] because there is nothing to count -->
echo 3->times(fn(i) => $i * $i)          // [0, 1, 4] because i is 0, then 1, then 2
echo 4->times(fn(i) => "Seat { $i + 1 }")->last() // 'Seat 4' because i stops at 3
echo 0->times(fn(i) => $i)               // [] because there is nothing to count
ParámetroRecibe
fn obligatoriofn
Ejemplo
<echo>{ 3->times(fn(i) => $i * $i) }</echo>
echo 3->times(fn(i) => $i * $i)

#number->to_date() → date

Lee el número como una marca de tiempo Unix, segundos desde el 1970-01-01 UTC: 1795996800->to_date() es el 30 de noviembre de 2026. ->timestamp() convierte una fecha de nuevo en una marca de tiempo.

->to_date() lee el número como una marca de tiempo Unix, el número de segundos desde el inicio del 1 de enero de 1970 en UTC, que es como muchos sistemas y APIs envían las fechas. $date->timestamp() convierte una fecha de nuevo en una marca de tiempo. Solo los enteros pueden convertirse en fechas de este modo; para avanzar una fecha, suma una duración como 3d:

<let name="sent" value="1795996800->to_date()" />
<echo value="$sent->format('d MMMM yyyy')" /> <!-- '30 November 2026' -->
<echo value="$sent->timestamp()" /> <!-- 1795996800 because ->timestamp() reverses ->to_date() -->
$sent = 1795996800->to_date()
echo $sent->format('d MMMM yyyy')   // '30 November 2026'
echo $sent->timestamp()             // 1795996800 because ->timestamp() reverses ->to_date()
Ejemplo
<echo>{ 1795996800->to_date()->timestamp() }</echo>
echo 1795996800->to_date()->timestamp()

#number->to_int() → number

La parte entera.

->to_int() elimina todo lo que va después del punto decimal, dejando solo la parte entera. A diferencia de ->floor(), para un número negativo se acerca a cero:

<echo value="9.99->to_int()" /> <!-- 9 because the .99 is dropped, not rounded -->
<echo value="-3.7->to_int()" /> <!-- -3 because the decimals are dropped, which moves towards zero -->
<echo value="-3.7->floor()" /> <!-- -4 because ->floor() always goes down -->
echo 9.99->to_int()      // 9 because the .99 is dropped, not rounded
echo -3.7->to_int()    // -3 because the decimals are dropped, which moves towards zero
echo -3.7->floor()     // -4 because ->floor() always goes down
Ejemplo
<echo>{ 9.99->to_int() }</echo>
echo 9.99->to_int()

#number->to_number(default?) → number

El propio número.

->to_number(default?) devuelve el propio número. Está para que un valor que puede ser un número o un texto pueda llamar a ->to_number() de cualquier forma. Sobre un texto lee el número escrito en él:

<echo value="42->to_number()" /> <!-- 42 -->
<echo value="'12.5'->to_number() + 1" /> <!-- 13.5 because the text is read as a number first -->
<echo value="'none'->to_number(0)" /> <!-- 0 because 'none' isn't a number, so the default is used -->
echo 42->to_number()                  // 42
echo '12.5'->to_number() + 1          // 13.5 because the text is read as a number first
echo 'none'->to_number(0)             // 0 because 'none' isn't a number, so the default is used
Ejemplo
<echo>{ '42'->to_number() + 1 }</echo>
echo '42'->to_number() + 1

Desde KScript.Math

Estos necesitan <import package="KScript.Math" />import KScript.Math. Consulta KScript.Math.

#number->sqrt() → number KScript.Math

La raíz cuadrada.
Ejemplo
<import package="KScript.Math" />
<echo>{ 16->sqrt() }</echo>
import KScript.Math
echo 16->sqrt()

Métodos de cualquier tipo