KScript 문서
KO

언어

영어에서 자동 번역되었습니다. 원문은 영어입니다.

타입과 검증

텍스트에서 읽는 타입

필드와 pattern를 가진 타입은 텍스트로부터 만들 수 있습니다. 패턴의 명명된 그룹이 같은 이름의 필드를 채우며, 각 그룹은 해당 필드의 타입으로 변환됩니다. 타입 안의 fn는 필드를 볼 수 있는 메서드를 추가합니다:

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

텍스트에 패턴 이상이 필요할 때는 parse:가 필드의 맵을 반환하는 식을 제공합니다. 이 식은 텍스트를 $value로 보며, 패턴이 있으면 일치 결과를 $match로 봅니다.

Edit this page on GitHub