KScript documentación
ES

Idioma

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

Tipos y validación

Tipos leídos desde texto

Un tipo con campos y un pattern puede crearse a partir de texto. Los grupos con nombre del patrón rellenan los campos del mismo nombre, y cada uno se convierte al tipo de su campo. fn dentro de un tipo añade un método, que ve los campos:

<import package="KScript.Math" />

<enum name="Unit" values="cm, in, mm" />

<type name="Dimensions" description="A size such as H4cmW12in: height 4 cm, width 12 inches." pattern="/^H(?&lt;height>[\d.]+)(?&lt;height_unit>cm|in|mm)W(?&lt;width>[\d.]+)(?&lt;width_unit>cm|in|mm)$/i">
  <field name="height" type="number" />
  <field name="height_unit" type="Unit" />
  <field name="width" type="number" />
  <field name="width_unit" type="Unit" />
  <fn name="width_in" params="unit: Unit" value="@convert_length(.width, .width_unit, $unit)" />
</type>

<let name="size" type="Dimensions" value="H4cmW12in" />
<echo>{ $size.width } { $size.width_unit } is { $size->width_in(cm) } cm</echo>
import KScript.Math

enum Unit { cm, in, mm }

/// A size such as H4cmW12in: height 4 cm, width 12 inches.
type Dimensions {
  pattern: /^H(?<height>[\d.]+)(?<height_unit>cm|in|mm)W(?<width>[\d.]+)(?<width_unit>cm|in|mm)$/i
  height: number
  height_unit: Unit
  width: number
  width_unit: Unit
  fn width_in(unit: Unit) => @convert_length(.width, .width_unit, $unit)
}

$size: Dimensions = H4cmW12in
echo "{ $size.width } { $size.width_unit } is { $size->width_in(cm) } cm"

Cuando el texto necesita más que un patrón, parse: da una expresión que devuelve un mapa de los campos. Ve el texto como $value y, con un patrón, la coincidencia como $match.