KScript documentation
FR

Types et validation

Types lus à partir du texte

Un type avec des champs et un pattern peut être créé à partir d'un texte. Les groupes nommés du motif remplissent les champs de même nom, et chacun est converti dans le type de son champ. fn dans un type ajoute une méthode, qui voit les champs :

<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"

Lorsque le texte nécessite plus qu'un motif, parse: fournit une expression qui renvoie une table des champs. Elle voit le texte comme $value et, avec un motif, la correspondance comme $match.