KScript 语言
简介
这是 KScript 2 脚本的参考手册,涵盖每个脚本和页面都具备的核心语言、用于其他功能的导入包,以及适用于所有操作系统的脚本技巧。如果你刚接触 KScript,建议先阅读快速入门。
变量与输出
<let name="count" value="0" /> <!-- declare -->
<let name="people" value="[{ name: 'Joan', age: 82 }]" />
<set name="count" value="$count + 1" /> <!-- change it -->
<set name="count" op="+=" value="1" />
<let name="total" value="$price * $qty" />
<const name="limit" value="10" />
<let name="n" type="int" value="$args[0]" /> <!-- convert, or stop with a clear error -->
<echo>Hello, {$name}! You have { $count } new { $count == 1 ? 'message' : 'messages' }.</echo>
<echo>{ $person.name } is { $person.age }</echo>
<echo>{ $people }</echo> <!-- a map or list of maps prints as indented JSON -->$count = 0 // declare
$people = [{ name: 'Joan', age: 82 }]
$count = $count + 1 // change it
$count += 1
$total = $price * $qty
const $limit = 10
$n: int = $args[0] // convert, or stop with a clear error
echo "Hello, {$name}! You have { $count } new { $count == 1 ? 'message' : 'messages' }."
echo "{ $person.name } is { $person.age }"
echo "{ $people }" // a map or list of maps prints as indented JSON在 echo 中单独输出映射或映射列表时,会打印为缩进的 JSON,在终端中带有颜色(除非设置了 NO_COLOR)。在文本中则保持单行。echo(format: json) 可重新格式化 JSON 文本,->convert(to: json) 则生成紧凑的 JSON。
变量属于其声明所在的代码块。{{ 和 }} 是字面上的花括号。
带类型声明的变量会保留该类型。之后的每次赋值都会被转换为该类型,与第一次赋值的方式相同,否则脚本会在此处停止:
<let name="count" type="int" value="'3'" /> <!-- 3, because '3' reads as an int -->
<set name="count" value="4.0" /> <!-- 4: still an int -->
<set name="count" op="+=" value="1" /> <!-- 5 -->$count: int = '3' // 3, because '3' reads as an int
$count = 4.0 // 4: still an int
$count += 1 // 5此后,$count = 'many' 在编辑器中会报错,运行时也会在此停止:$count must be an int, but got the string 'many'。
"Double quotes"在{ }中插入表达式,位置为echo之后、赋值语句中、返回值中以及调用参数中。在.kscript中,KS6019会检测裸引用并提议用花括号包裹。'Single quotes'会原样保留文本,因此没有需要填充内容的文本应放在其中(KS6020会给出修改建议)。echo之后的引号文本同样会原样输出,包括其中的空格:echo " - { $item }"会输出两个空格。在 XML 中,<echo>与</echo>之间的文本会去除首尾空白,并移除各行共有的缩进;填入其中的值不做处理,但空值不会留下多余空格,且文本末尾永远不会出现换行。
<let name="greeting" value=""Hello { $name }, you have { $count * 2 } points."" />
<let name="label" value="'Write $name to use a variable.'" /> <!-- kept as written -->
<let name="boxes" value=""{ 2 * 3 } boxes, { [1, 2]->count() } lists"" /> <!-- a { } always holds an expression -->
<let name="route" value="'/users/{id}'" /> <!-- text with braces of its own goes in single quotes -->$greeting = "Hello { $name }, you have { $count * 2 } points."
$label = 'Write $name to use a variable.' // kept as written
$boxes = "{ 2 * 3 } boxes, { [1, 2]->count() } lists" // a { } always holds an expression
$route = '/users/{id}' // text with braces of its own goes in single quotes双引号中的{ }总是包含一个表达式,无论它以什么开头:可以是变量、命令、类型({ Order->count() })、数字或括号中的求和。若文本本身含有花括号,例如路由('/users/{id}')、正则模式('\d{3}')、CSS 或翻译文本('Hello {name}'),则应使用单引号,或将花括号双写:"/users/{{id}}"。@sql的文本是唯一的例外:其中的{ }会作为参数传递,而不会直接粘贴(见数据)。
表达式
+ - * / % **、== !=(宽松比较:'3' == 3)、=== !==(严格比较)、< <= > >=、and or not、??、?.、a ? b : c、in、列表字面量[1, 2]与映射字面量{ name: 'Joan' }(列表可用as set转换为集合)、$p.name、$list[0](负索引从末尾计数)、范围0..10与0..100 step 5(不含结束值,也可带步长如0.1)以及1..=10(包含结束值)、match $x { 1 => 'one', _ => 'other' }、->method()、|>和fn(x) => …。使用and与or组合条件。前缀!与not具有相同的优先级和真值判断,因此!$ready、! $ready与not $ready等价。可用于字段(!$user.active)、整个条件(if !($ready and $open) { … })或插值("{ ! null->is_null() }")。写法null->!is_null()会在链式调用的下一环节之前对方法结果取反。XML 中每种比较也都有对应的单词(lt le gt ge eq ne),供引号括起的属性中使用,因为 XML 在此处不能直接写原始的<;简写起始标签可直接接受<和>。在.kscript文件中,这些单词会被报告(KS6012),而kscript check --fix会改写为符号。
用 <、<=、> 或 >= 比较数字与字符串时,如果该字符串可以解析为数字,KScript 会按数值比较。若解析失败,比较结果为 false。比较可以像数学中那样连锁,数学一节对此有所说明。使用 == 判断两个日期是否相等时,只有当它们是同一时刻(包括秒)才相等。
数学
日常数学运算有其自己的符号,每个符号在脚本、模板和数据库查询中的作用都相同。+ 为加法,- 为减法,* 为乘法,/ 为除法,保留小数部分。~/ 为整除,向下取整。% 给出余数,余数的符号与左侧数字一致,%% 像时钟一样循环取模,** 为乘方:
<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运算符按以下顺序结合,从最紧密到最松散,因此 2 + 3 * 4 的结果是 14,因为 * 先于 + 结合:
| 优先级 | 运算符 | 分组 |
|---|---|---|
| 1 | . -> ?. ( ) [ ] |
从左到右 |
| 2 | ** |
从右到左:2 ** 3 ** 2 即 2 ** 9,512 |
| 3 | -x +x |
-2 ** 2的结果是 -4,因为**先结合,因此应写作-(2 ** 2)或(-2) ** 2(KS6023)。 |
| 4 | * / ~/ % %% |
从左到右 |
| 5 | + - |
从左到右 |
| 6 | .. ..= step |
每个表达式只能有一个范围 |
| 7 | |> |
从左到右 |
| 8 | < <= > >= in |
单向链:0 <= $n < 10 |
| 9 | == != === !== |
每个比较一个;要连接更多请使用 and |
| 10 | not, and, or, ??, a ? b : c |
% 与 %% 只有在符号为负时才有区别。余数的符号与左侧一致,与 C# 和 JavaScript 相同。取模的符号与右侧一致,因此会循环:午夜前一小时是 23,而不是 -1。对于时钟、星期以及在列表末尾循环的位置,请使用 %%:
<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~/ 向下取整,而不是向零取整,因此它与 %% 配对使用:($a ~/ $b) * $b + $a %% $b 始终等于 $a。它也适用于时长和金额,并返回普通数字:
<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// 开始一段注释,因此它不能是整数除法。$hours = $minutes // $per_hour 不会处理 $minutes,而 KS6022 会指出这一点,并给出写作 ~/ 的修复方案。
方向相同的比较可以像数学中那样连写,因此范围检查读起来与口头表述一致。中间的每个值只计算一次,链条在第一个为假的比较处停止:
<let name="score" value="42" />
<let name="passed" value="0 <= $score < 100" /> <!-- true because 42 is from 0 up to (not including) 100 -->
<let name="top" value="90 <= $score <= 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连写的比较必须朝同一方向。1 < $n > 0 是错误的,因为它没有说明 1 与 0 的大小关系,应写成 1 < $n and $n > 0。== 和 != 也不能连写:$a == $b == $c 会与 $c 比较出真或假,应写成 $a == $b and $b == $c。括号会中断连写,因此 (1 < $n) == true 比较的是结果。连写在数据库查询中同样适用:Person->where(fn(person) => 18 <= $person.age < 65) 表示 age >= 18 AND age < 65。->between() 已被移除,其错误信息会指出应改用的连写形式。
.. 生成的范围不包含终点,适合从 0 开始计数以及表示列表中的位置。..= 则包含终点,适合从 1 开始计数。将鼠标悬停在任一项上,可以看到范围的起点和终点:
<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与 .. 类似,当范围的终点小于起点时,范围会递减,因此 3..=1 等同于 [3, 2, 1],1..=0 等同于 [1, 0]。若要向上计数到一个可能为 0 的值(如 1..($count + 1)),请保留 ..,当 $count 为 0 时它不会产生任何值。
^ 在 KScript 中不是幂运算(在 C# 和 JavaScript 中它是按位运算符),因此 2 ^ 10 是一个错误,其修复建议会写成 2 ** 10。
位运算通过一个方法 ->bits() 完成,而不是使用符号,因为 & 和 | 很容易被误认为 and 和 or。该方法逐步作用于整数:
<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单独的 &、单独的 |、<< 以及位于两个值之间的 >> 都是错误,错误信息会指出应改用的 ->bits() 调用。& 和 | 会给出修复建议,写成 and 或 or,这通常才是原意。
($hour + 24) % 24是旧的数字取整写法。KS6021建议改用$hour %% 24,它对小于 -24 的数字同样有效。
+=、-=、*=、/=、~/=、%=、%%=、**= 和 ??= 会就地修改变量:$total += 5 等同于 $total = $total + 5。运算符两侧的空格由你决定,但运算符内部的空格会将其拆分:2 * * 10 是一个错误,错误信息会指出 **,其快速修复会删除该空格。
编辑器会在运算符和空格之后列出变量,左侧类型的变量排在前面;将鼠标悬停在运算符上,可以看到它的作用。
使用expression as Type进行带检查的转换,例如$text as int。目标类型也可以是已声明的记录、枚举或精化类型。带检查的转换
控制流
<if $n < 10>
<!-- … -->
</if>
<elif $n < 100>
<!-- … -->
</elif>
<else>
<!-- … -->
</else>
<for each="p" in="$people">
<!-- … -->
</for>
<for each="i" at="n" in="0..10 step 2">
<!-- … -->
</for>
<for each="key, value" in="$map">
<!-- … -->
</for>
<while $queue->count() > 0>
<!-- … -->
<break />
<!-- … -->
<continue />
<!-- … -->
</while>
<match $choice>
<case is="1">
<echo>One</echo>
</case>
<case is="2, 3">
<!-- … -->
</case>
<case when="$it > 9">
<echo>Out of range</echo>
</case>
<default>
<!-- … -->
</default>
</match>if $n < 10 {
// …
} elif $n < 100 {
// …
} else {
// …
}
for p in $people {
// …
}
for i at n in 0..10 step 2 {
// …
}
for key, value in $map {
// …
}
while $queue->count() > 0 {
// …
break
// …
continue
// …
}
match $choice {
1 => echo 'One'
2, 3 => {
// …
}
_ when $it > 9 => echo 'Out of range'
_ => {
// …
}
}match 的每个分支是 pattern => result。模式是一个或多个值(2, 3 =>),或匹配任意值的 _,后面可以跟一个 when 测试(_ when $it > 9 =>)。结果是同一行上的一条语句,或由多条语句组成的 { } 块。作为值使用的 match 以同样方式写分支,每个分支的结果是一个值:$label = match $choice { 1 => 'one', 2, 3 => 'a few', _ => 'many' }。在那里,分支的 { } 块给出其 return 给出的值,分支也可以 throw 而不给出值。分支之间用换行或逗号分隔,采用第一个匹配的分支。在 XML 中,分支是 <case is="2, 3">、<case when="…"> 和 <default>。
单行if
当if只做一件事时,把它写在一行上:条件、=>,然后是语句。它的写法与match的分支以及fn(name) => ...相似,让保护检查和提前退出都只占一行。
<let name="basket" value="['apple', 'plum', 'pear']" />
<let name="budget" value="3" />
<!-- The guard is one line, so the main path stays at the left edge. -->
<if $basket->is_empty()>
<exit />
</if>
<!-- 3 items and a budget of 3: the test is true, so the line prints. -->
<if $basket->count() >= $budget>
<echo>The basket is full</echo>
</if>
<for each="fruit" in="$basket">
<!-- 'plum' is skipped, because continue moves on to the next fruit. -->
<if $fruit == 'plum'>
<continue />
</if>
<echo value="$fruit" />
</for>
<!--
apple
pear
-->$basket = ['apple', 'plum', 'pear']
$budget = 3
// The guard is one line, so the main path stays at the left edge.
if $basket->is_empty() => exit
// 3 items and a budget of 3: the test is true, so the line prints.
if $basket->count() >= $budget => echo 'The basket is full'
for fruit in $basket {
// 'plum' is skipped, because continue moves on to the next fruit.
if $fruit == 'plum' => continue
echo $fruit
}
// apple
// pearelif和else的写法相同,每个分支占一行:
<let name="temperature" value="18" />
<!-- 18 is not below 5, but it is below 20, so 'Mild' is printed. -->
<if $temperature < 5>
<echo>Cold</echo>
</if>
<elif $temperature < 20>
<echo>Mild</echo>
</elif>
<else>
<echo>Warm</echo>
</else>$temperature = 18
// 18 is not below 5, but it is below 20, so 'Mild' is printed.
if $temperature < 5 => echo 'Cold'
elif $temperature < 20 => echo 'Mild'
else => echo 'Warm'=>之后的语句可以是任何能放在一行中的内容:调用(if $continue => @method_call())、赋值(if $count > 2 => $label = 'many')、echo、return、break、continue、throw或exit。它在行尾结束,因此无论哪种写法,if $ready => echo 1; echo 2都会输出2。如需多条语句或循环,请使用match、另一个if或{ }块。括号外第一个=>用于结束条件,因此调用内部的fn(fruit) => ...和@load() catch => false仍属于该调用。if $ready => { }是错误写法:条件后面跟块时不能加箭头。XML没有单行形式,kscript convert会把语句写在<if>之内。
在XML中,<if>、<elif>、<while>和<match>直接在开始标签中书写表达式:<if $user.is_logged_in>是<if test="$user.is_logged_in">的简写,<match $choice>是<match value="$choice">的简写。两种写法在脚本和页面中都可用;当标签还有其他属性时,使用完整写法。在标签内部,<、>和引号无需转义,因此<if $n > 3>和<if $name == "Joan">可以直接使用。>会结束标签,除非它两侧都有空格且条件的后续内容仍在其后,所以应写$n > 3而不是$n>3。kscript convert以及编辑器中的<if>代码片段都使用简写形式。
简写标签使.ks.xml文件成为KScript标记,而非严格的XML:KScript自带的解析器、格式化工具和编辑器支持它,但xmllint等通用XML工具会拒绝它。如果文件必须保持有效的XML,请坚持使用test="…"。
用提前返回代替else
在函数或循环内部,应尽早结束分支,而不是写else:函数中用return,循环中用continue或break(它们只作用于同一函数中的循环,绝不作用于调用它的那个循环)。这样主路径保持在最左侧,每种特殊情况都会先被处理。
<fn name="grade" params="score: number">
<if $score >= 90>
<return value="'A'" />
</if>
<if $score >= 75>
<return value="'B'" />
</if>
<return value="'C'" />
</fn>
<echo>{ @grade(82) }</echo>fn grade(score: number) {
if $score >= 90 => return 'A'
if $score >= 75 => return 'B'
return 'C'
}
echo "{ @grade(82) }"kscript check和编辑器会对else与elif发出 KS6001 警告;当其前面的每个分支都已以return、break、continue、throw或exit结束时,脚本顶部也会发出该警告。快速修复会删除else(或将elif改为独立的if),并且当该链式结构是函数或循环的最后一条语句时,会自动添加return或continue。页面、<live>代码块以及for…else(用于空列表)不会被标记,因为此时没有可返回的内容。KS6001 来自默认的标准,即kscript:recommended。若要为某个项目关闭它,请在kscript.json中(或在项目共用的标准中)设置"lint": { "rules": { "KS6001": "off" } }。
未使用的代码
kscript check和编辑器还会指出不起作用的代码。在编辑器中,这些代码会以淡色显示,并提供快速修复:删除它,或在名称前加上前导_,以表明它被有意标记为未使用(_名称永远不会被报告)。
| 代码 | 标记的内容 |
|---|---|
| KS6002 | 一个没有被任何代码调用的函数。脚本的 main 函数 从不会被报告,因为它会自行运行。来自项目其他文件的调用同样算数:例如另一个脚本导入并调用的库函数、路由文件所指定的控制器(to="people.show",或其 index、store、show、update 和 destroy 对应的 <Resource to="people">),以及 kscript.json 中指定的中间件。仅调用自身的函数仍然属于未使用。 |
| KS6003 | 其值从未被读取的变量、常量或循环变量,包括仅被赋值过的变量。脚本顶层的常量与函数一样会被导出,因此当导入它的文件使用它们时,它们被视为已使用。在页面中,只检查函数自身的变量,因为布局或组件可能读取其他变量。 |
| KS6004 | 函数体从未读取的函数参数。对于lambda,只标记最后一个被读取的参数之后的参数,因为由调用者决定传入什么:若要保留参数位置,请写fn(_y) => ...。 |
| KS6005 | 未被使用的导入:as别名、names="..."中的名称、整个脚本,或者其任何元素、命令、方法或变量都未出现的包。 |
| KS6006 | 这不是未使用的代码,而是一条风格提示:在.kscript文件中,用一个字符串写成的名称列表(Middleware(use: "log, cors"))。应改写为数组,use: [log, cors];快速修复会自动完成此操作。XML属性本身就是文本,因此use="log, cors"在那里是可以接受的。 |
| KS6008 | 这同样不是未使用的代码:它指的是项目中的某个脚本声明了第二个类型、模型、枚举或错误类型。每个类型都应放在以其命名的单独文件中,并在使用处导入;警告会说明应将其移动到哪里(types/order-status.kscript)。与文件同名的类型可以保留。项目之外的脚本不做检查。 |
项目是指最近的kscript.json所在的文件夹及其下的所有内容(隐藏文件夹、bin、obj和node_modules会被跳过)。项目之外的脚本会与其所在文件夹中的其他文件进行比对。若函数是项目外部使用的API的一部分,可以在其文档注释中加上@public来声明:
<!---
Kept for scripts that still call it.
@public
-->
<fn name="titlecase" params="text: string" value="$text->upper()" />/// Kept for scripts that still call it.
/// @public
fn titlecase(text: string) => $text->upper()与 KS6001 一样,这些规则来自默认的标准,即kscript:recommended,以警告形式出现(kscript:strict会将其变为错误)。项目可以在kscript.json中更改或关闭其中每一条,例如"lint": { "rules": { "KS6004": "off" } }。
函数
<fn name="greet" params="who: string, greeting = 'Hello'">
<return value="$greeting + ', ' + $who + '!'" />
</fn>
<fn name="square" params="n: number" value="$n * $n" />
<echo>{ @greet('World') } { 4 |> @square() }</echo>
<do>@greet('Kyle')</do>
<spawn fn="background_job" />fn greet(who: string, greeting = 'Hello') {
return $greeting + ', ' + $who + '!'
}
fn square(n: number) => $n * $n
echo "{ @greet('World') } { 4 |> @square() }"
@greet('Kyle')
spawn(fn: @background_job)函数可以在声明之前调用、可以递归,也可以作为参数传递:@square 本身就是该函数。Lambda 同样是值,并以相同的简单方式声明其参数:$by_age = fn(a, b) => $a.age - $b.age。
lambda 的参数可以带类型,写法与函数相同。参数会被转换为该类型,否则脚本停止,与函数的行为一致:
<let name="area" value="fn(width: number, height: number) => $width * $height" />
<echo value="$area('3', 4)" /> <!-- 12: '3' reads as a number -->
<echo value="['a', 'b']->map(fn(s: string) => $s->upper())" />$area = fn(width: number, height: number) => $width * $height
echo $area('3', 4) // 12: '3' reads as a number
echo ['a', 'b']->map(fn(s: string) => $s->upper())简短的函数会对每个元素读取字段或调用方法。它以 . 或 -> 开头,代表当前元素,可用于任何需要函数的地方:
<let name="urgent" value="$orders->sort(by: .priority)->filter(.paid)" />
<let name="by_shop" value="$orders->group_by(.shop.name)" />
<let name="lines" value="$lines->map(->trim()->upper())" />$urgent = $orders->sort(by: .priority)->filter(.paid)
$by_shop = $orders->group_by(.shop.name)
$lines = $lines->map(->trim()->upper()).priority 等同于 fn(order) => $order.priority,->trim() 等同于 fn(line) => $line->trim()。简短的函数是由字段和方法调用组成的单个链式表达式。对于更复杂的情况,例如 $order.price > 10,请改写为 fn(order) => …。
main 函数
脚本可以将其工作放在名为 main 的函数中。当该脚本是被运行的脚本时,main 会在顶层代码运行后自动运行,因此顶层代码负责设置,而由 main 完成实际工作:
<!-- greet.kscript, run with: kscript greet.kscript Ada Grace -->
<let name="greeting" value="'Hello'" /> <!-- the top-level code runs first -->
<fn name="main" params="args: list">
<!-- $args is ['Ada', 'Grace'], the words after the script's name -->
<for each="name" in="$args">
<echo>{ $greeting }, { $name }!</echo> <!-- Hello, Ada! then Hello, Grace! -->
</for>
</fn>// greet.kscript, run with: kscript greet.kscript Ada Grace
$greeting = 'Hello' // the top-level code runs first
fn main(args: list) {
// $args is ['Ada', 'Grace'], the words after the script's name
for name in $args {
echo "{ $greeting }, { $name }!" // Hello, Ada! then Hello, Grace!
}
}- 其参数是可选的。
fn main()的运行方式相同;fn main(args: list)接收脚本的参数,与$args的列表相同。第二个参数需要默认值,因为不会传入其他内容:fn main(first, second)会报错(KS5004)。 - 它返回的是退出码。
main返回的整数会使脚本以该退出码结束,exit也是如此,因此 shell 或 CI 任务可以判断运行情况。其他任何返回值,或不返回值,退出码均为 0:
<fn name="main" params="args: list" returns="int">
<if $args->count() == 0>
<echo>Name a file to read.</echo>
<return value="2" /> <!-- exit code 2: the script wasn't given what it needs -->
</if>
<echo>Reading { $args[0] }</echo>
<return value="0" /> <!-- exit code 0: all went well -->
</fn>fn main(args: list): int {
if $args->count() == 0 {
echo 'Name a file to read.'
return 2 // exit code 2: the script wasn't given what it needs
}
echo "Reading { $args[0] }"
return 0 // exit code 0: all went well
}- 仅适用于被运行的脚本。
main属于你运行的脚本:kscript run、kscript greet.kscript、已编译的程序、调试器以及编辑器的运行命令都会调用它。被导入的脚本会运行其顶层代码,但从不运行main,因此库可以保留一个main,用于单独试运行。 - 仅限顶层。在另一个函数、类型或测试文件中的
fn main只是普通函数。 - 从不视为未使用。没有任何代码调用
main,因此kscript check和编辑器从不会将其报告为未使用(KS6002)。如果顶层代码也调用了它,它们会发出警告,因为这样它会运行两次(KS5019);请删除该调用,快速修复会完成此操作。
在 kscript.json 中使用 app.main_function 可为项目中的每个脚本赋予另一个名称:
{
"app": { "main_function": "start" } // fn start runs by itself; a fn main is then an ordinary function
}块函数
当函数需要不止一个表达式时,请使用代码块代替 =>。该代码块包含语句,与 fn name() { } 的函数体相同,并由 return 给出函数的结果:
<let name="prices" value="[3, 7, 12]" />
<let name="with_tax">$prices->map(fn(price) {
$taxed = $price * 1.5 // 4.5 for the first price, because 3 * 1.5 is 4.5
return $taxed->round() // 5, because 4.5 rounds up
})</let>
<!-- $with_tax is [5, 11, 18]: the block ran once for each price -->$prices = [3, 7, 12]
$with_tax = $prices->map(fn(price) {
$taxed = $price * 1.5 // 4.5 for the first price, because 3 * 1.5 is 4.5
return $taxed->round() // 5, because 4.5 rounds up
})
// $with_tax is [5, 11, 18]: the block ran once for each price参数的类型由调用处推断,与 fn(price) => … 中的情况相同:这里 $price 是数字,因为 $prices 是数字列表,因此编辑器会在 $price-> 之后建议数字方法,并显示 with_tax: number[]。
代码块可以用 if 做判断,也可以用 return 提前退出:
<let name="scores" value="[42, 97, 61, 88]" />
<let name="passed">$scores->filter(fn(score) {
if $score < 60 {
return false // 42 is dropped here, because it is under 60
}
return $score % 2 == 0 // 97 and 61 are dropped, because they are odd
})</let>
<!-- $passed is [88] -->$scores = [42, 97, 61, 88]
$passed = $scores->filter(fn(score) {
if $score < 60 {
return false // 42 is dropped here, because it is under 60
}
return $score % 2 == 0 // 97 and 61 are dropped, because they are odd
})
// $passed is [88]带两个参数的函数(例如 ->reduce(fn(total, item), initial?))同样可以接受代码块:
<let name="basket" value="[{ name: 'apple', cost: 2 }, { name: 'melon', cost: 5 }]" />
<let name="total">$basket->reduce(fn(sum, item) {
return $sum + $item.cost // 2 after the apple, then 7, because the melon adds 5
}, 0)</let>
<!-- $total is 7 -->$basket = [{ name: 'apple', cost: 2 }, { name: 'melon', cost: 5 }]
$total = $basket->reduce(fn(sum, item) {
return $sum + $item.cost // 2 after the apple, then 7, because the melon adds 5
}, 0)
// $total is 7以 return 结束的代码块会返回 null,适用于 ->each() 这类只关心代码块所执行操作的场景。在其他场景中,调用会使用代码块的返回值,因此空的或从不返回值的代码块是错误的,无论在编辑器中、在 kscript check 中还是运行时都会报错:
<let name="words" value="['fig', 'kiwi']" />
<let name="longest">$words->common(1, by: fn(word) {
})</let>
<!-- Error: This fn block is empty, so it gives null each time it is called, and 'by' uses what it gives. -->$words = ['fig', 'kiwi']
$longest = $words->common(1, by: fn(word) {
})
// Error: This fn block is empty, so it gives null each time it is called, and 'by' uses what it gives.代码块可以读取并修改其周围的变量,它所创建的变量则只在代码块内部有效:
<let name="seen" value="0" />
<do>['x', 'y', 'z']->each(fn(letter) {
$seen = $seen + 1 // the outer $seen goes up, because the block changes the variable around it
$shout = $letter->upper() // $shout exists only inside the block
echo $shout // X, then Y, then Z, because the block runs once per letter
})</do>
<!-- $seen is 3 -->$seen = 0
['x', 'y', 'z']->each(fn(letter) {
$seen = $seen + 1 // the outer $seen goes up, because the block changes the variable around it
$shout = $letter->upper() // $shout exists only inside the block
echo $shout // X, then Y, then Z, because the block runs once per letter
})
// $seen is 3块函数与其他函数一样是一个值,因此可以保存在变量中并被调用:先写 $greet = fn(name) { … },再调用 $greet('Ada')。块函数可用于 .kscript 文件。XML 属性无法容纳语句,因此在那里应写成 fn(n) => value,或者声明一个 <fn> 并将其作为 @name 传递。数据库查询的条件(->where(fn(u) => $u.age >= 18))会被转换为 SQL,因此它必须保持为单个表达式。
声明为 any 的参数可以接受任何值。对其进行的方法调用会使用该值的实际类型。例如,$key->trim() 会去除字符串的首尾空白,对数字则会报错,并且在该类型存在自己的 trim() 时会调用它。对于字符串规范化,请写成 fn trim_key(key: string) => $key->trim()。这样编辑器便可推断出字符串的返回类型。
命名参数
任何调用都可以按任意顺序为参数命名:内置命令、方法、你自己定义的 fn 函数以及 Lambda 均可。
<echo>{ @known_folder(name: 'downloads') }</echo>
<echo>{ @greet(greeting: 'Hi', who: 'Kyle') }</echo>
<echo>{ @range(1, step: 2, end: 10) }</echo>
<echo>{ 'abc'->pad(char: '*', width: 6, start) }</echo>
<echo>{ @join_path(base: $folder, ['archive', $name]) }</echo>echo "{ @known_folder(name: 'downloads') }"
echo "{ @greet(greeting: 'Hi', who: 'Kyle') }"
echo "{ @range(1, step: 2, end: 10) }"
echo "{ 'abc'->pad(char: '*', width: 6, start) }"
echo "{ @join_path(base: $folder, ['archive', $name]) }"位置参数按顺序填充参数,每个 name: value 则填充同名的参数,因此你可以跳过中间的可选参数。写在命名参数之后的位置参数会填充第一个仍为空的参数,@join_path(base: $folder, [...]) 的读法即是如此。为不存在的参数命名,或为同一参数重复赋值,都会报错,并附带“你是否想要”的提示。编辑器会在 ( 或 , 之后补全参数名。
互斥组
部分参数是互斥的选项:一次调用只能传入其中之一。用 | 连接它们的名称:
<fn name="file" params="note_id: int, add|remove: string, notify: bool = true">
<let name="change" value="$add != null ? "Added { $add }" : "Removed { $remove }"" />
<let name="told" value="$notify ? ', and told its owner' : ''" />
<return value=""{ $change } on note { $note_id }{ $told }"" />
</fn>
<echo value="@file(4, add: 'plan.png')" />
<echo value="@file(4, remove: 'old.png', not notify)" />fn file(note_id: int, add|remove: string, notify: bool = true) {
$change = $add != null ? "Added { $add }" : "Removed { $remove }"
$told = $notify ? ', and told its owner' : ''
return "{ $change } on note { $note_id }{ $told }"
}
echo @file(4, add: 'plan.png')
echo @file(4, remove: 'old.png', not notify)@file(4, add: $a, remove: $b) 是错误的(“@file() 只接受 add: 或 remove:,不能两者都传”),@file(4) 同样是错误的(“需要 add: 或 remove:”)。kscript check 会在代码运行前同时报告这两种情况。组内成员始终需要命名,调用时未传入的成员在函数体中为 null。为其中某个成员传入 null(或 false)等同于未传入。
| 写法 | 含义 |
|---|---|
add|remove: file |
add 与 remove 两个文件中恰好一个。 |
at|after?: date |
至多一个:最后一个名称后的 ? 允许调用时两者都不传。 |
text: string | template: Template |
恰好一个,且各自有自己的类型。 |
(text: string | template: Template)? |
同样的含义,用方括号表示,其中 ? 表示至多一个。 |
当一个组的成员类型不同,而该组旁边还有其他参数时,需要使用方括号,以明确组的结束位置:fn send(to: email, (text: string | template: Template), at|after?: date)。任何组都允许加方括号。组内成员不能有自己的默认值。
内置命令也使用互斥组。@api() 接受 post:、put:、patch: 和 delete: 之一,作业的 ->dispatch() 接受 delay: 或 at:,二者不能同时使用。签名帮助会将一个组显示为一个位置,一旦写入了其中一个成员,补全便不再提供组内其他成员,而且编辑器会为一个组的名称使用同一种颜色。
标志
布尔类型的参数可以写成单独的词:recursive 将其设为真,not recursive 将其设为假,因此调用读起来像一句话。
<let name="all" value="@files($folder, pattern: '*.txt', recursive)" />
<echo>{ $data->convert(to: json, indented) }</echo>
<fn name="save" params="path: string, overwrite: bool = false">
<!-- … -->
</fn>
<do>@save('out.txt', overwrite)</do>$all = @files($folder, pattern: '*.txt', recursive)
echo "{ $data->convert(to: json, indented) }"
fn save(path: string, overwrite: bool = false) {
// …
}
@save('out.txt', overwrite)写成overwrite: true或recursive: false同样可行,但编辑器会建议改用标志(KS6024),并给出将其改写为overwrite或not recursive的修复方案。
参数类型
每个实参都必须是其参数所接受的值。一条规则决定了这一点,编辑器、kscript check 和运行时都应用同一规则,因此它们会在代码运行前以相同的措辞报告同样的错误:
<let name="rolls" value="[4, 6, 6, 2]" />
<do>$rolls->common(1, least)</do> <!-- [2]: least on its own is true -->
<do>$rolls->common(1, not least)</do> <!-- [6]: not least is false -->
<do>$rolls->common(1, least: 'yes')</do> <!-- [2]: text that reads as true or false is converted -->
<do>$rolls->common('1')</do> <!-- [6]: text that reads as a number is converted -->
<do>$rolls->common(1, least: {})</do>
<!-- Error: The 'least' argument needs true or false, but this is a map. It is a flag: write least on its own for true, or not least for false. -->
<do>$rolls->common(fn() => 2)</do>
<!-- Error: The 'count' argument needs a number, but this is a function. -->
<do>$rolls->common(1, by: 3)</do>
<!-- Error: The 'by' argument needs a function, but this is a number. -->
<do>['fig']->union('fig')</do>
<!-- Error: The 'other' argument needs a list, but 'fig' is text. -->$rolls = [4, 6, 6, 2]
$rolls->common(1, least) // [2]: least on its own is true
$rolls->common(1, not least) // [6]: not least is false
$rolls->common(1, least: 'yes') // [2]: text that reads as true or false is converted
$rolls->common('1') // [6]: text that reads as a number is converted
$rolls->common(1, least: {})
// Error: The 'least' argument needs true or false, but this is a map. It is a flag: write least on its own for true, or not least for false.
$rolls->common(fn() => 2)
// Error: The 'count' argument needs a number, but this is a function.
$rolls->common(1, by: 3)
// Error: The 'by' argument needs a function, but this is a number.
['fig']->union('fig')
// Error: The 'other' argument needs a list, but 'fig' is text.| 参数接受 | 同时也接受 | 从不接受 |
|---|---|---|
文本(string) |
以文本形式写出的数字或真/假 | 列表、映射或函数 |
数字(number、int、float) |
可被读作数字的文本,例如 '3' |
其他文本、真/假、列表、映射或函数 |
真或假(bool) |
可被读作真或假的文本,例如 'yes' |
数字、列表、映射或函数 |
| 列表、映射或函数 | 其他任何值 |
你声明的函数对文本更为严格:声明为 string 的参数或结果只接受文本。数字或真/假在编辑器中、在 kscript check 中以及运行时都是错误,因此传入错误值的调用无法悄悄将其转换为文本。请将调用中写出的值用引号括起来,或用 ->to_string() 将数字转换为文本。编辑器会将这两种做法都作为快速修复提供。
<fn name="count_trees" params="input: string" value="$input->grid()->count()" />
<do>@count_trees(1)</do>
<!-- Error: The 'input' argument needs string, but this value is a number, not text. -->
<do>@count_trees('1')</do> <!-- fine: '1' is text -->
<let name="trees" value="3" />
<do>@count_trees($trees->to_string())</do> <!-- fine: the number 3, turned into the text '3' -->fn count_trees(input: string) => $input->grid()->count()
@count_trees(1)
// Error: The 'input' argument needs string, but this value is a number, not text.
@count_trees('1') // fine: '1' is text
$trees = 3
@count_trees($trees->to_string()) // fine: the number 3, turned into the text '3'一条属于某个已声明类型的记录,会按照参数、结果或带类型变量所声明的类型进行检查。如果记录缺少该类型的某个必需字段,则在脚本运行前即报错,运行时的情况也是如此:
<type name="Post">
<field name="title" type="string" />
</type>
<type name="Comment">
<field name="body" type="string" />
</type>
<fn name="headline" params="post: Post" value="$post.title->upper()" />
<echo value="@headline(Comment(body: 'First!'))" />
<!-- Error: The 'post' argument needs Post, but this value is a Comment, which has no title field. -->type Post {
title: string
}
type Comment {
body: string
}
fn headline(post: Post) => $post.title->upper()
echo @headline(Comment(body: 'First!'))
// Error: The 'post' argument needs Post, but this value is a Comment, which has no title field.{ } 始终是映射,即使它写在参数名后面的两行中,因此下一行的 least: { 和 } 是映射而不是代码块。编辑器会提供将 least: { } 替换为 least 的选项。
类型参数
对任意类型都以相同方式工作的函数,会在其名称后的尖括号中指明类型,并在其参数和结果中使用该类型。调用时会根据所传入的内容来确定类型:
<fn name="first" generics="T" params="items: T[]" returns="T">
<return value="$items[0]" />
</fn>
<fn name="same" generics="T" params="a: T, b: T" returns="bool" value="$a == $b" />
<echo value="@first([3, 4])->round()" /> <!-- 3: @first() of a list of numbers is a number -->
<echo value="@first(['fig'])->upper()" /> <!-- FIG -->
<echo value="@same('a', 'b')" /> <!-- false -->fn first<T>(items: T[]): T {
return $items[0]
}
fn same<T>(a: T, b: T): bool => $a == $b
echo @first([3, 4])->round() // 3: @first() of a list of numbers is a number
echo @first(['fig'])->upper() // FIG
echo @same('a', 'b') // false每次调用为每个类型参数指定一个类型。@same(1, 'x') 在编辑器、kscript check 中以及运行时都会报错,因为 a 会使 T 成为数字,而 b 是文本。若结果不是调用所指定的类型 T,同样会报错。在函数内部,T 可以是任意类型,因此 $items[0] 无需检查。多个类型参数用逗号分隔书写:fn pair<K, V>(key: K, value: V)。在 XML 中,它们放在 generics 属性中:<fn name="first" generics="T" params="items: T[]" returns="T">。
尾随逗号
列表中的项之间用逗号分隔。只有当列表每行写一项时,才允许在最后一项后加逗号,这样增加一项时只需改动一行。若在同一行的结束括号前加逗号,则在任何类型的列表中都是错误的:
<let>$label = fn(name,) => $name</let> <!-- Error: Nothing follows this comma. -->
<let>$sizes = [1, 2,]</let> <!-- Error, and the same for { size: 1, } and ->take(2,) -->
<set name="sizes">[
1,
2, // fine: the list is written one per line
]</set>$label = fn(name,) => $name // Error: Nothing follows this comma.
$sizes = [1, 2,] // Error, and the same for { size: 1, } and ->take(2,)
$sizes = [
1,
2, // fine: the list is written one per line
]枚举与常量
enum 用于声明一组命名值,const 用于声明一个不可更改的值。
<enum name="Size" values="small, medium, large" />
<const name="max_items" value="10" />
<fn name="pack" params="size: Size, gift: bool = false" value="'Packing ' + $size" />
<echo>{ @pack(.large) } { @pack(size: .small, gift) } { Size.medium }</echo>enum Size { small, medium, large }
const $max_items = 10
fn pack(size: Size, gift: bool = false) => 'Packing ' + $size
echo "{ @pack(.large) } { @pack(size: .small, gift) } { Size.medium }"长枚举可以每行放一个值,且不需要逗号,就像类型每行放一个字段一样。kscript fmt 会把能放进行宽的枚举放在同一行,较长的枚举则每行放一个值:
<enum name="Topping" values="mozzarella
pepperoni
mushrooms
green_peppers
black_olives
pineapple
jalapenos" />enum Topping {
mozzarella
pepperoni
mushrooms
green_peppers
black_olives
pineapple
jalapenos
}在已知类型的情况下,枚举的值前面要加一个前导点:.large 即 Size.large,因为 size 是 Size(参见下文的前导点)。若没有任何信息说明类型,则需完整书写:Size.medium。枚举的列表使用枚举值的数组:使用 fn pack_all(sizes: Size[]) 时,写作 @pack_all([.large, .small])。内置命令也有单词参数,这些单词直接书写,不加点:@known_folder(downloads) 接受 home、desktop、documents、downloads、music、pictures、videos、appdata 或 temp。Size 本身是一个从每个名称映射到其自身的映射,因此 'large' in Size 可用于检查某个值。顶层的 <const> 和 <enum> 声明会导出给导入该文件的脚本。
前导点: .name
以点号开头的名称是所在位置所期望的类型的成员。当周围的代码已经说明了类型时,可以省去写类型名称:
<enum name="NoteColor" values="yellow, pink, blue, red" />
<type name="Note">
<field name="text" type="string" />
<field name="color" type="NoteColor" default=".yellow" />
<fn name="label" value=".text->upper()" />
<fn name="urgent" value=".color == .red" />
<fn name="kind" returns="string" value="match .color {
.red => 'Urgent'
_ => 'Normal'
}" />
</type>
<fn name="paint" params="color: NoteColor" returns="string" value=""painted { $color }"" />
<let name="note" value="Note(text: 'milk', color: .pink)" />
<echo>{ $note->label() } { $note->kind() } { $note->urgent() } { @paint(color: .blue) }</echo>
<let name="people" value="[{ name: 'Ann', age: 31 }, { name: 'Bo', age: 25 }]" />
<echo value="$people->sort(by: .age)->map(.name)" />enum NoteColor { yellow, pink, blue, red }
type Note {
text: string
color: NoteColor = .yellow
fn label() => .text->upper()
fn urgent() => .color == .red
fn kind(): string => match .color {
.red => 'Urgent'
_ => 'Normal'
}
}
fn paint(color: NoteColor): string => "painted { $color }"
$note = Note(text: 'milk', color: .pink)
echo "{ $note->label() } { $note->kind() } { $note->urgent() } { @paint(color: .blue) }"
$people = [{ name: 'Ann', age: 31 }, { name: 'Bo', age: 25 }]
echo $people->sort(by: .age)->map(.name)点号的含义按以下顺序读取:
- 一个带类型的槽位。 参数、字段的默认值、比较、匹配分支、列表项,或接受枚举的带类型
fn的返回值:.pink即该枚举的值。接受函数的槽位(如->map(.name))会读取每个项目的该字段。 - 循环中的项,位于
for循环内。 在for account in $accounts { ... }中,.id的值为$account.id,.name = 'Ann'用于设置该项的字段。在嵌套循环中,同名的最内层项优先,因此内层循环的.label与外层循环的.id可以并列使用。while循环没有项,因此不会添加任何内容。 - 记录自身,在其自身的方法内。 在
type、model、extend或组件方法中,.text是记录自身的字段,.save()调用其自身的方法。.count += 1和.color = .red用于设置其字段。 - 这些都不是。
$c = .red是一个错误,.red needs a type here,快速修复会把它完整写出:NoteColor.red。
先尝试槽位。在方法内部,@paint(color: .red) 即为 NoteColor.red,即使记录中有名为 red 的字段也是如此。枚举中没有的名称属于记录自身,因此 fn current(): NoteColor => .color 返回记录的 color。两者都没有的名称则会报错。
循环的 item 位于 record 之前。在遍历带有 title 的行的方法中,.title 属于该行,而记录自身的则写作 $this.title;检查器会指出这一点并提供该修复方法。
<type name="Tag">
<field name="label" type="string" />
</type>
<type name="Row">
<field name="id" type="int" />
<field name="name" type="string" />
<field name="tags" type="Tag[]" default="[]" />
</type>
<let name="rows" type="Row[]" value="[Row(id: 1, name: 'Ann', tags: [Tag(label: 'new')])]" />
<for each="row" in="$rows">
<echo>{ .id } { .name->upper() }</echo>
<for each="tag" in=".tags">
<echo>{ .id } { .label }</echo>
</for>
</for>type Tag {
label: string
}
type Row {
id: int
name: string
tags: Tag[] = []
}
$rows: Row[] = [Row(id: 1, name: 'Ann', tags: [Tag(label: 'new')])]
for row in $rows {
echo "{ .id } { .name->upper() }"
for tag in .tags {
echo "{ .id } { .label }"
}
}在值的位置输入 . 时,会精确提示适合填入的内容:在有类型的位置提示枚举的值;在循环中提示循环项的字段(然后是外层循环的字段,最后是记录的字段);在方法中提示记录的字段和方法。将鼠标悬停在某个值上,会显示它所代表的含义,例如 NoteColor.pink。
类型化数据
type用于声明某些数据(例如 API 响应)的结构。经过它的数据会被检查并转换为记录:这是一种知道自身类型的映射,因此编辑器能够补全其字段,且像$repo.stras这样的拼写错误会被捕获。字段也可以是email、password、handle、uuid或regex,类型还可以为其他类型添加规则或与其他类型合并。参见类型与校验。
类型是一个代码块,每行一个字段,name: type:
<type name="User">
<field name="login" type="string" />
<field name="id" type="int" />
</type>
<type name="Repo">
<field name="name" type="string" />
<field name="stars" type="int" from="stargazers_count" />
<field name="owner" type="User" />
</type>
<let name="repo" value="Repo({ name: 'kscript', stargazers_count: 12, owner: { login: 'kyle', id: 1 } })" />
<echo>{ $repo.name } has { $repo.stars } stars, owned by { $repo.owner.login }</echo>type User {
login: string
id: int
}
type Repo {
name: string
stars: int from stargazers_count
owner: User
}
$repo = Repo({ name: 'kscript', stargazers_count: 12, owner: { login: 'kyle', id: 1 } })
echo "{ $repo.name } has { $repo.stars } stars, owned by { $repo.owner.login }"stars: int from stargazers_count 从名称不同的键中读取字段,owner: User 是另一个类型,因此嵌套的数据也会经过检查并转换为 User 记录。Repo(data) 将映射、映射列表或 JSON 文本进行映射。
使用 $.name 在当前作用域中查找某个值。它解析名称的方式与 $name 相同,包括函数参数、局部变量或组件字段。
方法签名
类型可以声明一个方法而不编写其方法体:在 fn 行末尾使用 ; 代替 => 或 { } 的位置。这一行即为方法签名,而 extends 此类型的其他类型必须实现它。方法名后的 ?(如 fn details?(): string;)会使该方法变为可选。编辑器和本文档会以斜体显示签名行,便于一眼区分它们与带方法体的方法。检查器会报告任何缺失的必需方法,或其参数名称、参数类型、返回类型不匹配的情况。
<type name="Summary">
<fn name="label" params="prefix: string" returns="string" signature=";" />
<fn name="details" optional="?" returns="string" signature=";" />
</type>
<type name="NoteSummary" extends="Summary">
<field name="title" type="string" />
<fn name="label" params="prefix: string" returns="string" value="$prefix + .title" />
</type>type Summary {
fn label(prefix: string): string;
fn details?(): string;
}
type NoteSummary extends Summary {
title: string
fn label(prefix: string): string => $prefix + .title
}字段行
字段行的格式为 name[?][: type] [from path] [= default | => value]。除名称外,每个部分都是可选的。带值但不带类型的字段可以在冒号后直接书写值,如 layout: ```text ... ``` 或 symbols: { '#': '#' },并从该值推断其类型:
<enum name="Visibility" values="public, private, internal" />
<type name="Repo" description="A GitHub repository.">
<field name="name" type="string" />
<field name="stars" type="int" from="stargazers_count" description="How many people starred it." />
<field name="owner" type="User" />
<field name="owner_name" type="string" from="owner.login" />
<field name="topics" type="string[]" default="[]" />
<field name="license?" type="string" from="license.name" />
<field name="visibility" type="Visibility" />
<field name="updated" type="date" from="updated_at" />
<field name="label" value="$name + ' (' + $stars + ' stars)'" />
</type>enum Visibility { public, private, internal }
/// A GitHub repository.
type Repo {
name: string
/// How many people starred it.
stars: int from stargazers_count
owner: User
owner_name: string from owner.login
topics: string[] = []
license?: string from license.name
visibility: Visibility
updated: date from updated_at
label => $name + ' (' + $stars + ' stars)'
}| 部分 | 作用 |
|---|---|
: type |
内置类型(string、int、float、number、bool、date、list、set、map、fn、any、email、password、handle、uuid、regex)、某个 enum、另一个 type、表示列表的 T[]、表示 T 集合的 set(of: T)。可在方括号中添加规则:string(min: 1)。若不指定类型,该字段接受任何值。 |
名称后的 ? |
该值可以缺失或为 null。这是将字段标记为可选的唯一方式,适用于 type、model、error 和 job:使用 license?: string,而不是 license: string?(KS6014,附带快速修复)。T? 适用于并非字段自身类型的情况,例如可能为 null 的参数:fn show(repo: Repo?)。 |
from path |
当值不在字段名对应的位置时,从何处读取:stargazers_count、owner.login、items[0].name。嵌套数据会被展平。包含空格的路径需加引号。 |
= default |
数据中没有该值时使用的值。此时字段为可选。 |
=> value |
根据其他字段(即 $name、$stars 等)计算该字段,而不是读取它。 |
行上方的 /// |
在悬停和补全时显示。 |
类型本身可在方括号中接受选项:type Repo(extra: error) { … }。extra用于说明对类型未列出的键如何处理:drop(默认)、keep或error。path: 'data/repo.json'会从已保存的数据样本中提取字段:对象会变为嵌套类型,只有部分列表项具有的键会变为可选。代码块中的行会替换其所指明的采样字段。类型之间可以以任意顺序相互引用,也可以引用自身,顶层类型会导出给导入该文件的脚本。在项目中,应为每个类型分配单独的文件(types/repo.kscript、types/owner.kscript),并导入其使用的类型:在types/repo.kscript顶部写import "owner.kscript"(参见每个类型一个文件)。
小型类型也可以写在一行中,字段的写法类似 fn 参数:type Point(fields: [x: int, y: int])。kscript convert 则将其写成代码块形式。
在 XML 中,类型是 <type name="Repo">,每行对应一个 <field name="stars" type="int" from="stargazers_count" /> 元素;单行形式则使用 fields="..." 属性。将示例切换为 XML 即可查看。
带类型的列表保留其项类型
声明了项类型 $scores: int[] = [90, 72] 的列表会保留该类型:$scores[0] = '85' 会存入数字 85,而 $scores[1] = 'high' 会停止运行,并显示 "An item of $scores must be an int"。kscript check 和编辑器会报告就地写入的、不可能属于该类型的值(KS5012)。
可能为 null 的值
使用 ? 书写的类型表示该值可能为 null:声明为 fn find(slug: string): Post? 的函数、post: Post? 参数、$post: Post? = ... 变量,或没有默认值的 license?: string 字段。对 null 读取字段或对其调用方法会使脚本停止,因此当此类值在任何检查之前被使用时,kscript check 和编辑器会发出警告(KS5018):
<type name="Post">
<field name="title" type="string" />
<field name="summary?" type="string" />
</type>
<fn name="find" params="slug: string" returns="Post?">
<return value="$slug == 'hello' ? Post(title: 'Hello') : null" />
</fn>
<let name="post" value="@find('hello')" />
<if $post == null>
<exit />
</if>
<echo value="$post.title" /> <!-- fine: the line above stops when it is null -->
<echo value="($post.summary ?? 'no summary')->upper()" /> <!-- fine: ?? gives a default -->type Post {
title: string
summary?: string
}
fn find(slug: string): Post? {
return $slug == 'hello' ? Post(title: 'Hello') : null
}
$post = @find('hello')
if $post == null => exit
echo $post.title // fine: the line above stops when it is null
echo ($post.summary ?? 'no summary')->upper() // fine: ?? gives a default以下任何一种都算作检查:在使用处周围的 if、elif 或 while(if $post != null、if $post、if $post is Post),在 if $post == null 之后的 else,上方的 if $post == null { return }(或 throw、break、continue、exit),以及在单个表达式中的 $post and $post.title、$post == null or $post.title == '' 和 $post ? $post.title : ''。刚刚创建且已给出字段的记录 $p = Post(title: 'x', summary: 'y') 也算。可选的列表、集合或映射为空,而非 null;模型的字段则留待运行时检查,因为它们来自数据库。
严格类型
以 strict 开头的文件受其类型约束。每个值都必须有检查器能够证明的类型,类型错误会在脚本任何部分运行之前将其停止:
<strict />
<fn name="area" params="width: number, height: number" value="$width * $height" />
<let name="total" value="0" /> <!-- a number: the value proves it -->
<let name="names" type="string[]" value="[]" /> <!-- an empty list says what it will hold -->
<for each="size" in="[2, 3]">
<set name="total" op="+=" value="@area($size, 2)" />
</for>
<echo value="$total" />strict
fn area(width: number, height: number) => $width * $height
$total = 0 // a number: the value proves it
$names: string[] = [] // an empty list says what it will hold
for size in [2, 3] {
$total += @area($size, 2)
}
echo $total在 strict 文件中:
- 类型错误即错误。类型错误的值(KS5005)、值上不存在的字段或方法(KS5010、KS5003)、不符合其类型的值(KS5012),以及未经检查就使用的可能为 null 的值(KS5018)都是错误,而非警告。
kscript check会报告它们,kscript run、serve和test不会启动脚本。任何lint.rules设置都无法关闭它们。 - 参数要写明类型(KS6007),或从默认值获取类型:
fn greet(who = 'world')。lambda 的参数从其使用的位置获取类型,如[1, 2]->map(fn(n) => $n * 2),或写明类型:fn(n: number) => $n * 2。 - 其他一切都需要检查器能够证明的类型(KS5020)。变量从其值获取类型(
$n = 0、$repo = Repo(name: 'x')),或写明类型($n: int = $args[0])。检查器会要求你写出以下内容的类型:空列表($names: string[] = [])、元素类型混杂的列表、null($found: Repo? = null)、被赋予不同类型值的变量、从 JSON 等无类型数据读取的值、它无法推断的函数结果(fn first(items: list): string),以及没有类型或默认值的字段。 - 当一个值确实可以是任何东西时,可以写
any类型:$data: any = $text->convert(from: json)。从中读取的值需要再次指定类型:$count: int = $data.count。
strict 放在文件顶部,除导入外位于一切之前。在 XML 中,它是 <kscript> 的第一个元素 <strict />。要让项目中的每个脚本都是 strict,在 kscript.json 中设置 "strict": true。导入的 strict 文件在加载时会被检查,因此导入它的脚本也不会启动。
数据与类型的交汇处
<let name="repo" value="@api($url, as: Repo)" /> <!-- KScript.Net: ->check()->convert(from: json, as: Repo) -->
<let name="repos" value="@read_json(./repos.json, as: Repo)" /> <!-- KScript.IO; a list maps item by item -->
<let name="user" value="$text->convert(from: json, as: User)" />
<set name="user" value="User($data)" /> <!-- a map, a list or JSON text -->
<let name="repo" type="Repo" value="$data" /> <!-- also on const and plain assignment -->
<fn name="show" params="repo: Repo, tags: string[]">
<!-- … -->
</fn>$repo = @api($url, as: Repo) // KScript.Net: ->check()->convert(from: json, as: Repo)
$repos = @read_json(./repos.json, as: Repo) // KScript.IO; a list maps item by item
$user = $text->convert(from: json, as: User)
$user = User($data) // a map, a list or JSON text
$repo: Repo = $data // also on const and plain assignment
fn show(repo: Repo, tags: string[]) {
// …
}as: 接受一个类型:as: Repo、as: int,或用 as: Repo[] 表示其列表,写法与声明相同。$repo->type() 为 'Repo'。记录在任何能用映射的地方仍然有效,但读取或设置该类型不具备的字段会报错,设置字段时会将值转换为该字段的类型。
->type() 返回列表的元素类型。[1, 2]->type() 返回 'number[]',由 Repo 记录组成的列表返回 'Repo[]'。混合列表和无类型的空列表返回 'any[]'。使用 ->is_a(list) 判断某个值是否为任意类型的列表。
当数据不符合要求时,映射会失败,并抛出一个 Shape 错误,列出每个问题及其 JSON 路径:
The response from https://api.github.com/... doesn't fit Repo (2 problems):
$.stargazers_count: needs an int, but got the string 'lots'.
$.visibility: must be a Visibility (public, private, internal), but got the string 'secret'.在 catch 中,$err.problems 是一个由 { path, field, message } 映射组成的列表。Repo->check($data) 在数据符合时返回该列表(否则为空),且不会抛出异常;Repo.fields 列出各字段;Repo->schema() 以 JSON Schema 的形式描述该类型。
由类型派生类型
一个类型可以由另一个类型派生而来,这样参数或字段就能跟随其所代表的类型,而无需重复声明。当原类型发生变化时,由它派生的所有类型也随之变化,编辑器会对名称进行补全、链接并检查。
| 表单 | 它是什么 |
|---|---|
Post.fields |
Post 的某个字段名,直接写出:title。模型自身的字段(id 及其键)和关系都可以使用。 |
Post.fields(except: [body]) |
更少的名称:except: 去掉部分名称,only: 保留部分名称,relations: false 去掉关系,relations: only 仅保留关系。 |
Post.title |
Post 的 title 字段的类型及其规则。Post.title(max: 80) 在此基础上添加规则。 |
Order.address.postcode |
字段的字段。Order.lines.item 是列表字段 lines 中的一项。 |
Self.fields, Self.title |
在 type 或 model 内部,指正在声明的类型。 |
draft|live |
其中一个词,直接写出。 |
int|uuid |
任一类型的值。表示类型的名称即为该类型;若要表示这个词本身,请加引号:card|'email'。 |
(draft|live)[] |
方括号用于对联合类型分组,这里用于构成其列表。 |
<type name="Post">
<field name="title" type="string(min: 3)" />
<field name="body" type="string" />
<field name="tags" type="string[]" />
<field name="sorted_by" type="Self.fields" default="'title'" />
</type>
<fn name="column" params="by: Post.fields(except: [tags])" value=""sorted by { $by }"" />
<fn name="retitle" params="title: Post.title" value=""renamed to { $title }"" />
<fn name="tag" params="tag: Post.tags.item" value=""tagged { $tag }"" />
<fn name="publish" params="post: Post, as: draft|live = 'live'" value=""{ $post.title } is { $as }"" />
<fn name="find" params="id: int|uuid" value=""found { $id }"" />
<let name="post" value="Post({ title: 'Hello', body: '…', tags: [] })" />
<echo>{ @column(by: body) }, { @retitle('Hello again') }, { @tag('news') }</echo>
<echo>{ @publish($post, as: draft) }, { @find(42) }, { $post.sorted_by }</echo>type Post {
title: string(min: 3)
body: string
tags: string[]
sorted_by: Self.fields = 'title'
}
fn column(by: Post.fields(except: [tags])) => "sorted by { $by }"
fn retitle(title: Post.title) => "renamed to { $title }"
fn tag(tag: Post.tags.item) => "tagged { $tag }"
fn publish(post: Post, as: draft|live = 'live') => "{ $post.title } is { $as }"
fn find(id: int|uuid) => "found { $id }"
$post = Post({ title: 'Hello', body: '…', tags: [] })
echo "{ @column(by: body) }, { @retitle('Hello again') }, { @tag('news') }"
echo "{ @publish($post, as: draft) }, { @find(42) }, { $post.sorted_by }"无法匹配的值会像其他任何带类型参数一样报告,并列出它可能是的所有名称:
'titel' isn't one of Post's fields. Use title, body, tags or sorted_by.
'drafty' isn't one of these words. Did you mean draft? Use draft or live.
The 'id' argument of @find() doesn't fit int|uuid: needs int or uuid, but got the string 'nope'.内置选项同样带有类型,悬停提示、签名帮助和参考文档都会显示每个选项的类型:
- 模型的
hidden:和guarded:接受Self.fields[],key:接受Self.fields。unique:和index:接受(Self.fields|Self.fields[])[],即一个名称或一组名称。 - 作业的
unique_by:接受Self.fields[]。 ModelUpdate的fields:接受model.fields[],即其model:所指定模型的字段。- 迁移的
Index(columns:)接受其表的字段。 - 方法同样以这种方式引用接收者的字段:
$post->is_dirty(title)接受Self.fields,记录上的->pick([title, views])和->omit([body])接受Self.fields[],记录列表上的$posts->pluck(title)或->pluck([title, views])接受Self.fields|Self.fields[]。接收者没有的名称会报错,并给出建议。 - 带有少量固定词的选项即为词联合类型:
Document(template: plain|paper|report|letter|invoice)、->sort(by:, order?: asc|desc),以及接受(index|store|show|update|destroy)[]的Resource(only:)。若某个词同时也是某个类型的名称,则在该类型中加引号,如echo的format: text|'json'|'markdown',但仍直接写出:format: json。
写作 status: draft|live 的模型字段会存储为数据库的枚举列。
在一组 one-of 中,冒号前的 | 用于分隔名称,冒号后的 | 表示联合类型:id|slug: int|uuid 接受 id: 或 slug:,即整数或 uuid。在成员类型各不相同的组中,| 后接 name: 表示开始下一个成员:(as: draft|live | template: Template)。
值与方法
值包括字符串、数字、布尔值、列表、映射、日期、函数和 null,另外值包 还会添加更多类型(文件、HTTP 响应)。每个值都有方法,使用 -> 调用并可链式连接:
<echo>{ $name->trim()->upper() }</echo>
<echo>{ $people->filter(fn(p) => $p.age >= 18)->map(.name)->join(', ') }</echo>
<echo>{ $people |> sort(by: .name) |> first() }</echo>
<echo>{ @now()->add(days: 7)->format(pattern: 'd MMMM yyyy') }</echo>echo "{ $name->trim()->upper() }"
echo "{ $people->filter(fn(p) => $p.age >= 18)->map(.name)->join(', ') }"
echo "{ $people |> sort(by: .name) |> first() }"
echo "{ @now()->add(days: 7)->format(pattern: 'd MMMM yyyy') }"使用 pluck(key) 按顺序读取每一项的某个字段。给 pluck 传入一个键的列表,即可为每一项生成一个新映射。键可以是裸名称、带引号的字符串或变量。
<let name="people" value="[{ name: 'Joan', age: 82 }, { name: 'Sam' }]" />
<let name="names" value="$people->pluck(name)" /> <!-- ['Joan', 'Sam'] -->
<let name="cards" value="$people->pluck([name, age])" /> <!-- [{ name: 'Joan', age: 82 }, { name: 'Sam', age: null }] -->
<let name="labels" value="$people->pluck(['name'])" /> <!-- [{ name: 'Joan' }, { name: 'Sam' }] -->$people = [{ name: 'Joan', age: 82 }, { name: 'Sam' }]
$names = $people->pluck(name) // ['Joan', 'Sam']
$cards = $people->pluck([name, age]) // [{ name: 'Joan', age: 82 }, { name: 'Sam', age: null }]
$labels = $people->pluck(['name']) // [{ name: 'Joan' }, { name: 'Sam' }]映射中缺失的键会得到 null。带类型的记录仍保留其常规字段检查。空的输入列表得到 [],pluck([]) 为每个输入项生成一个空映射。重复的键只出现一次,并按请求的顺序排列。
在列表上,contains(value)、index_of(value)、remove(value) 和 count_of(value) 使用 == 进行比较。例如,[1, '1']->count_of(1) 得到 2。unique() 使用严格相等(===),因此 [1, '1']->unique() 会保留两项。
is_empty() 在字符串上表示零个字符,在列表上表示零项,在映射上表示零个键。如果你曾用 $text->is_empty() 来接受仅含空白的输入,请改用 $text->is_blank() 以保留该行为。
| 文本 | ->is_empty() |
->is_blank() |
|---|---|---|
'' |
true |
true |
' ' |
false |
true |
'hello' |
false |
false |
数字总是以普通数字书写,从不使用指数形式:echo 10 ** 20 输出 100000000000000000000,echo 0.1 ** 20 输出 0.00000000000000000001。整数在任何大小下都是精确的:123456789 * 987654321 为 121932631112635269,2 ** 100 为 1267650600228229401496703205376,从文本或 JSON 读取的 20 位 id 会保留每一位数字。+、-、*、%、**、/(整除时)、->sum()、->product()、@gcd、@lcm 和 @factorial 都保持精确;小数、@sqrt 等则使用普通浮点运算。小数显示 15 位有效数字,因此 0.1 + 0.2 输出 0.3。整数最多可增长到约 30,000 位,超出后会以 Limit 错误停止。
对于文本,->count() 以及位置(在 ->slice()、->index_of() 和 $text[0] 中)大多数字符计为一个位置,而表情符号等字符计为两个。没有任何方法会把这样的字符切开:->chars()、->first()、->last() 和 ->reverse() 都以读者所见的完整字符为单位工作,->slice() 和 ->truncate() 会把落在字符中间的切分点移回到该字符之前。
关于值的简单事实是字段,直接用点号读取,无需方括号,与读取映射的键方式相同:
<import package="KScript.IO" />
<let name="day" value="'2026-11-19'->to_date()" />
<let name="file" value="@file(./notes.txt)" />
<echo>{ $day.year } { $day.weekday } { $file.name } { $file.size }</echo>import KScript.IO
$day = '2026-11-19'->to_date()
$file = @file(./notes.txt)
echo "{ $day.year } { $day.weekday } { $file.name } { $file.size }"因此 $response.status、$file.size、$url.host 和 $e.status 是字段,而任何接受参数或执行操作的都是方法:$response->convert(from: json)、$file->read_text()、$day->format('yyyy')。返回真或假的名称以 is_ 或 has_ 开头:$response.is_ok、$ip.is_private、$list->is_empty()、$map->has(key)。
时长是一段时间:一个数字加一个单位,不加引号,例如 500ms、30s、10m、2h、1d 或 1w,也可组合使用(1h30m)。所有需要时长的地方都接受它:wait(500ms)、@api($url, options: { timeout: 30s })、$cache->set(key, value, ttl: 10m)。纯数字总是表示秒。
年和月分别为 y 和 mo(m 表示分钟):1y、6mo、5y10mo。月和年没有固定长度,因此这些单位按日历移动日期($date + 1mo 会尽可能保留月中的日),而在需要固定长度的地方(如 wait(1mo) 或 1mo.hours)会被拒绝。
编辑器会为每种类型补全字段和方法,并显示其作用。若要更改值的格式,例如读取 JSON 文本或将行写成 CSV,请使用 ->convert():参见 格式之间的转换。
日期
日期的日历属性是字段:.year、.month、.day、.weekday、.quarter、.day_of_year、.week(ISO 周数)和 .days_in_month。.is_past、.is_future、.is_today 和 .is_weekend 将其与当前时间比较,因此适用于模板:
<let name="post" value="{ title: 'Launch', published_at: '2030-01-01 09:00'->to_date() }" />
<echo value="$post.published_at.is_future ? 'Coming soon' : $post.title" />$post = { title: 'Launch', published_at: '2030-01-01 09:00'->to_date() }
echo $post.published_at.is_future ? 'Coming soon' : $post.title->start_of(unit) 和 ->end_of(unit) 分别给出日期所在 day、week、month、quarter 或 year 的第一刻与最后一刻,这正是“本月订单”报表所需要的。一周从区域设置的第一天开始(en-GB 为周一,en-US 为周日),或由 week_start: 指定的那一天:
<let name="now" value="'2026-11-19 14:30'->to_date()" />
<let name="from" value="$now->start_of(month)" /> <!-- 2026-11-01 00:00 -->
<let name="to" value="$now->end_of(month)" /> <!-- 2026-11-30 23:59:59 -->
<let name="monday" value="$now->start_of(week, week_start: monday)" /> <!-- 2026-11-16 -->$now = '2026-11-19 14:30'->to_date()
$from = $now->start_of(month) // 2026-11-01 00:00
$to = $now->end_of(month) // 2026-11-30 23:59:59
$monday = $now->start_of(week, week_start: monday) // 2026-11-16日历运算按整数单位计算。$date + 1y6mo 按年和月移动日期,->add() 也是如此,它接受 years:、months:、weeks: 和 days: 的任意组合(->subtract() 则向后移动)。月份会尽可能保留月中的日,因此 1 月 31 日加一个月得到 2 月的最后一天。对于小时和分钟,请加上或减去一个时长:
<let name="due" value="'2026-11-30'->to_date()->add(months: 1, days: 2)" /> <!-- 2027-01-01 -->
<let name="last_week" value="@today()->subtract(weeks: 1)" />
<let name="renewal" value="'2026-01-31'->to_date() + 1y1mo" /> <!-- 2027-02-28 -->
<let name="meeting" value="'2026-11-30 09:00'->to_date() + 1h30m" /> <!-- 10:30 -->$due = '2026-11-30'->to_date()->add(months: 1, days: 2) // 2027-01-01
$last_week = @today()->subtract(weeks: 1)
$renewal = '2026-01-31'->to_date() + 1y1mo // 2027-02-28
$meeting = '2026-11-30 09:00'->to_date() + 1h30m // 10:30日期只能通过时长移动。$date + 1 是错误的,因为在其他地方纯数字都表示秒,加上布尔值、列表或另一个日期同样是错误的。请写明单位($date + 3d)。唯一将数字视为日期的情形是 Unix 时间戳,即自 1970 年起的秒数,->to_date() 读取它,->timestamp() 将其返回:
<let name="created" value="1795996800->to_date()" /> <!-- 2026-11-30 00:00 UTC -->
<let name="seconds" value="$created->timestamp()" /> <!-- 1795996800 -->$created = 1795996800->to_date() // 2026-11-30 00:00 UTC
$seconds = $created->timestamp() // 1795996800两个日期相减会得到它们之间的精确时长。->since(other, in: unit) 则改为按整天、整周、整月或整年计数,就像计算生日那样。->is_same(other, unit) 判断两个日期是否处于同一天(默认)、同一周、同一月、同一季度或同一年:
<let name="start" value="'2026-11-30 09:00'->to_date()" />
<let name="took" value="'2026-11-30 10:30'->to_date() - $start" /> <!-- 1h30m -->
<let name="born" value="'1990-12-01'->to_date()" />
<let name="age" value="'2026-11-19'->to_date()->since($born, in: years)" /> <!-- 35 -->
<let name="same" value="@today()->is_same(@now(), day)" /> <!-- true -->$start = '2026-11-30 09:00'->to_date()
$took = '2026-11-30 10:30'->to_date() - $start // 1h30m
$born = '1990-12-01'->to_date()
$age = '2026-11-19'->to_date()->since($born, in: years) // 35
$same = @today()->is_same(@now(), day) // truenow 取自计算机时钟,因此在测试中 @with_clock(date, fn) 会为 @now()、@today()、上述字段以及 @format_relative() 固定其值。
处理文本
文本提供了一些反复用到的辅助功能:更改名称的大小写、按分隔符切分、整理空格以及为负载签名。
<echo value="'Order Total'->case(snake)" /> <!-- order_total -->
<echo value="'order_total'->case(camel)" /> <!-- orderTotal -->
<echo value="'order total'->case(pascal)" /> <!-- OrderTotal -->
<echo value="'orderTotal'->case(kebab)" /> <!-- order-total -->
<let name="email" value="'joan@example.com'" />
<echo>{ $email->before('@') } at { $email->after('@') }</echo> <!-- joan at example.com -->
<echo value="'archive.tar.gz'->after('.', last)" /> <!-- gz -->
<echo value="' too many spaces '->squish()" /> <!-- too many spaces -->
<let name="words" value="'Hello, world!'->words()" /> <!-- ['Hello', 'world'] -->
<echo value="'4242424242424242'->mask('*', keep_end: 4)" />echo 'Order Total'->case(snake) // order_total
echo 'order_total'->case(camel) // orderTotal
echo 'order total'->case(pascal) // OrderTotal
echo 'orderTotal'->case(kebab) // order-total
$email = 'joan@example.com'
echo "{ $email->before('@') } at { $email->after('@') }" // joan at example.com
echo 'archive.tar.gz'->after('.', last) // gz
echo ' too many spaces '->squish() // too many spaces
$words = 'Hello, world!'->words() // ['Hello', 'world']
echo '4242424242424242'->mask('*', keep_end: 4)->before() 和 ->after() 在第一个分隔符处切分,使用 last 时则在最后一个分隔符处切分;若找不到分隔符,则返回整个文本。->wrap(width: 60) 在单词之间断行,使文本适合某个宽度,例如 @terminal_width()。->is_numeric() 对于 '42' 或 '-3.5' 这类文本为真。
->contains()、->starts_with()、->ends_with()、->index_of()(最后一个与last匹配)和->replace()严格区分大小写。传入ignore_case可使大小写匹配不区分:
<let name="query" value="'TEA'" />
<echo value="'Green tea'->contains($query, ignore_case)" /> <!-- true -->$query = 'TEA'
echo 'Green tea'->contains($query, ignore_case) // true要校验 webhook,先用->hmac(key)计算签名(默认 SHA-256,也可用sha1或sha512),再与@secure_equals()比较。该比较所用时间与两者相同部分的多少无关:
<let name="body" value="'{"id": 1}'" />
<let name="signature" value="$body->hmac('whsec_test')" />
<echo value="@secure_equals($signature, $body->hmac('whsec_test'))" /> <!-- true -->$body = '{"id": 1}'
$signature = $body->hmac('whsec_test')
echo @secure_equals($signature, $body->hmac('whsec_test')) // true->md5()、->sha1()、->sha256()和->sha512()返回十六进制哈希值。@escape_regex(text)会转义用户输入的内容,使由其构建的模式只匹配该文本。
列表与映射
列表用->difference(other)、->intersect(other)和->union(other)按集合比较。每个函数都保留第一个列表的顺序,每项只保留一次,并通过==匹配项目,或通过by:为每项给出的结果进行匹配:
<let name="left" value="[1, 2, 3, 4]->difference([2, 4])" /> <!-- [1, 3] -->
<let name="both" value="['tea', 'milk']->union(['milk', 'sugar'])" /> <!-- ['tea', 'milk', 'sugar'] -->
<let name="people" value="[{ id: 1, name: 'Ada' }, { id: 2, name: 'Bo' }]" />
<let name="kept" value="$people->intersect([{ id: 2 }], by: fn(p) => $p.id)" /> <!-- [{ id: 2, name: 'Bo' }] -->$left = [1, 2, 3, 4]->difference([2, 4]) // [1, 3]
$both = ['tea', 'milk']->union(['milk', 'sugar']) // ['tea', 'milk', 'sugar']
$people = [{ id: 1, name: 'Ada' }, { id: 2, name: 'Bo' }]
$kept = $people->intersect([{ id: 2 }], by: fn(p) => $p.id) // [{ id: 2, name: 'Bo' }]->count_by(fn)统计每个键对应的项目数,->take_while(fn)和->skip_while(fn)在遇到第一个不满足条件的项目时停止,->window(size, step?)返回重叠的子序列,->replace_at(index, item)返回修改了一个项目后的副本:
<let name="counts" value="['apple', 'avocado', 'banana']->count_by(fn(fruit) => $fruit->first())" /> <!-- { a: 2, b: 1 } -->
<let name="pairs" value="['mon', 'tue', 'wed', 'thu']->window(2)" /> <!-- [['mon', 'tue'], ['tue', 'wed'], ['wed', 'thu']] -->
<let name="fixed" value="['tea', 'tae', 'milk']->replace_at(1, 'juice')" /> <!-- ['tea', 'juice', 'milk'] -->$counts = ['apple', 'avocado', 'banana']->count_by(fn(fruit) => $fruit->first()) // { a: 2, b: 1 }
$pairs = ['mon', 'tue', 'wed', 'thu']->window(2) // [['mon', 'tue'], ['tue', 'wed'], ['wed', 'thu']]
$fixed = ['tea', 'tae', 'milk']->replace_at(1, 'juice') // ['tea', 'juice', 'milk']最常见与最少见:common
->common(count?, least, by?)统计每个项目出现的次数,并按该次数顺序返回各项,每项只出现一次。不带least时最常见的排在前面;带least时最少见的排在前面。count只保留前面指定数量的项目,不指定时返回所有不重复的项目。出现次数相同的项目保持它们在列表中首次出现的顺序,且每项原样返回,因此数字仍为数字:
<let name="basket" value="['apple', 'pear', 'apple', 'fig', 'fig', 'apple']" />
<!-- apple occurs 3 times, fig 2 times, pear once. -->
<echo value="$basket->common()" /> <!-- ['apple', 'fig', 'pear'] because that is most to least -->
<echo value="$basket->common(1)" /> <!-- ['apple'] because it is the 1st most common -->
<echo value="$basket->common(2)" /> <!-- ['apple', 'fig'] because those are the top 2 -->
<echo value="$basket->common(1, least)" /> <!-- ['pear'] because it is the 1st least common -->
<echo value="$basket->common(least)" /> <!-- ['pear', 'fig', 'apple'] because that is least to most -->$basket = ['apple', 'pear', 'apple', 'fig', 'fig', 'apple']
// apple occurs 3 times, fig 2 times, pear once.
echo $basket->common() // ['apple', 'fig', 'pear'] because that is most to least
echo $basket->common(1) // ['apple'] because it is the 1st most common
echo $basket->common(2) // ['apple', 'fig'] because those are the top 2
echo $basket->common(1, least) // ['pear'] because it is the 1st least common
echo $basket->common(least) // ['pear', 'fig', 'apple'] because that is least to mostby:决定什么算作相同的项目。这里'Tea'和'tea'会被合并计算,因为二者都会转换为'tea',返回的是先出现的那一个:
<let name="drinks" value="['Tea', 'milk', 'tea']" />
<echo value="$drinks->common(1, by: fn(drink) => $drink->lower())" /> <!-- ['Tea'] because 'Tea' and 'tea' count as one, twice -->$drinks = ['Tea', 'milk', 'tea']
echo $drinks->common(1, by: fn(drink) => $drink->lower()) // ['Tea'] because 'Tea' and 'tea' count as one, twice要把出现次数最多的三个数字相乘,先用->common(3)取出它们,再用->product()相乘:
<let name="readings" value="[12, 7, 12, 9, 7, 12, 3]" />
<let name="top" value="$readings->common(3)" /> <!-- [12, 7, 9] because 12 occurs 3 times, 7 twice, then 9 comes before 3 -->
<echo value="$top->product()" /> <!-- 756 because 12 * 7 * 9 is 756 -->$readings = [12, 7, 12, 9, 7, 12, 3]
$top = $readings->common(3) // [12, 7, 9] because 12 occurs 3 times, 7 twice, then 9 comes before 3
echo $top->product() // 756 because 12 * 7 * 9 is 756映射拥有与列表相同的回调函数,参数依次为值和键:->filter()、->reject()、->any()、->all()、->find()(其结果为{ key, value })、->reduce()、->sort(by:)和->map()。->map_keys(fn)会重命名每个键,参数依次为键和值:
<let name="stock" value="{ apples: 3, pears: 0, plums: 2 }" />
<let name="empty" value="$stock->reject(fn(n) => $n > 0)" /> <!-- { pears: 0 } -->
<let name="order" value="$stock->sort(by: fn(n) => $n, order: desc)->keys()" /> <!-- ['apples', 'plums', 'pears'] -->
<let name="renamed" value="{ first_name: 'Ada' }->map_keys(fn(key) => $key->case(camel))" /> <!-- { firstName: 'Ada' } -->$stock = { apples: 3, pears: 0, plums: 2 }
$empty = $stock->reject(fn(n) => $n > 0) // { pears: 0 }
$order = $stock->sort(by: fn(n) => $n, order: desc)->keys() // ['apples', 'plums', 'pears']
$renamed = { first_name: 'Ada' }->map_keys(fn(key) => $key->case(camel)) // { firstName: 'Ada' }集合
集合是一组各不重复的项目。添加已存在的项目不会有任何效果,而且无论集合多大,判断某项目是否在其中都很快。集合写作列表的形式,再用as set转换为集合;也可以把变量或字段声明为set:
<let name="line" value="'rr?gb?r'" />
<let name="colours" value="$line->chars() as set" /> <!-- ['r', '?', 'g', 'b'] because each character goes in once -->
<echo value="($colours - ['?'])->count()" /> <!-- 3 because r, g and b are left once ? is taken away -->$line = 'rr?gb?r'
$colours = $line->chars() as set // ['r', '?', 'g', 'b'] because each character goes in once
echo ($colours - ['?'])->count() // 3 because r, g and b are left once ? is taken away集合最适合用来记录已经见过的内容。$seen: set = []创建一个空集合,+=向其中添加项目,in检查某项目是否存在。随着集合增大,这两个操作仍然很快:
<let name="seen" type="set" value="[]" />
<for each="place" in="['home', 'shop', 'home', 'park']">
<if $place in $seen>
<echo>back at { $place }</echo> <!-- back at home, once, because home was seen before -->
</if>
<set name="seen" op="+=" value="$place" />
</for>$seen: set = []
for place in ['home', 'shop', 'home', 'park'] {
if $place in $seen {
echo "back at { $place }" // back at home, once, because home was seen before
}
$seen += $place
}+合并两个集合,-移除项目,->intersect()保留两者共有的项目。右侧可以是普通列表。set(of: string)是某一类型的集合,每个项目在加入时都会被转换为该类型,与带类型的列表一样。$set as list会把项目以列表形式返回。所有集合方法及示例见集合。
<type name="Post">
<field name="title" type="string" />
<field name="tags" type="set(of: string)" default="[]" />
</type>
<let name="post" value="Post({ title: 'Hello', tags: ['news', 'tech', 'news'] })" />
<echo value="$post.tags" /> <!-- ['news', 'tech'] because the second 'news' is already in the set -->
<echo value="$post.tags->overlaps(['tech'])" /> <!-- true -->
<echo value="$post.tags->is_subset(of: ['news', 'tech', 'sport'])" /> <!-- true because both tags are in the list -->type Post {
title: string
tags: set(of: string) = []
}
$post = Post({ title: 'Hello', tags: ['news', 'tech', 'news'] })
echo $post.tags // ['news', 'tech'] because the second 'news' is already in the set
echo $post.tags->overlaps(['tech']) // true
echo $post.tags->is_subset(of: ['news', 'tech', 'sport']) // true because both tags are in the list在格式之间转换:convert
数据经常需要在不同格式之间转换:API 返回 JSON,配置文件是 YAML,电子表格保存为 CSV。所有值都通过同一个方法->convert()完成,读起来就像一句话:从这种格式,转换为那种格式。
from:读取某种格式的文本并返回其中的值。to:将值写成某种格式。两者结合使用,即可把一种格式直接转换为另一种格式。
| 格式 | from:读取 |
to:写入 |
|---|---|---|
json |
映射、列表、文本、数字 | json 文本 |
yaml |
映射、列表、文本、数字 | yaml 文本 |
csv |
由行组成的列表 | csv 文本 |
markdown, latex |
文档 | 使用 KScript.Document |
html |
通过 KScript.Markdown 从 Markdown 读取,通过 KScript.Document 从文档读取 |
读取文本:from
from:接受文本、文本块(如```yaml或```csv块)、json或csv值,或 HTTP 响应(取其正文):
<let name="order" value="'{"fruit": "apple", "count": 3}'->convert(from: json)" />
<echo value="$order.count" /> <!-- 3 because the json text is now a map with a count key -->
<let name="settings">```yaml
theme: dark
size: 12
```</let>
<echo value="$settings->convert(from: yaml).size" /> <!-- 12 because the yaml is read into a map -->$order = '{"fruit": "apple", "count": 3}'->convert(from: json)
echo $order.count // 3 because the json text is now a map with a count key
$settings = ```yaml
theme: dark
size: 12
```
echo $settings->convert(from: yaml).size // 12 because the yaml is read into a mapCSV 默认包含标题行,用于为每行的键命名。当每一行都是数据时,写not header,此时每行就是由其单元格组成的列表:
<let name="prices">```csv
fruit,price
apple,3
plum,5
```</let>
<echo value="$prices->convert(from: csv)[0].fruit" /> <!-- 'apple' because the header line names the fruit column -->
<echo value="$prices->convert(from: csv, not header)[0]" /> <!-- ['fruit', 'price'] because without a header the first line is a row too -->$prices = ```csv
fruit,price
apple,3
plum,5
```
echo $prices->convert(from: csv)[0].fruit // 'apple' because the header line names the fruit column
echo $prices->convert(from: csv, not header)[0] // ['fruit', 'price'] because without a header the first line is a row too按类型校验:as
as:会根据某个类型校验读取到的内容,并将其转换为记录,因此缺失或错误的字段会在读取它的那一行报错,而不会在之后产生意外。记录列表的写法与声明相同,即Fruit[]:
<type name="Fruit">
<field name="fruit" type="string" />
<field name="price" type="int" />
</type>
<let name="prices">```csv
fruit,price
apple,3
plum,5
```</let>
<let name="fruits" value="$prices->convert(from: csv, as: Fruit[])" />
<echo value="$fruits[0].price + 1" /> <!-- 4 because as: Fruit[] turned the '3' cell into the int 3 -->type Fruit {
fruit: string
price: int
}
$prices = ```csv
fruit,price
apple,3
plum,5
```
$fruits = $prices->convert(from: csv, as: Fruit[])
echo $fruits[0].price + 1 // 4 because as: Fruit[] turned the '3' cell into the int 3写入格式:to
to:可以写入任意值:映射和列表写成 JSON 或 YAML,由行组成的列表写成 CSV。indented将 JSON 分散到多行,headers:用于挑选并排列 CSV 的列:
<let name="basket" value="[{ fruit: 'apple', count: 3 }, { fruit: 'plum', count: 5 }]" />
<echo value="$basket->convert(to: json)" /> <!-- [{"fruit":"apple","count":3},{"fruit":"plum","count":5}] on one line -->
<echo value="$basket->convert(to: json, indented)" /> <!-- the same json, one key a line, for people to read -->
<echo value="$basket->convert(to: csv, headers: ['count'])" /> <!-- "count", then "3" and "5" because only the count column is asked for -->$basket = [{ fruit: 'apple', count: 3 }, { fruit: 'plum', count: 5 }]
echo $basket->convert(to: json) // [{"fruit":"apple","count":3},{"fruit":"plum","count":5}] on one line
echo $basket->convert(to: json, indented) // the same json, one key a line, for people to read
echo $basket->convert(to: csv, headers: ['count']) // "count", then "3" and "5" because only the count column is asked for同时使用两者
同时传入from:和to:,即可在不处理中间值的情况下将一种格式转换为另一种格式:
<let name="settings">```yaml
theme: dark
size: 12
```</let>
<echo value="$settings->convert(from: yaml, to: json)" /> <!-- {"theme":"dark","size":12} because the yaml is read, then written as json -->$settings = ```yaml
theme: dark
size: 12
```
echo $settings->convert(from: yaml, to: json) // {"theme":"dark","size":12} because the yaml is read, then written as json简写:from 与 to
只读取或只写入时,->from(type: json)和->to(type: csv)表达相同的意思,但更简短。它们接受与->convert()相同的选项:
<let name="order" value="'{"fruit": "apple"}'->from(type: json)" />
<echo value="$order.fruit" /> <!-- 'apple' because ->from(type: json) is ->convert(from: json) -->
<echo value="[{ fruit: 'plum' }]->to(type: json)" /> <!-- [{"fruit":"plum"}] because ->to(type: json) is ->convert(to: json) -->$order = '{"fruit": "apple"}'->from(type: json)
echo $order.fruit // 'apple' because ->from(type: json) is ->convert(from: json)
echo [{ fruit: 'plum' }]->to(type: json) // [{"fruit":"plum"}] because ->to(type: json) is ->convert(to: json)->convert()是改变格式的唯一方式,因此旧的一格式一方法写法(->json()、->yaml()、->csv()、->markdown()、->to_json()、->to_yaml()、->to_csv(),以及文档的->html()、->latex()和->markdown())会报错,并提示应改用的->convert()写法,编辑器中还附有修复建议。
读取结构化文本
数据常常以文本形式到达:每行一条记录、以空行分隔的多组行,或用字符绘制的图形。这些方法可将文本转换为便于处理的列表。
行与块
->lines()按行返回文本,每行一项。->blocks()则在空行处切分文本,因此每个块是一组行。单个换行符保留在块内,只有空行才会开始新的块:
<let name="pantry">```text
tea
milk
flour
sugar
eggs
```</let>
<let name="shelves" value="$pantry->blocks()" />
<!-- ['tea\nmilk', 'flour\nsugar\neggs'] because the blank line after milk starts a second block -->
<let name="counts" value="$shelves->map(.lines()->count())" />
<!-- [2, 3] because the first block has 2 lines and the second has 3 -->$pantry = ```text
tea
milk
flour
sugar
eggs
```
$shelves = $pantry->blocks()
// ['tea\nmilk', 'flour\nsugar\neggs'] because the blank line after milk starts a second block
$counts = $shelves->map(.lines()->count())
// [2, 3] because the first block has 2 lines and the second has 3在函数的位置上使用.lines()是fn(block) => $block->lines()的简写:即对每个项目调用该方法,就像.name读取每个项目的字段一样。凡是可以放函数的地方它都能使用,例如->filter(.is_empty())或->sort(by: .age)。
切分列表:split
已有列表时,->split(separator)会在分隔项出现的位置把列表切开,并丢弃分隔项。可以用==指定要匹配的值,也可以提供对分隔项为真的判断条件:
<let name="lines" value="['tea', 'milk', '', 'juice']" />
<echo value="$lines->split('')" /> <!-- [['tea', 'milk'], ['juice']] because '' is the separator -->
<echo value="$lines->split(.is_empty())" /> <!-- [['tea', 'milk'], ['juice']] because the check is true for '' -->
<echo value="[5, 0, 7, 8, 0]->split(0)" /> <!-- [[5], [7, 8], []] because a separator at the end leaves an empty list after it -->$lines = ['tea', 'milk', '', 'juice']
echo $lines->split('') // [['tea', 'milk'], ['juice']] because '' is the separator
echo $lines->split(.is_empty()) // [['tea', 'milk'], ['juice']] because the check is true for ''
echo [5, 0, 7, 8, 0]->split(0) // [[5], [7, 8], []] because a separator at the end leaves an empty list after it->split()作用于文本时切分文本;->split()作用于列表时切分列表。
文本中的数字:numbers
->numbers()按顺序返回文本中写出的每个数字,无需为此编写模式。当负号紧接在数字前、其左侧没有任何相连字符时,它被视为符号,如x=-3;当它位于两个数字之间,如1-3,则视为连字符,结果为1和3:
<echo value="'move 3 boxes from -1 to 12'->numbers()" /> <!-- [3, -1, 12] because -1 has a space before its minus -->
<echo value="'pages 4-9'->numbers()" /> <!-- [4, 9] because the minus joins 4 and 9, so it is a dash -->
<echo value="'price 2.50, qty 4'->numbers()" /> <!-- [2.5, 4] -->echo 'move 3 boxes from -1 to 12'->numbers() // [3, -1, 12] because -1 has a space before its minus
echo 'pages 4-9'->numbers() // [4, 9] because the minus joins 4 and 9, so it is a dash
echo 'price 2.50, qty 4'->numbers() // [2.5, 4]用字符绘制的图形:grid
->grid()将多行字符转换为由单个字符组成的行,因此$grid[row][column]即为一个字符。第 0 行为最上面一行,第 0 列为第一个字符:
<let name="garden">```text
#.#
..#
```</let>
<let name="plot" value="$garden->grid()" />
<!-- [['#', '.', '#'], ['.', '.', '#']] -->
<echo value="$plot[0][1]" /> <!-- '.' because row 0 is '#.#' and column 1 is its second character -->
<echo value="$plot[1][2]" /> <!-- '#' because row 1 is '..#' and column 2 is its last character -->$garden = ```text
#.#
..#
```
$plot = $garden->grid()
// [['#', '.', '#'], ['.', '.', '#']]
echo $plot[0][1] // '.' because row 0 is '#.#' and column 1 is its second character
echo $plot[1][2] // '#' because row 1 is '..#' and column 2 is its last character遍历行与列:cells
->cells()像读取表格一样读取网格。单独使用或与rows一起使用时返回每一行;与columns一起使用时按从上到下的顺序返回每一列。这就是在两个方向上遍历网格的方式:
<let name="garden">```text
#.#
..#
```</let>
<let name="plot" value="$garden->grid()" />
<for each="row" in="$plot->cells(rows)">
<echo value="$row->join('')" />
</for>
<!-- '#.#' then '..#' because each row is one line of the picture -->
<for each="column" in="$plot->cells(columns)">
<echo value="$column->join('')" />
</for>
<!-- '#.' then '..' then '##' because each column reads one character from every line, top to bottom -->
<echo value="$plot->cells(columns)->map(fn(column) => $column->count_of('#'))" />
<!-- [1, 0, 2] because only the last column has a # in both rows -->$garden = ```text
#.#
..#
```
$plot = $garden->grid()
for row in $plot->cells(rows) {
echo $row->join('')
}
// '#.#' then '..#' because each row is one line of the picture
for column in $plot->cells(columns) {
echo $column->join('')
}
// '#.' then '..' then '##' because each column reads one character from every line, top to bottom
echo $plot->cells(columns)->map(fn(column) => $column->count_of('#'))
// [1, 0, 2] because only the last column has a # in both rowsrow:选取一行,column:选取一列,二者均从 0 开始计数,-1表示最后一项。两者同时给出时,即可取到它们交汇处的那一个单元格:
<let name="garden">```text
#.#
..#
```</let>
<let name="plot" value="$garden->grid()" />
<echo value="$plot->cells(row: 0)" /> <!-- ['#', '.', '#'] because row 0 is the top line -->
<echo value="$plot->cells(column: -1)" /> <!-- ['#', '#'] because -1 is the last column, and both lines end in # -->
<echo value="$plot->cells(row: 1, column: 0)" /> <!-- '.' because row 1 is '..#' and column 0 is its first character -->$garden = ```text
#.#
..#
```
$plot = $garden->grid()
echo $plot->cells(row: 0) // ['#', '.', '#'] because row 0 is the top line
echo $plot->cells(column: -1) // ['#', '#'] because -1 is the last column, and both lines end in #
echo $plot->cells(row: 1, column: 0) // '.' because row 1 is '..#' and column 0 is its first character行的长度可以不同,例如不规则的地图。此时某列会跳过长度不够到达该列的行,不会为填补空缺而凭空生成内容:
<let name="steps">```text
#.#
#
```</let>
<echo value="$steps->grid()->cells(columns)" />
<!-- [['#', '#'], ['.'], ['#']] because the second line only reaches column 0 -->$steps = ```text
#.#
#
```
echo $steps->grid()->cells(columns)
// [['#', '#'], ['.'], ['#']] because the second line only reaches column 0->cells()适用于任何列表的列表,而不仅限于网格:[[1, 2], [3, 4]]->cells(columns)即[[1, 3], [2, 4]],它会把行转换为列。
在网格中查找:positions_of
->positions_of(item)返回某个项目在网格中出现的每个位置,位置为带有.row和.column的点,按行从上到下、每行从左到右排列。若给定一个函数,则返回该函数对单元格为真的位置:
<let name="garden">```text
#.#
..#
```</let>
<let name="trees" value="$garden->grid()->positions_of('#')" />
<!-- [{ row: 0, column: 0 }, { row: 0, column: 2 }, { row: 1, column: 2 }] because those are the three #s, top line first -->
<echo value="$trees->contains({ row: 1, column: 2 })" /> <!-- true because there is a # at row 1, column 2 -->
<echo value="$trees->contains({ row: 1, column: 0 })" /> <!-- false because row 1 starts with a . -->$garden = ```text
#.#
..#
```
$trees = $garden->grid()->positions_of('#')
// [{ row: 0, column: 0 }, { row: 0, column: 2 }, { row: 1, column: 2 }] because those are the three #s, top line first
echo $trees->contains({ row: 1, column: 2 }) // true because there is a # at row 1, column 2
echo $trees->contains({ row: 1, column: 0 }) // false because row 1 starts with a .点与->combinations(2)配合得很好,它会返回每一对点各一次,且较早的点排在前面。带有两个参数的函数会依次接收这对点的两个点。下面的例子统计四个角均为树的正方形数量,即使角之间还夹着其他树:
<let name="field">```text
#.##.
.....
.#...
##.##
```</let>
<let name="trees" value="$field->grid()->positions_of('#')" />
<echo value="$trees->combinations(2)->count_of(fn(left, right) {
// only two trees on the same row can be a square's top corners
if $left.row != $right.row {
return false
}
// the gap between them is the square's width, so the bottom corners sit that many rows down
$size = $right.column - $left.column
return $trees->contains({ row: $left.row + $size, column: $left.column })
and $trees->contains({ row: $left.row + $size, column: $right.column })
})" />
<!-- 1 because only the trees at columns 0 and 3 of row 0 have trees 3 rows below both of them -->$field = ```text
#.##.
.....
.#...
##.##
```
$trees = $field->grid()->positions_of('#')
echo $trees->combinations(2)->count_of(fn(left, right) {
// only two trees on the same row can be a square's top corners
if $left.row != $right.row {
return false
}
// the gap between them is the square's width, so the bottom corners sit that many rows down
$size = $right.column - $left.column
return $trees->contains({ row: $left.row + $size, column: $left.column })
and $trees->contains({ row: $left.row + $size, column: $right.column })
})
// 1 because only the trees at columns 0 and 3 of row 0 have trees 3 rows below both of them查找形状:shapes
->shapes() 可在文本、列表、网格或三维列表中查找形状:内置的正方形、长方形、直线和圆形,以及您自己绘制的遮罩(masks)。文本按 ->grid() 的读取方式处理,每行为一行、每个字符为一个单元格,因此无需先调用 ->grid()。网格的单元格可以存放任何内容,因此对于内置形状,of: 会指定哪些单元格构成该形状:可以是 '#' 这样的值,也可以是 /[#@]/ 这样的正则表达式。每个匹配结果只返回一次,格式为 { kind, points },其中每个点都是一个单元格 { row, column, value }。形状的各点之间可以夹有其他单元格:
<let name="field">```text
#.##.
.....
.#...
##.##
```</let>
<echo value="$field->shapes(square, of: '#')->count()" />
<!-- 1 because the #s at columns 0 and 3 of row 0 have #s 3 rows below both of them -->$field = ```text
#.##.
.....
.#...
##.##
```
echo $field->shapes(square, of: '#')->count()
// 1 because the #s at columns 0 and 3 of row 0 have #s 3 rows below both of them如果不使用 rotated,形状保持水平:正方形和长方形的边保持水平,直线横向或纵向延伸。使用 rotated 后,形状可以倾斜,因此正方形可以是菱形,直线也可以斜向延伸:
<let name="kite">```text
..#..
.#.#.
..#..
```</let>
<echo value="$kite->shapes(square, of: '#')->count()" /> <!-- 0 because no four #s make a square with level sides -->
<echo value="$kite->shapes(square, of: '#', rotated)->count()" /> <!-- 1 because the four #s make a diamond, a square on its corner -->$kite = ```text
..#..
.#.#.
..#..
```
echo $kite->shapes(square, of: '#')->count() // 0 because no four #s make a square with level sides
echo $kite->shapes(square, of: '#', rotated)->count() // 1 because the four #s make a diamond, a square on its corner同时指定多个形状即可一次查找全部。即使一个匹配结果符合多种形状,也只返回一次:正方形同时也是长方形,因此它会作为正方形返回,.kind 会指明它的类型:
<let name="plot">```text
@@@.
@..@
@@@@
```</let>
<echo value="$plot->shapes(rectangle, of: '@')->count()" /> <!-- 4 because three rectangles share rows 0 and 2, and one shares rows 1 and 2 -->
<echo value="$plot->shapes(square, rectangle, of: '@')->map(.kind)" />
<!-- ['square', 'rectangle', 'rectangle', 'rectangle'] because the 2 by 2 one is a square, so it isn't a rectangle as well -->
<echo value="$plot->shapes(line, of: '@', size: 4)->count()" /> <!-- 1 because only the bottom row has 4 @s in a row -->
<echo value="$plot->shapes(line, of: '@', size: 3, rotated)->count()" /> <!-- 4 because rotated lets lines run diagonally too -->$plot = ```text
@@@.
@..@
@@@@
```
echo $plot->shapes(rectangle, of: '@')->count() // 4 because three rectangles share rows 0 and 2, and one shares rows 1 and 2
echo $plot->shapes(square, rectangle, of: '@')->map(.kind)
// ['square', 'rectangle', 'rectangle', 'rectangle'] because the 2 by 2 one is a square, so it isn't a rectangle as well
echo $plot->shapes(line, of: '@', size: 4)->count() // 1 because only the bottom row has 4 @s in a row
echo $plot->shapes(line, of: '@', size: 3, rotated)->count() // 4 because rotated lets lines run diagonally too直线需要 size: 指定其点数。圆形需要 radius:,distance: 用于指定距离的计算方式:straight(直线距离,默认值)、steps(仅横向和纵向距离,绘制出菱形)或 moves(对角线距离计为一步,绘制出正方形环):
<let name="pond">```text
.~.
~.~
.~.
```</let>
<echo value="$pond->shapes(circle, of: '~', radius: 1)->count()" /> <!-- 1 because the four ~s are each 1 away from the middle -->
<echo value="$pond->shapes(circle, of: '~', radius: 1, distance: moves)->count()" /> <!-- 0 because with moves the corners are 1 away too, and they aren't ~ -->$pond = ```text
.~.
~.~
.~.
```
echo $pond->shapes(circle, of: '~', radius: 1)->count() // 1 because the four ~s are each 1 away from the middle
echo $pond->shapes(circle, of: '~', radius: 1, distance: moves)->count() // 0 because with moves the corners are 1 away too, and they aren't ~->shapes() 同样适用于点的列表,例如 ->positions_of() 返回的结果,或从 csv 读取的行。此时每个点都会计入,因此不需要 of::$trees->shapes(square, rotated)。
自定义形状:遮罩(masks)
遮罩是您自己绘制的形状。内置形状只知道各点的位置;遮罩则精确规定每个单元格必须包含什么内容,包括空白单元格。将其声明为 extends Mask 所对应的类型,并在 layout 中绘制:一个文本块,每个字符对应一个单元格,用以描绘形状(也可以使用正则表达式,用于描述沿行延伸任意长度的形状:正则表达式布局)。每个字符都匹配与其内容相同的单元格。所有行共有的缩进不属于图案的一部分,因此请将其与周围的代码一同缩进。
要查找由 # 组成的实心 2×2 方块,请先绘制它,然后通过名称将遮罩传递给 ->shapes():
<type name="Block" description="Four #s packed into a square." extends="Mask">
<field name="layout" default="```text
##
##
```" />
</type>
<let name="roof">```text
###.
###.
...#
```</let>
<let name="blocks" value="$roof->shapes(Block)" /> <!-- the matches, top left first -->
<echo value="$blocks->count()" /> <!-- 2 because the block fits at columns 0-1 and again at columns 1-2 -->
<echo value="$blocks->first().kind" /> <!-- 'Block' because a mask's match is named after its type -->
<echo value="$blocks->first().points->map(.column)" /> <!-- [0, 1, 0, 1] because the first block covers columns 0 and 1 of rows 0 and 1 -->/// Four #s packed into a square.
type Block extends Mask {
layout: ```text
##
##
```
}
$roof = ```text
###.
###.
...#
```
$blocks = $roof->shapes(Block) // the matches, top left first
echo $blocks->count() // 2 because the block fits at columns 0-1 and again at columns 1-2
echo $blocks->first().kind // 'Block' because a mask's match is named after its type
echo $blocks->first().points->map(.column) // [0, 1, 0, 1] because the first block covers columns 0 and 1 of rows 0 and 1symbols 仅用于那些具有特殊含义的字符。它将一个字符映射为其所匹配的内容:值(t: 'taken')匹配包含该值的单元格,正则表达式(/[#@]/)匹配文本符合该表达式的单元格,fn(cell) 匹配使其返回 true 的单元格,same 匹配必须都包含同一个值的单元格(见下文),any 匹配不属于该形状的单元格。any 单元格可以包含任何内容,可以超出输入的边缘,并且不计入匹配结果的各点。要查找 3×3 正方形四角的四棵树,中间可以有任意内容:
<type name="Corners" description="Trees at the four corners of a 3x3 square, anything between." extends="Mask">
<field name="layout" default="```text
#.#
...
#.#
```" />
<field name="symbols" default="{ '.': any }" />
</type>
<let name="orchard">```text
#.#.#
.#...
#.#.#
```</let>
<echo value="$orchard->shapes(Corners)->count()" /> <!-- 2 because the corners fit at columns 0-2 and at columns 2-4 -->
<echo value="$orchard->shapes(Corners)->first().points->map(.symbol)" />
<!-- ['#', '#', '#', '#'] because . is any, so its cells aren't part of the match, even the # in the middle -->/// Trees at the four corners of a 3x3 square, anything between.
type Corners extends Mask {
layout: ```text
#.#
...
#.#
```
symbols: { '.': any }
}
$orchard = ```text
#.#.#
.#...
#.#.#
```
echo $orchard->shapes(Corners)->count() // 2 because the corners fit at columns 0-2 and at columns 2-4
echo $orchard->shapes(Corners)->first().points->map(.symbol)
// ['#', '#', '#', '#'] because . is any, so its cells aren't part of the match, even the # in the middle当单元格不是单个字符时,symbols 就体现出其价值。一排座位是一个单词列表,而一个值的列表是一行,因此布局需要为每个单词分配一个字母:
<type name="QuietPair" description="Two free seats side by side, with a taken seat on each side." extends="Mask">
<field name="layout" default="```text
tfft
```" />
<field name="symbols" default="{ t: 'taken', f: 'free' }" />
</type>
<let name="row" value="['free', 'taken', 'free', 'free', 'taken', 'taken']" />
<echo value="$row->shapes(QuietPair)->count()" /> <!-- 1 because only seats 1 to 4 read taken, free, free, taken -->/// Two free seats side by side, with a taken seat on each side.
type QuietPair extends Mask {
layout: ```text
tfft
```
symbols: { t: 'taken', f: 'free' }
}
$row = ['free', 'taken', 'free', 'free', 'taken', 'taken']
echo $row->shapes(QuietPair)->count() // 1 because only seats 1 to 4 read taken, free, free, taken->shapes() 可接受一个遮罩或一个遮罩列表,rotated 会将每个遮罩在输入允许的所有方向上进行变换:沿行从后向前,在网格中旋转四分之一、二分之一和四分之三圈,在三维中则有全部 24 种旋转方式。多个遮罩的匹配结果会一并返回,并通过各自的 .kind 命名,并且可以在一次调用中同时查找遮罩和内置形状:
<type name="Fork" description="Three trees in a V, with anything between them." extends="Mask">
<field name="layout" default="```text
t~t
~t~
```" />
<field name="symbols" default="{ t: /[#@]/, '~': any }" />
</type>
<type name="Gap" description="Two trees with a clearing between them." extends="Mask">
<field name="layout" default="```text
#.#
```" />
</type>
<let name="wood">```text
#.@
.#.
#.#
```</let>
<echo value="$wood->shapes(Fork)->count()" /> <!-- 1 because the V fits only with its point at the bottom -->
<echo value="$wood->shapes(Fork, rotated)->count()" /> <!-- 4 because turned a quarter, a half and three quarters, it fits once each way -->
<echo value="$wood->shapes([Fork, Gap], rotated)->map(.kind)" />
<!-- ['Fork', 'Fork', 'Fork', 'Fork', 'Gap', 'Gap'] because the bottom row and the left column are each #.# -->
<echo value="$wood->shapes(Fork)->first().points->map(.symbol)" />
<!-- ['t', 't', 't'] because ~ is any, so its cells aren't part of the match -->/// Three trees in a V, with anything between them.
type Fork extends Mask {
layout: ```text
t~t
~t~
```
symbols: { t: /[#@]/, '~': any }
}
/// Two trees with a clearing between them.
type Gap extends Mask {
layout: ```text
#.#
```
}
$wood = ```text
#.@
.#.
#.#
```
echo $wood->shapes(Fork)->count() // 1 because the V fits only with its point at the bottom
echo $wood->shapes(Fork, rotated)->count() // 4 because turned a quarter, a half and three quarters, it fits once each way
echo $wood->shapes([Fork, Gap], rotated)->map(.kind)
// ['Fork', 'Fork', 'Fork', 'Fork', 'Gap', 'Gap'] because the bottom row and the left column are each #.#
echo $wood->shapes(Fork)->first().points->map(.symbol)
// ['t', 't', 't'] because ~ is any, so its cells aren't part of the match与任何字段一样,遮罩的符号可以在使用处进行修改:Fork(symbols: { t: fn(cell) => $cell != '.', '~': any }) 与 . 之外的任何字符匹配同一个 V。
布局中的空行表示下一层的开始,自上而下依次排列,与遮罩所匹配的文本中空行的含义相同。每一层的行数必须相同,三维匹配结果中的每个点也都有一个 layer。三维列表($cube[layer][row][column])的读取方式相同:
<type name="Step" description="A step: one block on the top layer, with two under it on the layer below." extends="Mask">
<field name="layout" default="```text
#.
##
```" />
<field name="symbols" default="{ '.': any }" />
</type>
<let name="tower">```text
#..
...
##.
.#.
```</let>
<echo value="$tower->shapes(Step)->count()" /> <!-- 1 because the one block on the top layer has a block under it, and another beside that -->
<echo value="$tower->shapes(Step)->first().points->map(.layer)" /> <!-- [0, 1, 1] because one point is on the top layer and two are on the layer below -->/// A step: one block on the top layer, with two under it on the layer below.
type Step extends Mask {
layout: ```text
#.
##
```
symbols: { '.': any }
}
$tower = ```text
#..
...
##.
.#.
```
echo $tower->shapes(Step)->count() // 1 because the one block on the top layer has a block under it, and another beside that
echo $tower->shapes(Step)->first().points->map(.layer) // [0, 1, 1] because one point is on the top layer and two are on the layer below层数或行数少于输入的遮罩会在整个输入上滑动:单行遮罩会沿网格的每一行尝试匹配,而单层遮罩则会在三维文本或三维列表的每一层中尝试匹配。层数或行数多于输入的遮罩会报错,并给出提示,例如"Step has 2 layers, and this is one grid."
Mask 是一种可用于参数或字段的类型。它接受任何继承自 Mask 的类型,既可以是类型本身(Block),也可以是由其构造的类型(Block(symbols: ...)),而 Mask[] 接受它们的列表:
<type name="Block" description="Four #s packed into a square." extends="Mask">
<field name="layout" default="```text
##
##
```" />
</type>
<fn name="count_in" params="input: string, shape: Mask" returns="int" value="$input->shapes($shape)->count()" />
<fn name="count_all" params="input: string, shapes: Mask[]" returns="int" value="$input->shapes($shapes)->count()" />
<let name="roof">```text
###.
###.
...#
```</let>
<echo value="@count_in($roof, Block)" /> <!-- 2 because Block fits twice in the roof -->
<echo value="@count_in($roof, Block(symbols: { '#': /[#.]/ }))" /> <!-- 6 because now a . counts as well, so every 2x2 window fits -->
<echo value="@count_all($roof, [Block, Block(symbols: { '#': '.' })])" /> <!-- 2 because no 2x2 of the roof is all .s, so only Block's 2 count -->/// Four #s packed into a square.
type Block extends Mask {
layout: ```text
##
##
```
}
fn count_in(input: string, shape: Mask): int => $input->shapes($shape)->count()
fn count_all(input: string, shapes: Mask[]): int => $input->shapes($shapes)->count()
$roof = ```text
###.
###.
...#
```
echo @count_in($roof, Block) // 2 because Block fits twice in the roof
echo @count_in($roof, Block(symbols: { '#': /[#.]/ })) // 6 because now a . counts as well, so every 2x2 window fits
echo @count_all($roof, [Block, Block(symbols: { '#': '.' })]) // 2 because no 2x2 of the roof is all .s, so only Block's 2 count相同的单元格:same
迄今为止的所有符号都是将单元格与某个固定内容进行比较。same 则是比较单元格之间的关系:凡是以该字符绘制的单元格,都必须包含同一个值(无论是什么值),并且两个不同的 same 字符必须包含不同的值。same(...) 用于限定该值的范围,可以是一个值、一个正则表达式或一个 fn(cell)。要查找一个正读反读都相同的单词,例如 oxxo:
<type name="Mirror" description="Two letters, then the same two backwards, like 'abba'." extends="Mask">
<field name="layout" default="```text
xyyx
```" />
<field name="symbols" default="{ x: same(/[a-z]/), y: same(/[a-z]/) }" />
</type>
<echo value="'ioxxoj'->shapes(Mirror)->count()" /> <!-- 1 because only 'oxxo' reads the same letters out and back -->
<echo value="'ioxxoj'->shapes(Mirror)->first().points->map(.value)" /> <!-- ['o', 'x', 'x', 'o'] because x is o and y is x there -->
<echo value="'aaaa'->shapes(Mirror)->count()" /> <!-- 0 because x and y are different characters, so they hold different letters -->/// Two letters, then the same two backwards, like 'abba'.
type Mirror extends Mask {
layout: ```text
xyyx
```
symbols: { x: same(/[a-z]/), y: same(/[a-z]/) }
}
echo 'ioxxoj'->shapes(Mirror)->count() // 1 because only 'oxxo' reads the same letters out and back
echo 'ioxxoj'->shapes(Mirror)->first().points->map(.value) // ['o', 'x', 'x', 'o'] because x is o and y is x there
echo 'aaaa'->shapes(Mirror)->count() // 0 because x and y are different characters, so they hold different letters任意长度的形状:正则表达式布局
图案的大小是固定的。布局也可以改用正则表达式,它会沿每一行逐个读取单元格,并匹配所需数量的单元格。每个单元格按其文本读取,匹配必须从单元格之间的边界开始并在边界结束。正则表达式布局不支持 symbols:使用 (?<name>...) 为某一部分命名,每个点的 symbol 即为其所在部分的名称:
<type name="PartNumber" description="A part number: digits side by side, each one named a digit." extends="Mask">
<field name="layout" default="/(?<digit>\d)+/" />
</type>
<let name="schematic">```text
467..114
...*....
..35.633
```</let>
<echo value="$schematic->shapes(PartNumber)->count()" /> <!-- 4 because 467, 114, 35 and 633 are each a run of digits -->
<echo value="$schematic->shapes(PartNumber)->first().points->map(.column)" /> <!-- [0, 1, 2] because 467 fills the first three columns of row 0 -->
<echo value="$schematic->shapes(PartNumber)->first().points->map(.symbol)" /> <!-- ['digit', 'digit', 'digit'] because each cell fell in the digit part -->/// A part number: digits side by side, each one named a digit.
type PartNumber extends Mask {
layout: /(?<digit>\d)+/
}
$schematic = ```text
467..114
...*....
..35.633
```
echo $schematic->shapes(PartNumber)->count() // 4 because 467, 114, 35 and 633 are each a run of digits
echo $schematic->shapes(PartNumber)->first().points->map(.column) // [0, 1, 2] because 467 fills the first three columns of row 0
echo $schematic->shapes(PartNumber)->first().points->map(.symbol) // ['digit', 'digit', 'digit'] because each cell fell in the digit part使用 rotated 时,正则表达式布局也会从后向前读取每一行,并且在网格中从下向上读取每一列。单词列表会按每个单元格一个单词的方式读取,因此 /\d+/ 作用于 ['ab', '12', '34'] 可以找到 ['12', '34']。
盖章遮罩:repeated
使用 repeated 时,遮罩如同曲奇模具:它会从左上角开始反复盖章,直到覆盖整个输入,位于右侧和底部边缘的副本会被截断。当每个副本的每个单元格都与第一个副本一致时(any 单元格不受约束),即视为匹配。匹配结果为第一个副本,copies 则指明盖了多少次章:
<type name="Checker" description="One black and one white tile, and the same two swapped below." extends="Mask">
<field name="layout" default="```text
#.
.#
```" />
</type>
<let name="floor">```text
#.#.#
.#.#.
#.#.#
```</let>
<echo value="$floor->shapes(Checker, repeated)->count()" /> <!-- 1 because the whole floor is a checkerboard -->
<echo value="$floor->shapes(Checker, repeated)->first().copies" /> <!-- 6 because 2 rows of 3 stamps cover it, the last row and column cut off -->
<echo value="'#..'->shapes(Checker, repeated)->count()" /> <!-- 0 because the third cell should be # like the first -->/// One black and one white tile, and the same two swapped below.
type Checker extends Mask {
layout: ```text
#.
.#
```
}
$floor = ```text
#.#.#
.#.#.
#.#.#
```
echo $floor->shapes(Checker, repeated)->count() // 1 because the whole floor is a checkerboard
echo $floor->shapes(Checker, repeated)->first().copies // 6 because 2 rows of 3 stamps cover it, the last row and column cut off
echo '#..'->shapes(Checker, repeated)->count() // 0 because the third cell should be # like the first正则表达式布局没有固定的大小,因此使用 repeated 时,它会先尝试最短的模具并返回能够匹配的最短结果:前 size 个单元格沿行盖章后必须恰好构成该行,并且正则表达式必须完整匹配这些单元格。它一次只读取一行,因此请每次只提供一行:
<type name="Instructions" description="A printer's instructions: one or more colours, read along a row." extends="Mask">
<field name="layout" default="/[roygbv]+/" />
</type>
<let name="printed" value="'rgbrgbrgbr'->shapes(Instructions, repeated)->first()" />
<echo value="$printed.points->map(.value)->join('')" /> <!-- 'rgb' because rgb, stamped and cut off, prints rgbrgbrgbr -->
<echo value="$printed.copies" /> <!-- 4 because the fourth rgb is cut off after its r -->/// A printer's instructions: one or more colours, read along a row.
type Instructions extends Mask {
layout: /[roygbv]+/
}
$printed = 'rgbrgbrgbr'->shapes(Instructions, repeated)->first()
echo $printed.points->map(.value)->join('') // 'rgb' because rgb, stamped and cut off, prints rgbrgbrgbr
echo $printed.copies // 4 because the fourth rgb is cut off after its r可匹配任意内容的单元格:blank
输入有时会有损坏或未知的部分。blank: 用于指定可以匹配任意内容的单元格,可以是一个值('?')、一个正则表达式或一个 fn(cell)。空白单元格可以匹配任何符号,并且在使用 same 或 repeated 时不参与比较,因此各副本会相互填补空白:当另一副本已知某个点的值时,该点的 value 即为被填补后的值。blank: 应写在调用中而不是遮罩中,因为它描述的是输入,而不是形状:
<type name="Instructions" description="A printer's instructions: one or more colours, read along a row." extends="Mask">
<field name="layout" default="/[roygbv]+/" />
</type>
<let name="cutter" value="'o??v???y'->shapes(Instructions, repeated, blank: '?')->first()" />
<echo value="$cutter.points->count()" /> <!-- 5 because no shorter cutter agrees with every colour that can be read -->
<echo value="$cutter.points->map(.value)->join('')" /> <!-- 'o?yv?' because the y comes from the second copy, and two cells are never read -->
<echo value="'???'->shapes(Instructions, repeated, blank: '?')->first().points->count()" /> <!-- 1 because a barcode of blanks fits one instruction -->/// A printer's instructions: one or more colours, read along a row.
type Instructions extends Mask {
layout: /[roygbv]+/
}
$cutter = 'o??v???y'->shapes(Instructions, repeated, blank: '?')->first()
echo $cutter.points->count() // 5 because no shorter cutter agrees with every colour that can be read
echo $cutter.points->map(.value)->join('') // 'o?yv?' because the y comes from the second copy, and two cells are never read
echo '???'->shapes(Instructions, repeated, blank: '?')->first().points->count() // 1 because a barcode of blanks fits one instruction内置形状同样支持 blank:,并且 of: 除了值或正则表达式之外也支持 fn(cell),因此这三者读取单元格的方式一致:$field->shapes(square, of: '#', blank: '?') 会将 ? 计为 #。
要在条形码列表的各行中查找某个形状,可以对各行进行映射:
<type name="Instructions" description="A printer's instructions: one or more colours, read along a row." extends="Mask">
<field name="layout" default="/[roygbv]+/" />
</type>
<let name="barcodes">```text
rgbrgbrgbr
?rv
??b?????
```</let>
<echo value="$barcodes->lines()->sum(fn(barcode) => $barcode->shapes(Instructions, repeated, blank: '?')->first().points->count())" />
<!-- 6 because rgbrgbrgbr needs 3 instructions, ?rv needs 2 (vr) and ??b????? needs 1 (b) -->/// A printer's instructions: one or more colours, read along a row.
type Instructions extends Mask {
layout: /[roygbv]+/
}
$barcodes = ```text
rgbrgbrgbr
?rv
??b?????
```
echo $barcodes->lines()->sum(fn(barcode) => $barcode->shapes(Instructions, repeated, blank: '?')->first().points->count())
// 6 because rgbrgbrgbr needs 3 instructions, ?rv needs 2 (vr) and ??b????? needs 1 (b)遮罩(mask)包含layout、symbols及其自身的方法,用:编写。编辑器与kscript check会报告编写有误的遮罩,多数附带修复方案:缺少或为空的布局、布局全部为any、图片中含制表符、各图层高度不一致、某个符号超过一个字符或被重复列出、null应为any、引号中的'same'应为same、symbols与正则布局并存、layout =应为layout:、对内置形状使用repeated、将遮罩传给->find_all()或->matches()(它们只接受正则表达式),以及like:(->shapes()已不再接受)。布局中未使用的符号会以警告形式报告(KS6026),将字符映射为自身的符号同样会报告(KS6025),因为每个字符本就与自身匹配:
<type name="Block" extends="Mask">
<field name="layout" default="```text
##
```" />
<field name="symbols" default="{ '#': '#' }" /> <!-- the warning: '#' already matches '#'. -->
</type>type Block extends Mask {
layout: ```text
##
```
symbols: { '#': '#' } // the warning: '#' already matches '#'.
}在编辑器中,遮罩是语言的一部分。extends ‸ 会提供 Mask,在 Mask 类型内部输入 layout 即可编写文本块;一旦有了文本块,symbols 会以布局中的一个字符和 any 的形式完整写出。在 symbols: { } 内部,自动补全会提供布局中尚未列出的字符;在某个键的冒号之后,则会提供 any、same、same(/…/)、值、正则表达式和 fn(cell)。在 layout: 之后,它会提供文本块和正则表达式。签名提示工具会在编写遮罩时显示 ->shapes(mask, rotated?, repeated?, blank?)。将鼠标悬停在布局的某个字符上,会显示该字符所匹配的内容以及布局中使用它的次数,并且每个字符会按其匹配内容着色:与自身匹配的字符或值(如文本)、正则表达式对应的颜色、fn 对应函数的颜色,而 any 则以注释的淡化颜色显示。
按序列工作
相乘:product
->product(fn?) 对各项求积,正如 ->sum() 对各项求和。给定一个函数时,它会对函数为每一项返回的结果求积。整数无论多大都保持精确:
<echo value="[2, 3, 4]->product()" /> <!-- 24 because 2 * 3 * 4 is 24 -->
<let name="boxes" value="[{ width: 2, height: 5 }, { width: 3, height: 1 }]" />
<echo value="$boxes->product(fn(box) => $box.width)" /> <!-- 6 because 2 * 3 is 6 -->
<echo value="[942, 945, 571]->product()" /> <!-- 508298490 -->echo [2, 3, 4]->product() // 24 because 2 * 3 * 4 is 24
$boxes = [{ width: 2, height: 5 }, { width: 3, height: 1 }]
echo $boxes->product(fn(box) => $box.width) // 6 because 2 * 3 is 6
echo [942, 945, 571]->product() // 508298490累计值:scan
->scan(fn(total, item), initial?) 的用法与 ->reduce() 类似,但会保留过程中的每一个累计值,便于您了解结果是如何逐步形成的。若不使用 initial,则第一项即为第一个累计值:
<let name="spending" value="[5, 2, 8, 1]" />
<echo value="$spending->scan(fn(total, amount) => $total + $amount)" />
<!-- [5, 7, 15, 16] because 5, then 5 + 2, then 7 + 8, then 15 + 1 -->
<echo value="$spending->scan(fn(total, amount) => $total - $amount, 20)" />
<!-- [15, 13, 5, 4] because the budget starts at 20 and each amount comes off it -->$spending = [5, 2, 8, 1]
echo $spending->scan(fn(total, amount) => $total + $amount)
// [5, 7, 15, 16] because 5, then 5 + 2, then 7 + 8, then 15 + 1
echo $spending->scan(fn(total, amount) => $total - $amount, 20)
// [15, 13, 5, 4] because the budget starts at 20 and each amount comes off it全部组合:combinations
->combinations(size) 给出列表中所有从中选取 size 个项目的方式,且不考虑所选项目的顺序。每次选取中的项目都保持列表原有顺序,同一次选取中不会重复选同一项。
从 ['tea', 'milk', 'juice'] 中选 2 个的过程如下:先以 tea 开始,与其后的每个项目配对(milk,然后是 juice);再以 milk 开始,与其后的每个项目配对(juice)。juice 之后已没有项目,因此到此为止。['milk', 'tea'] 永远不会出现,因为它与 ['tea', 'milk'] 是同一种选取:
<let name="drinks" value="['tea', 'milk', 'juice']" />
<echo value="$drinks->combinations(2)" />
<!-- [['tea', 'milk'], ['tea', 'juice'], ['milk', 'juice']] because 3 drinks give 3 ways to pick 2 -->
<echo value="$drinks->combinations(3)" />
<!-- [['tea', 'milk', 'juice']] because there is only one way to pick all 3 -->
<echo value="$drinks->combinations(1)" />
<!-- [['tea'], ['milk'], ['juice']] -->$drinks = ['tea', 'milk', 'juice']
echo $drinks->combinations(2)
// [['tea', 'milk'], ['tea', 'juice'], ['milk', 'juice']] because 3 drinks give 3 ways to pick 2
echo $drinks->combinations(3)
// [['tea', 'milk', 'juice']] because there is only one way to pick all 3
echo $drinks->combinations(1)
// [['tea'], ['milk'], ['juice']]一种常见用法是检查每一对组合,例如查找两个价格之和等于某个总额的组合:
<let name="prices" value="[15, 40, 25, 60]" />
<let name="pair" value="$prices->combinations(2)->find(fn(two) => $two->sum() == 65)" />
<!-- [40, 25] because 15 + 40, 15 + 25 and 15 + 60 aren't 65, but 40 + 25 is -->$prices = [15, 40, 25, 60]
$pair = $prices->combinations(2)->find(fn(two) => $two->sum() == 65)
// [40, 25] because 15 + 40, 15 + 25 and 15 + 60 aren't 65, but 40 + 25 is如果函数的参数个数与所选项目数相同,每个参数会依次接收对应项目,因此你可以为它们命名,而无需读取 $two[0] 和 $two[1]。此方式适用于任意大小:选取 3 个时填充 fn(first, second, third)。只有一个参数的函数仍会接收整个选取结果:
<let name="prices" value="[15, 40, 25, 60]" />
<echo value="$prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70)" />
<!-- 3 because 15 + 60, 40 + 60 and 25 + 60 are over 70, and no other pair is -->
<let name="sides" value="[3, 4, 5, 9]" />
<echo value="$sides->combinations(3)->count_of(fn(shortest, middle, longest) => $shortest ** 2 + $middle ** 2 == $longest ** 2)" />
<!-- 1 because only 3, 4 and 5 make a right-angled triangle: 9 + 16 is 25 -->
<echo value="$sides->combinations(3)->map(fn(three) => $three->sum())" />
<!-- [12, 16, 17, 18] because a function with one parameter gets each pick as a list -->$prices = [15, 40, 25, 60]
echo $prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70)
// 3 because 15 + 60, 40 + 60 and 25 + 60 are over 70, and no other pair is
$sides = [3, 4, 5, 9]
echo $sides->combinations(3)->count_of(fn(shortest, middle, longest) => $shortest ** 2 + $middle ** 2 == $longest ** 2)
// 1 because only 3, 4 and 5 make a right-angled triangle: 9 + 16 is 25
echo $sides->combinations(3)->map(fn(three) => $three->sum())
// [12, 16, 17, 18] because a function with one parameter gets each pick as a list由于所选项目依次填入参数,这样的函数无法同时获得索引:以两两配对为例,fn(first, second) 就是该配对的两个项目。
所有排列:permutations
->permutations(size?) 给出所有排列,其中顺序有影响,因此 ['tea', 'milk'] 和 ['milk', 'tea'] 都会出现。若不使用 size,每种排列都会用到全部项目:
<echo value="['tea', 'milk', 'juice']->permutations()" />
<!--
6 orderings: [['tea', 'milk', 'juice'], ['tea', 'juice', 'milk'], ['milk', 'tea', 'juice'], ...]
because there are 3 choices for first, 2 for second and 1 for third, and 3 * 2 * 1 is 6
-->
<echo value="['tea', 'milk', 'juice']->permutations(2)->count()" />
<!-- 6 because 3 choices for first and 2 for second -->echo ['tea', 'milk', 'juice']->permutations()
// 6 orderings: [['tea', 'milk', 'juice'], ['tea', 'juice', 'milk'], ['milk', 'tea', 'juice'], ...]
// because there are 3 choices for first, 2 for second and 1 for third, and 3 * 2 * 1 is 6
echo ['tea', 'milk', 'juice']->permutations(2)->count()
// 6 because 3 choices for first and 2 for second组合与排列增长很快(10 个项目有 3,628,800 种排列),因此超过一百万个列表时会以 Limit 错误停止,而不是耗尽内存。
循环移位:rotate
->rotate(by) 会把每个项目向前移动 by 个位置,从前端移出的项目则放到末尾。负数的 by 则向相反方向移动:
<let name="week" value="['mon', 'tue', 'wed', 'thu']" />
<echo value="$week->rotate(1)" /> <!-- ['tue', 'wed', 'thu', 'mon'] because mon moves from the front to the end -->
<echo value="$week->rotate(-1)" /> <!-- ['thu', 'mon', 'tue', 'wed'] because thu moves from the end to the front -->$week = ['mon', 'tue', 'wed', 'thu']
echo $week->rotate(1) // ['tue', 'wed', 'thu', 'mon'] because mon moves from the front to the end
echo $week->rotate(-1) // ['thu', 'mon', 'tue', 'wed'] because thu moves from the end to the front为类型添加方法:extend
extend 可为某个类型添加你自己的方法,无论该类型是内置的还是你自定义的。在其中,每个 fn 是一个方法,$this 是被调用该方法的值:
<extend type="date">
<fn name="api_date" description="The date as text for an API: 2026-11-21." value="$this->format('yyyy-MM-dd')" />
<fn name="is_payday" value="$this.day == 25" />
</extend>
<extend type="list">
<fn name="second" value="$this[1]" />
</extend>
<extend type="string">
<fn name="slug" value="$this->lower()->trim()->replace(' ', '-')" />
</extend>
<echo>{ '2026-11-25'->to_date()->api_date() } { '2026-11-25'->to_date()->is_payday() }</echo>
<echo>{ ['a', 'b', 'c']->second() } { 'Hello World'->slug() } { 'Hello World' |> slug() }</echo>extend date {
/// The date as text for an API: 2026-11-21.
fn api_date() => $this->format('yyyy-MM-dd')
fn is_payday() => $this.day == 25
}
extend list {
fn second() => $this[1]
}
extend string {
fn slug() => $this->lower()->trim()->replace(' ', '-')
}
echo "{ '2026-11-25'->to_date()->api_date() } { '2026-11-25'->to_date()->is_payday() }"
echo "{ ['a', 'b', 'c']->second() } { 'Hello World'->slug() } { 'Hello World' |> slug() }"你可以扩展 string、number(或 int 和 float)、bool、list、set、map、fn、date、email、password、handle、uuid 和 regex,也可以扩展包中的值,例如 file 或 response,以及你自己的 type,其方法中可通过 $this.name 访问 $this(即一条记录)及其字段。方法和其他 fn 一样,可以有参数、默认值和命名实参。
方法不能与该类型已有方法同名,因此拼写错误或命名冲突不会改变内置方法的行为。若要有意替换某个方法,请编写 override:
<extend type="date">
<fn name="to_string" override="yes" value="$this->format('d MMMM yyyy')" />
</extend>extend date {
override fn to_string() => $this->format('d MMMM yyyy')
}在 XML 中,extend 是包含 <fn> 元素的 <extend type="date">,而 override fn 则是 <fn override="true">。
扩展的适用范围。文件中自身的 extend 代码块仅适用于该文件以及导入它的每个文件。在项目中(即含有 kscript.json 的文件夹),extensions/ 文件夹中的每个文件都会应用于项目中的每个脚本、测试和页面,无需导入。你可以按需拆分,例如每个类型一个文件:
extensions/
date.kscript extend date { … }
list.kscript extend list { … }
text/
slug.kscript extend string { … }kscript make extension date --methods api_date,is_payday 会写入 extensions/date.kscript 作为起始内容。若要将它们放在其他位置,可在 kscript.json 中列出文件夹或通配符,这会替换默认文件夹:"extensions": ["extensions", "shared/**/*.kscript"]。两个扩展文件为同一类型添加同名方法会报错,错误信息会同时指出两个文件。脚本自身的 extend(或导入文件中的)优先于项目中的定义。
编辑器只在扩展方法适用的范围内提供补全和检查:在既未声明、也未导入(或通过项目获得)->api_date() 的文件中,日期上的方法 @today()->api_date() 仍会被视为未知方法。悬停时会显示该方法的 /// 文档以及添加它的文件,跳转到定义则会打开该文件。
错误
仅当前置条件成立时才继续执行,请使用guard condition else { ... }。失败块必须通过return、throw、break、continue或exit离开当前流程。
<fn name="save_age" params="age: int, enabled: bool">
<guard test="$enabled">
<return value="'Skipped'" />
</guard>
<if $age < 0>
<throw value="{
type: 'Validation'
message: "Age cannot be negative: { $age }"
}" />
</if>
<return value="'Saved'" />
</fn>
<echo value="@save_age(-1, true) catch => $err.message" />fn save_age(age: int, enabled: bool) {
guard $enabled else {
return 'Skipped'
}
throw if $age < 0 {
type: 'Validation'
message: "Age cannot be negative: { $age }"
}
return 'Saved'
}
echo @save_age(-1, true) catch => $err.message后缀catch在求值成功时保留其左侧的值。当求值抛出错误时,KScript会将该错误绑定到$err并计算备用值。若只想处理某一种错误类型,请使用catch Validation => $err.message;若要为绑定命名,请使用catch Validation as problem => $problem.message。备用值为null时,会将原始错误继续向上抛出。
在@a() + @b() catch => 0中,处理器同时覆盖调用和加法运算。在@a() + (@b() catch => 0)中,它只覆盖@b()。
当某个条件成立时才抛出错误,请使用throw if。在其代码块内,每行写一个字段。KScript只对条件求值一次,且仅当条件为真时才对字段求值,因此成功的响应可以完全省略e。
<fn name="result" params="reply: map">
<if $reply->has('e')>
<throw value="{
type: 'Network'
message: "Host refused: {$reply.e.message}"
code: $reply.e.code
}" />
</if>
<return value="$reply.r" />
</fn>
<try>
<echo value="@result({ r: 'ready' })" />
<catch type="Network" as="err">
<echo>Request failed ({$err['code']}): {$err.message}</echo>
</catch>
</try>fn result(reply: map) {
throw if $reply->has('e') {
type: 'Network'
message: "Host refused: {$reply.e.message}"
code: $reply.e.code
}
return $reply.r
}
try {
echo @result({ r: 'ready' })
} catch Network as err {
echo "Request failed ({$err['code']}): {$err.message}"
}<try>
<let name="data" value="@read_json($path)" />
<catch type="FileNotFound">
<echo>No file at {$path}, using defaults.</echo>
</catch>
<catch as="err">
<echo>Failed: {$err.message} (line {$err.line})</echo>
</catch>
<finally>
<echo>done</echo>
</finally>
</try>
<throw type="Validation">Age must be positive, got {$age}</throw>try {
$data = @read_json($path)
} catch FileNotFound {
echo "No file at {$path}, using defaults."
} catch err {
echo "Failed: {$err.message} (line {$err.line})"
} finally {
echo 'done'
}
throw Validation "Age must be positive, got {$age}"catch接受它所处理的错误类型,类型之间用|连接,as用于为错误命名:catch FileNotFound | Permission as e。只有小写名称的catch(catch err)会处理所有错误。when用于添加测试:catch Network as e when $e.status == 503。catch按顺序尝试,第一个匹配的会被执行。错误类型名称以大写字母开头,这是catch区分它们与变量名的方式。
未知元素、属性和语法错误会在脚本启动之前报告,因此末尾的一个拼写错误不会让任务只完成一半。
未被捕获的错误会以KScript错误的形式打印出来,包括错误发生的位置和类型,脚本以退出码3结束:
ERROR app.kscript:2:11: Name: Unknown command @nope().kscript对所有失败都以这种方式显示,包括脚本、kscript serve错误页面以及所有其他命令,绝不会以.NET异常的形式出现。由计算机而非脚本引起的失败会获得与之匹配的错误类型(FileNotFound、Access、IO、Network等),而kscript未预料到的失败则是Internal错误,这是值得报告的缺陷。若要查看错误背后的.NET异常和堆栈跟踪,请使用--stack-trace运行(放在脚本路径之前:kscript --stack-trace app.kscript),或设置KSCRIPT_STACK_TRACE=1,该设置同样适用于kscript serve和已编译的程序。
在值的位置 throw
throw 既是语句也是值,因此 match 分支、?? 的右侧或 ? : 的一侧可以用错误终止,而不是给出值。它的写法与语句相同:双引号中的类型和消息、单独的消息、由类型创建的错误或捕获的错误。它从不给出值,所以适用于任何期望某种类型的地方,检查器从其余部分读取类型:声明返回 int 的函数可以用 throw 分支结束它的 match。
<fn name="press" params="display: int, button: string" returns="int">
<return value="match $button {
'[oct]' => $display * 8
'[two]' => $display * 2
// Every other button stops here, with the button in the message.
_ => throw Validation "No press for { $button } yet"
}" />
</fn>
<!-- 32 because [oct] has an arm -->
<echo value="@press(4, '[oct]') catch => $err.message" />
<!-- 'No press for [mem] yet' because no arm fits [mem] -->
<echo value="@press(4, '[mem]') catch => $err.message" />fn press(display: int, button: string): int {
return match $button {
'[oct]' => $display * 8
'[two]' => $display * 2
// Every other button stops here, with the button in the message.
_ => throw Validation "No press for { $button } yet"
}
}
// 32 because [oct] has an arm
echo @press(4, '[oct]') catch => $err.message
// 'No press for [mem] yet' because no arm fits [mem]
echo @press(4, '[mem]') catch => $err.message在 ?? 之后,只有左侧的值缺失时 throw 才会运行,因此必须找到结果的查找可以用一行表达:
<let name="prices" value="{ tea: 3, coffee: 4 }" />
<fn name="price_of" params="item: string, prices: map" returns="int">
<return value="$prices[$item] ?? throw NotFound "There is no price for { $item }"" />
</fn>
<echo value="@price_of('tea', $prices) catch NotFound => 0" /> <!-- 3 because tea has a price, so the throw never ran -->
<echo value="@price_of('cake', $prices) catch NotFound => 0" /> <!-- 0 because cake has no price, so the throw ran -->$prices = { tea: 3, coffee: 4 }
fn price_of(item: string, prices: map): int {
return $prices[$item] ?? throw NotFound "There is no price for { $item }"
}
echo @price_of('tea', $prices) catch NotFound => 0 // 3 because tea has a price, so the throw never ran
echo @price_of('cake', $prices) catch NotFound => 0 // 0 because cake has no price, so the throw ran? : 也是如此,只有被选中的一侧会运行:$count > 0 ? $count : throw Validation "A basket holds at least one item"。catch 的回退值中单独的 throw 会原样再次给出捕获的错误:@load() catch => throw。
需要多个值的分支可以包含一个由语句组成的 { } 块,就像 match 语句的分支那样。它的 return 给出分支的值,块中可以看到 $it 以及 match 周围的变量:
<let name="limit" value="2" />
<let name="label">match 3 {
1 => 'one'
_ => {
if $it > $limit {
// 'more than 2' because 3 is over the limit
return "more than { $limit }"
}
return 'a few'
}
}</let>
<echo value="$label" /> <!-- 'more than 2' -->$limit = 2
$label = match 3 {
1 => 'one'
_ => {
if $it > $limit {
// 'more than 2' because 3 is over the limit
return "more than { $limit }"
}
return 'a few'
}
}
echo $label // 'more than 2'分支的 => 之后的 {,若先出现键和冒号(_ => { name: 'Ada' })则开启一个 map,否则开启一个语句块,包括空的 { }。编辑器以相同方式检查两者:在 throw 之后补全错误类型、在分支块中补全语句、为 throw 及其类型着色,并在这样抛出的错误可能逃出脚本时发出警告(KS5016)。
函数与类型上的处理器
将catch附加到函数或方法上,即可为每个调用者处理错误。将其附加到类型上,则可在该类型的所有方法之间共享同一处理器。
最近的匹配处理器会先运行。返回一个非null值即可恢复。false、0和''等值均可使用。单独的throw、null返回值,或处理器执行到末尾,都会把原始错误传递给下一个外层处理器。
<type name="Directory">
<field name="fallback" type="string" />
<fn name="lookup" params="key: string">
<if !$key->is_blank()>
<return value="$key" />
</if>
<if !$this.fallback->is_blank()>
<return value="$this.fallback" />
</if>
<throw type="Validation">A key is required</throw>
</fn>
<catch type="Validation" as="err">
<return value="$err.message" />
</catch>
</type>
<let name="directory" value="Directory(fallback: 'guest')" />
<echo value="$directory->lookup('owner')" /> <!-- owner -->
<echo value="$directory->lookup('')" /> <!-- guest -->
<let name="empty" value="Directory(fallback: '')" />
<echo value="$empty->lookup('')" /> <!-- A key is required -->type Directory {
fallback: string
fn lookup(key: string) {
if !$key->is_blank() => return $key
if !$this.fallback->is_blank() => return $this.fallback
throw Validation "A key is required"
}
} catch Validation as err {
return $err.message
}
$directory = Directory(fallback: 'guest')
echo $directory->lookup('owner') // owner
echo $directory->lookup('') // guest
$empty = Directory(fallback: '')
echo $empty->lookup('') // A key is required在处理程序内部,当条件成立时,throw if condition 会重新抛出当前错误。添加 payload 块可以抛出新的错误。仅记录错误的处理程序会让错误继续向上传播。可运行的 catch 测试展示了方法处理程序将错误传递给其类型的处理程序,以及调用方在错误被记录后捕获该错误。
使用/// @throws Network记录可能传递给调用方的错误。悬停提示与签名帮助会显示已知错误。在脚本顶层,若某个已知错误可能逸出,kscript check与编辑器会发出警告(KS5016)。
对于单次调用,使用 catch 以内联方式获取结果。
<echo value="@testing(1, 2) catch Error => $err.message" />
<fn name="testing" params="arg1: number, arg2: number">
<throw value="Error(message: "{ $arg1 } and { $arg2 }")" />
</fn>echo @testing(1, 2) catch Error => $err.message
fn testing(arg1: number, arg2: number) {
throw Error(message: "{ $arg1 } and { $arg2 }")
}带值和原因抛出错误
使用 throw Error(message: ..., value: ..., cause: ...) 抛出带有额外数据的通用错误。括号前的名称决定错误类型。Error 用于通用错误,Validation 等内置类型,或你自己声明的类型。具名参数会成为字段。message: 设置说明,cause: 在你包装先前错误时保存该错误。
<let name="age" value="-1" />
<try>
<try>
<throw type="Validation">Age must be positive, got {$age}</throw>
<catch type="Validation" as="original">
<throw value="Error(
message: 'Could not save profile',
value: $age,
cause: $original
)" />
</catch>
</try>
<catch type="Error" as="err">
<echo>{ $err.type }: { $err.message }</echo>
<echo>Rejected value: { $err.value }</echo>
<echo>Caused by: { $err.cause.message }</echo>
</catch>
</try>$age = -1
try {
try {
throw Validation "Age must be positive, got {$age}"
} catch Validation as original {
throw Error(
message: 'Could not save profile',
value: $age,
cause: $original
)
}
} catch Error as err {
echo "{ $err.type }: { $err.message }"
echo "Rejected value: { $err.value }"
echo "Caused by: { $err.cause.message }"
}Error: Could not save profile
Rejected value: -1
Caused by: Age must be positive, got -1抛出第一个错误时省略 cause:。添加到内置错误上的字段(如这里的 value:),在同一文件中捕获该类型或其父类型的任何 catch 里都可以用点语法($err.value)读取,编辑器也会补全它。如果错误是在另一个文件中抛出的,请用方括号读取:$err['value']。若希望每个调用方都能发现并检查这些字段,请声明一个错误类型并捕获该类型。
如果你已经有一个包含 type、message 及其他字段的映射,可以用 throw $payload 直接抛出该映射。将映射作为第一个参数传给 Error($payload) 会将其转换为消息文本。错误构造函数在编辑器补全中提供具名参数。
在 XML 中,同样的抛出写作 <throw value="Error(message: 'Could not save profile', value: $age, cause: $original)" />。外层 XML 的 value 属性保存整个错误表达式。内层 value: 参数是该错误上的额外字段。若只需类型和消息,<throw type="Validation" message="Invalid age" /> 对应 throw Validation "Invalid age"。
重试
某些失败会自行消失:数据库繁忙、网络短暂中断,或 API 正在限流。@retry(times, work) 会调用 work,并在每次抛出错误时再次调用,总共最多 times 次。它返回 work 的结果,或抛出最后一个错误。work 会接收尝试次数,第一次为 1:
<fn name="fetch_rates" params="attempt: int">
<if $attempt < 3>
<throw type="Timeout">The rates service is busy</throw>
</if>
<return value="{ eur: 0.86 }" />
</fn>
<let name="rates" value="@retry(3, @fetch_rates, backoff: 100ms)" />
<echo value="$rates.eur" />fn fetch_rates(attempt: int) {
if $attempt < 3 => throw Timeout "The rates service is busy"
return { eur: 0.86 }
}
$rates = @retry(3, @fetch_rates, backoff: 100ms)
echo $rates.eurbackoff 在两次调用之间等待。when 会接收错误并决定是否重试,因此永远不会成功的错误会立即失败:@retry(5, @charge, when: fn(err) => $err.type == 'Timeout')。
依次尝试
有些值可能是几种情况之一,要弄清楚是哪一种,就得逐个尝试每种解读,直到有一种可行。try each $value |> first, second 按顺序用该值调用每一项,并返回第一个结果。每一项可以是类型(调用 NumberEntry($label) 会检查标签),也可以是函数:
<fn name="digits" params="text: string" description="The number in text that is only digits." returns="int">
<if not $text->matches(/^[0-9]+$/)>
<throw type="Validation">'{$text}' isn't digits</throw>
</if>
<return value="$text->to_int()" />
</fn>
<fn name="word" params="text: string" description="The number in a word: one, two or three." returns="int">
<let name="numbers" value="{ one: 1, two: 2, three: 3 }" />
<if not $numbers->has($text)>
<throw type="Validation">'{$text}' isn't a number word</throw>
</if>
<return value="$numbers[$text]" />
</fn>
<echo value="try each '12' |> @digits, @word" /> <!-- 12, because @digits reads it -->
<echo value="try each 'two' |> @digits, @word" /> <!-- 2, because @digits throws and @word reads it -->
<echo value="try each 'many' |> @digits, @word, _ => 0" /> <!-- 0, because neither reads it -->
<!-- A longer list goes one item per line, each after a comma. -->
<fn name="reading" params="text: string" returns="int" value="try each $text |>
@digits,
@word,
_ => 0" />
<echo value="@reading('three')" /> <!-- 3, because @word reads it -->/// The number in text that is only digits.
fn digits(text: string): int {
if not $text->matches(/^[0-9]+$/) => throw Validation "'{$text}' isn't digits"
return $text->to_int()
}
/// The number in a word: one, two or three.
fn word(text: string): int {
$numbers = { one: 1, two: 2, three: 3 }
if not $numbers->has($text) => throw Validation "'{$text}' isn't a number word"
return $numbers[$text]
}
echo try each '12' |> @digits, @word // 12, because @digits reads it
echo try each 'two' |> @digits, @word // 2, because @digits throws and @word reads it
echo try each 'many' |> @digits, @word, _ => 0 // 0, because neither reads it
// A longer list goes one item per line, each after a comma.
fn reading(text: string): int => try each $text |>
@digits,
@word,
_ => 0
echo @reading('three') // 3, because @word reads it抛出 Shape(值不符合类型)或 Validation 的项会把值传给下一项。其他任何错误都是真正的失败,因此会一直向上传给调用方:项内部的除以零错误绝不会被误当作"不是这一项"。
最后一行可以是 _ => value,就像在 match 中一样,用于没有任何项接受该值的情况。如果没有这一行,没有项接受该值时会产生一个 Shape 错误,其中列出该值和尝试过的每一项:the string 'many' fits none of @digits, @word.
在调用的括号内,各项之间的逗号会被当作调用本身的逗号,因此要把 try each 放在单独的括号中:expect((try each 'one' |> @digits, @word), same: 1)。
类型的工厂通常是对由它派生的类型使用的 try each。
错误类型
使用error声明你自己的错误类型。字段的用法与type中相同,消息中也可以使用这些字段,extends用于说明该错误属于哪种类型:
<error name="PersonNotFound" message="No person with id {$id}" description="No person has that id." extends="NotFound">
<field name="id" type="int" />
</error>
<error name="OutOfStock" status="409" message="{$item} is out of stock">
<field name="item" type="string" />
<field name="left" type="int" default="0" />
</error>
<fn name="find_person" params="id: int">
<throw value="PersonNotFound(id: $id)" />
</fn>
<try>
<do>@find_person(42)</do>
<catch type="NotFound" as="e">
<echo>{ $e.message } ({ $e.type }, status { $e.status })</echo>
</catch>
</try>/// No person has that id.
error PersonNotFound(message: "No person with id {$id}") extends NotFound {
id: int
}
error OutOfStock(status: 409, message: "{$item} is out of stock") {
item: string
left: int = 0
}
fn find_person(id: int) {
throw PersonNotFound(id: $id)
}
try {
@find_person(42)
} catch NotFound as e {
echo "{ $e.message } ({ $e.type }, status { $e.status })"
}- 抛出。
throw PersonNotFound(id: 42)创建错误并将其抛出。它的参数包括按名称指定的字段,以及message:(代替类型的默认消息)和cause:(导致此错误的先前错误)。没有默认值的字段必须提供,编辑器会标记缺失和未知的字段。throw Validation "Too short"对于没有字段的类型仍然有效,throw Validation(field: 'name', message: 'Too short')则为内置类型添加字段。 - 捕获。
catch NotFound也会捕获PersonNotFound,因为它继承自NotFound。在 catch 中,$e.id读取一个字段,编辑器会补全 catch 所指定类型的字段。每个错误都有type、message、line、column、file、status和cause。$e->is(NotFound)在代码中检查类型,$e->chain()列出它:['PersonNotFound', 'NotFound', 'Error']。 - 重新抛出与包装。在 catch 中,单独的
throw会原样重新抛出正在处理的错误。throw $e对已保存的错误做同样的事。要添加上下文,请包装它:throw ConfigBroken(path: $path, cause: $e),然后$err.cause.message读取原始错误。 - 不抛出地创建。
OutOfStock(item: 'tea')将错误作为值返回,以便稍后返回或抛出。 - 状态码。
status是当没有任何处理程序捕获该错误时,KScript.Http 路由返回的 HTTP 状态码。类型会继承它,以及它的字段和消息,继承自其所扩展的类型。 - 导出。顶层错误类型会像函数和类型一样被导出,因此
import "errors/payment-failed.kscript"可以引入它们。kscript make error PaymentFailed --status 402 --extends Validation --fields "order: int"将其写入errors/。
KScript 自身抛出的内置错误类型形成一棵树,catch 遵循这棵树:
| 类型 | 继承自 | 引发于 |
|---|---|---|
Error |
每个错误。catch Error 捕获所有错误。 |
|
Syntax, Name, Null, Argument, Value, Const, Math |
Error |
脚本中的错误:语法错误、未知名称、需要值时却为 null、参数错误、值错误、修改 const、除以零。Index 继承自 Value,用于列表之外的位置。 |
Type |
Error |
错误类型的值。Shape 继承它,用于不符合 type 的数据($e.problems 列出每个问题)。 |
Format |
Error |
格式错误的文本。Json 和 Yaml 继承它。 |
IO |
Error |
文件。FileNotFound、Permission 和 Access 继承它。 |
Network |
Error |
请求。Timeout 继承它,$e.status 是响应的状态码。 |
Import, Config, Input, Limit, Context, Platform, Cancelled, Retired, Http, AI, UI, Reference, Assertion, Internal |
Error |
导入、设置、输入、递归等限制、错误的位置、操作系统、已停止的脚本、已废弃的功能、KScript.Http 应用、语言模型、桌面窗口、文档引用、失败的测试检查,以及 KScript 自身的故障。 |
Validation (422), BadRequest (400), Unauthorized (401), Forbidden (403), NotFound (404), Conflict (409), TooManyRequests (429) |
Error |
供你自己的代码抛出或继承。数字即 HTTP 状态码。 |
Query, Connection (503) |
Error |
KScript.Data:数据库拒绝执行的查询,或无法打开的数据库。Migration:无法读取或运行的迁移,或无法继续执行的kscript db命令。ModelNotFound扩展NotFound;UniqueViolation与ForeignKeyViolation扩展Conflict;MultipleRecordsFound(来自->sole())扩展Query。 |
JobFailed |
Error |
KScript.Queue:已用完重试次数的任务。JobTimeout扩展Timeout。 |
没有类型名以 Error 结尾:它们都是错误。(QueryError 和 ConnectionError 现在分别是 Query 和 Connection,catch QueryError 对此有说明。)
catch 或 throw 中的名称既未声明也非内置时仍然可用(作为 Error 的一种),但编辑器会对其发出警告(KS5011),因为它通常是拼写错误。
设置:$config
$config 保存应用自身的设置,例如其名称、数据库和缓存。每个脚本、页面、路由和测试都无需导入即可读取它。所有设置都存放在同一处:kscript.json 中的 config 部分。
{
"name": "shop",
"config": {
"app": { "name": "Shop" },
"database": { "connections": { "main": { "url": "sqlite:data/shop.sqlite" } } },
"features": ["search", "cart"]
}
}<echo value="$config.app.name" />
<let name="timeout" value="$config->get('http.timeout', 30)" /> <!-- a path, and a default when it isn't set -->
<if $config->has('features')>
<echo>{ $config.features->join(', ') }</echo>
</if>
<let name="key" value="$config->require('api.key')" /> <!-- stops with a clear message when it's missing -->echo $config.app.name
$timeout = $config->get('http.timeout', 30) // a path, and a default when it isn't set
if $config->has('features') => echo "{ $config.features->join(', ') }"
$key = $config->require('api.key') // stops with a clear message when it's missing不存在的设置返回 null,因此 $config.port ?? 8080 可以正常工作。名称不区分大小写,因此 $config.app.name 和 $config.APP.NAME 是同一个设置。在编辑器中,将鼠标悬停在 $config.app.name 上会显示其类型;“转到定义”会打开提供该键的文件,插值字符串中的键也适用。
各个包读取$config中各自的部分:KScript.Data 读取database,KScript.Cache 读取cache,KScript.Mail 读取mail,$log读取logging,翻译读取i18n,货币运算读取money.exchange_rates(参见货币)。
环境。同一个应用在不同场景下通常需要不同的设置,例如测试用的内存数据库,或生产环境中的真实服务器。将这些设置放在 kscript.json 旁边的 kscript.<env>.json 中。它的 config 部分会覆盖 kscript.json 中的对应部分,映射会逐字段合并,因此只需包含发生变化的设置:
// kscript.test.json
{
"config": {
"database": { "connections": { "main": { "url": "sqlite::memory:" } } }
}
}使用kscript --env staging script.kscript或KSCRIPT_ENV=staging选择运行环境。kscript test使用来自kscript.json的test.env(参见测试)。$config->environment()返回当前环境;若未选择任何环境则返回 null。环境文件只包含一个config部分:其他内容都应放在kscript.json中。
需要代码的设置:config.kscript。JSON 无法读取环境变量或进行计算。对于这些设置,请在 kscript.json 旁边添加 config.kscript(XML 项目中为 config.ks.xml)。它定义 configure(environment),该函数接收环境(未选择环境时为 development)并返回一个映射。该映射会覆盖 JSON 设置,因此只需包含需要代码的设置:
<!-- config.kscript -->
<fn name="configure" params="environment: string">
<let name="url" value="@env('DATABASE_URL', default: '')" />
<return value="{
database: { connections: { main: $url->is_blank() ? {} : { url: $url } } }
http: { timeout: $environment == 'production' ? 8s : 30s }
}" />
</fn>// config.kscript
fn configure(environment: string) {
$url = @env('DATABASE_URL', default: '')
return {
database: { connections: { main: $url->is_blank() ? {} : { url: $url } } }
http: { timeout: $environment == 'production' ? 8s : 30s }
}
}这些值保留其 KScript 类型,因此 8s 仍然是时长。脚本中可以使用 @env()、$env、导入的文件以及 KScript.IO 等包,其中的路径从脚本自身所在文件夹开始。它只在脚本首次读取 $config 时运行一次,且不能读取 $config 本身。kscript make config base 会写入一个初始的 config.kscript,kscript make config staging 会写入 kscript.staging.json。
各层级按从前到后叠加,后面的层级优先:kscript.json 的 config 部分,然后是 kscript.<env>.json,最后是 config.kscript。项目之外的脚本会从其自身文件夹读取 config.kscript。
.env 文件可将机密信息保存在项目文件之外。.env(若针对某个环境,则为 .env.<env>)与 kscript.json 并列存放,其中包含 NAME=value 行,可以使用 # 注释,前面可加 export,'single quotes' 按原样读取,"double quotes" 则允许 \n 并可跨行。${NAME} 和 ${NAME:-default} 会引用其他变量。这些值由 @env('NAME') 读取,通常位于 config.kscript 中;除非某个变量已经设置,否则它们也会成为环境变量,因此 KScript.AI 能在 .env 中找到 ANTHROPIC_API_KEY。请勿将 .env 文件提交到 git。
用户自己的设置。桌面应用可以让用户更改设置而无需修改项目:在kscript.json中使用"app": { "user_config": true },应用配置文件夹中的config.json会覆盖其他所有设置(参见应用文件夹)。
config 会以其他选项重新读取设置,或将另一组设置读入某个变量。若不使用 into,则会改变 $config:
<config env="production" />
<config files="themes/dark.json" into="theme" /> <!-- a separate set of settings in $theme -->
<config files="settings.json, secrets.kscript?, .env?" prefix="SHOP_" defaults="{ server: { port: 8080 } }" require="database.host" />config(env: 'production')
config(files: ['themes/dark.json'], into: theme) // a separate set of settings in $theme
config(files: ['settings.json', 'secrets.kscript?', '.env?'], prefix: 'SHOP_', defaults: { server: { port: 8080 } }, require: ['database.host'])files 列出要读取的其他文件(代替项目自身的文件):JSON 设置文件、配置脚本以及 .env 文件,按顺序读取,每个文件后可跟其对应环境的版本(settings.staging.json)。没有扩展名的名称表示其 .json 文件,以 ? 结尾的名称则可以缺失。使用 prefix 时,环境变量会覆盖文件中的设置,且 __ 会进行嵌套:SHOP_DATABASE__HOST=db.internal 设置 database.host,而 true、false 和 8080 等值会转换为布尔值和数字。root 是这些文件所在的文件夹,defaults 会为未被任何文件设置的项填充默认值,require 列出必须设置的项,user: true 还会读取用户自己的设置。
$config->sources() 列出已读取的文件,$config->all() 以映射形式给出所有设置,$config->reload() 则重新读取它们。@parse_env(text) 解析 .env 文本,KScript.IO 则添加 @read_env(path)。
kscript serve 不会提供 kscript.json、kscript.<env>.json、脚本、.env 文件或 config.* JSON 文件。页面可以读取项目的设置,并可对其 .env 文件中的值使用 @env(),但不会改动进程环境。
日志记录:$log
每个脚本都有一个日志记录器。info 及以上级别的条目会输出到终端(stderr),直到你为它们设置其他去处为止:
<log>Import started</log>
<log level="warn" category="payments" fields="{ order: $order.id }">Card declined for {$customer.name}</log>
<do>$log->info('Saved', { id: $id, size: $bytes })</do>
<let name="db" value="$log->named('db')->with({ host: $config.database.host })" />
<do>$db->debug('Connected')</do> <!-- category db, with a host field -->
<if $log->is_enabled(debug)>
<do>$log->debug($everything->convert(to: json))</do>
</if>
<try>
<do>@read_json(./missing.json)</do>
<catch as="err">
<do>$log->error('Could not read the file', $err)</do> <!-- error, error_type and error_line fields -->
</catch>
</try>log "Import started"
log(level: warn, category: 'payments', fields: { order: $order.id }) "Card declined for {$customer.name}"
$log->info('Saved', { id: $id, size: $bytes })
$db = $log->named('db')->with({ host: $config.database.host })
$db->debug('Connected') // category db, with a host field
if $log->is_enabled(debug) => $log->debug($everything->convert(to: json))
try {
@read_json(./missing.json)
} catch err {
$log->error('Could not read the file', $err) // error, error_type and error_line fields
}级别为 trace、debug、info、warn、error 和 fatal。提供程序决定条目的输出位置,通常在配置中设置:
// kscript.json
{
"config": {
"logging": {
"level": "info", // the lowest level written (default info)
"levels": { "db": "debug" }, // per category; db also covers db.queries
"providers": [
{ "type": "console", "level": "warn" }, // stderr, coloured at a terminal; stream: stdout, format: json, time: HH:mm:ss.fff
{ "type": "file", "path": "logs/app.log", "format": "json" }, // text, or json lines; roll: daily writes app-2026-11-20.log
{ "fn": "notify", "level": "error" } // a fn in the script, called with each entry
]
}
}
}log_provider(…) 可从脚本中添加一个提供程序,选项与之相同(replace 会移除已设置的提供程序,包括默认的控制台提供程序)。memory 提供程序会为 $log->entries() 保留日志条目,这在测试中很有用。被提供程序暂存的条目(例如 http 批量发送的条目)会在脚本结束时或调用 $log->flush() 时发送。若某个提供程序失败,其错误会在 stderr 上报告一次,其他提供程序继续运行。
Packages add provider types with p.LogProvider("type", description, create), and programs that run KScript can add their own with host.Logs.AddProvider(provider, level), where a provider implements ILogProvider.
翻译:@t()
将翻译放在脚本旁边的 locales 文件夹中(或放在站点文件夹中):locales/en.json、locales/fr.yaml,或者每个语言区域一个文件夹,例如 locales/de/shop.json,其键以 shop. 开头。
# locales/fr.yaml
hello: Bonjour, {name} !
cart:
items:
"=0": Votre panier est vide
one: "{count} article"
other: "{count} articles"<locale set="fr" />
<echo>{ @t('hello', { name: $user.name }) }</echo> <!-- Bonjour, Ann ! -->
<echo>{ @t('cart.items', { count: $cart->count() }) }</echo> <!-- 3 articles -->
<echo>{ @format_currency($total, 'EUR') } { @format_date(@today(), 'long') }</echo> <!-- 9,50 € 20 novembre 2026 -->locale(set: 'fr')
echo "{ @t('hello', { name: $user.name }) }" // Bonjour, Ann !
echo "{ @t('cart.items', { count: $cart->count() }) }" // 3 articles
echo "{ @format_currency($total, 'EUR') } { @format_date(@today(), 'long') }" // 9,50 € 20 novembre 2026- 复数形式。使用
count时,@t()会依据该语言自身的规则选择zero、one、two、few、many或other。这些是英语、法语、葡萄牙语、俄语、乌克兰语、波兰语、捷克语、阿拉伯语、希伯来语、爱尔兰语、威尔士语、日语、中文、韩语等语言的 CLDR 规则。精确形式(如=0)优先。 - 回退。若缺少某个翻译,会依次在
fr-CA、fr以及默认语言区域(除非另行设置,为en)中查找。若各处都找不到,则返回键本身,并在i18n类别下记录一次警告。 - 区域设置来自
locale(set: fr),来自locale(from: …)(与列表或 Accept-Language 请求头最匹配的可用项),来自$config.i18n.locale,来自KSCRIPT_LOCALE,或来自计算机的语言。@locale()会提供它,@locales()会列出存在文件的所有区域设置。设置区域设置的路由或中间件,会在其中选定其响应所用的@view(),并优先于请求所要求的语言,因此站点可以让自己的 Cookie 优先于浏览器的设置。 - 页面按以下顺序选择语言区域:路径前缀(当存在法语翻译时,
/fr/about会以法语提供about.html)、?lang=fr、langCookie,最后是浏览器的 Accept-Language。@locale_path($request.path, 'de')会给出指向同一页面德语版本的链接。默认语言区域没有前缀。 - 格式化。这些会遵循当前语言区域,或遵循作为最后一个参数传入的语言区域:
@format_number(1234.5)输出 1,234.5 或 1 234,5;@format_percent(0.25);@format_currency(9.5, 'GBP');@format_date(date, 'short' | 'medium' | 'long' | 'full' | 'time' | 'datetime' | 'd MMMM yyyy');@format_relative(date, from?)输出 3 hours ago、in 2 days 或 just now,除非给出from:,否则以当前时间为基准;@format_duration(1h30m)输出 1 hour 30 minutes;@format_list(['tea', 'coffee', 'milk'])输出 tea, coffee and milk,使用style: 'or'时输出 tea, coffee or milk;@format_ordinal(23)输出 23rd,法语中输出 23e;@format_bytes($file.size)输出 1.4 MB,使用binary: true时输出 1.3 MiB。
- 设置:配置中的
i18n: { folder: lang, default: en-GB, locale: fr },或translations(folder: lang, default: en-GB)。@has_t(key)检查某个键是否有翻译,@plural(count)则给出复数类别。
相对时间、时长、列表和序数的词语已为英语、法语、德语、西班牙语、意大利语、葡萄牙语和荷兰语内置。对于其他语言,或要修改这些词语,请在对应的翻译文件中添加这些键:time.second 至 time.year(带复数形式),以及 {count}、time.ago 和 time.in(配合 {time}、time.now、list.and、list.or),还有 ordinal(配合 {count}):
# locales/pl.yaml
time:
hour: { one: "{count} godzina", few: "{count} godziny", many: "{count} godzin" }
ago: "{time} temu"包
KScript.Core(上述全部内容)始终可用。其余功能均来自包,在脚本顶部导入,因此脚本只加载它所使用的部分:终端脚本永远不会加载 Web 服务器。
<import package="KScript.Terminal" />
<import package="KScript.Math" as="math" /> <!-- commands stay under the prefix: @math.sqrt(2) -->
<import path="lib/strings.kscript" as="str" /> <!-- another script's top-level functions and constants -->
<import names="slugify" path="lib/strings.kscript" />
<!-- … -->import KScript.Terminal
import KScript.Math as math // commands stay under the prefix: @math.sqrt(2)
import "lib/strings.kscript" as str // another script's top-level functions and constants
import slugify from "lib/strings.kscript"
// …只能导入 .kscript 和 .ks.xml 文件。脚本自行声明的函数优先于导入的同名函数,导入的 const 仍保持为常量。
| 包 | 它的新增功能 |
|---|---|
KScript.Terminal |
input(into, type, default, secret)(类型可为email、handle、uuid或password)、picker(文件或文件夹路径)、menu(options, multiple)、progress(into, total)搭配->advance()、confirm、pause、clear、@color(text, color: 'green')、@bold、@dim、@underline、@terminal_width()、@is_terminal()(输出为管道时不适用)、echo(format: markdown),以及kscript命令行自身的外观:info、success、warn、alert(type: error)、heading、detail(name)、bullets(items)、task(name) { }、table(rows, columns, header, align)(参见终端输出) |
KScript.Math |
@sqrt @round(x, digits: 2) @clamp(x, min: 0, max: 10) @logarithm @sin @cos @atan2 @hypot @gcd @factorial @random(low: 1, high: 6) @random_bytes(16, format: hex) @random_generator(seed) @pick @shuffle @sum @average @median @stdev @variance @mode @percentile(values, 95), $pi $e |
KScript.IO |
@read_text @read_lines @read_json @write_text @append_text @write_json @files(folder, pattern: '*.txt', recursive) @folders @file(path) @exists @join_path(base: $dir, ['a', 'b.txt']) @known_folder(downloads),@move(from, to) @copy(from, to) @delete(path) @create_folder(path)。文件值具有字段 .name .extension .mime .size .modified……以及方法 ->read_text() ->read_bytes() ->read_json(as:) ->sha256() ->write_text(text) ->copy_to(path) ->move_to(path) ->delete()。 |
KScript.Net |
使用@api(url, options: { method, headers, body, timeout })发送 HTTP 请求,或使用简写形式post:、put:、patch:、delete:、bearer:、timeout:、retries:、as:、encoding:(json、form 或 multipart)以及query:。响应包含.status、.is_ok、.text、->convert(from: json)和->check()。另外提供@download(url, to)和@query_string。诸如'/api/notes'之类的路径会访问项目自身的路由。参见调用你自己的 API。 |
KScript.Markdown |
@markdown(text) 和 @read_markdown(path)(front matter 中的 html、title、meta),->convert(from: markdown, to: html) |
KScript.Web |
使用布局、组件和 kscript serve 的实时块渲染页面。页面无需导入即可使用 KScript.IO、KScript.Markdown 和 KScript.Web。 |
KScript.AI |
@llm(prompt, system, schema, tools, model, max_tokens)、llm(into, system, schema, tools, model, max_tokens)、@chat(system),配合->ask() .history ->reset(),以及用于测试的@fake_llm(replies)。Claude 使用来自ANTHROPIC_API_KEY的密钥(参见语言模型)。 |
KScript.Style |
用 KScript 编写的样式表(.ks.css、.ks.scss、.ks.sass);@up、@down、@between、@rem、@fluid、@adjust_lightness、@lighten、@darken、@mix、@alpha、@contrast_color、@css_var、@css_vars;@stylesheet(path, vars)(参见样式表)。 |
KScript.Http |
用于kscript serve的路由、控制器与中间件:Routes { }文件包含Get Post Put Patch Delete Any Route Resource Group Middleware。控制器使用@view、@response、@redirect、@abort和@route。参见路由、控制器与中间件。 |
KScript.Storage |
应用自身的文件夹,位于各平台的正确位置:@storage(config)(另有 data、cache、state、logs),包含 ->read ->read_json ->write ->write_json ->read_bytes ->write_bytes ->file ->move ->copy ->append ->list ->delete ->folder ->path_of,另外还有 @app_name() 和 @app_folders()。请参阅 应用文件夹。 |
KScript.Cache |
$cache(内存中)以及带有@cache(file)的->get->set->remember(key, fn, ttl: 10m)->has->remove->increment->ttl->keys->clear。参见缓存。 |
KScript.Data |
使用model存储记录,通过查询构建器进行查询,并使用Migration和kscript db migrate管理架构变更。请参阅数据库。 |
KScript.Queue |
使用job声明后台工作,用->dispatch()将其加入队列,并用kscript worker运行。其Schedule会在设定的时间运行任务。参见队列和作业与调度任务。 |
KScript.Mail |
通过 SMTP 发送带有 @send_mail(to:, subject:, html:|text:|view:) 的电子邮件,可以发送到日志或模拟器,立即发送,或通过 kscript worker 使用 queue 发送。@fake_mail() 会保留邮件用于测试。另请参阅 邮件。 |
KScript.Auth |
为 kscript serve 应用登录:@register、@attempt、@login、@logout、@user()、@is_signed_in()、$session(->get ->set ->flash …)、@users()、@csrf_field()、@reset_token、@reset_password、@api_token,以及 auth 和 guest 中间件。参见 登录。 |
KScript.Document |
Document(template: paper, to: 'paper.pdf') { } 与 Section、Paragraph、List、Table、Figure、Math、Bibliography 等;Letter 和 Invoice;->save ->pages ->words ->markdown ->latex ->html。参见 文档。 |
KScript.UI |
Window { } 块可以打开一个桌面窗口。Column Row Grid Text Button TextBox CheckBox Select Slider Box Spacer Timer,@close_window()。参见 桌面应用。 |
KScript.Test |
test、describe、before_each、after_each、expect、expect_error、capture、@assert、@fail、@run_script、@check_script。测试文件会自行导入它(参见 测试脚本)。 |
使用未导入包中的内容时会以 input is part of KScript.Terminal. Add import KScript.Terminal at the top of the script. 停止,编辑器会提供添加导入的选项。包只能在 import 中命名:语句绝不会写成带 KScript. 前缀的形式(写 input,而不是 KScript.input),并且不会静默导入任何内容,包括 job 和 dispatch(import KScript.Queue)。项目可以为 kscript.json(见下文)中的每个脚本导入包。
加密安全的随机字节
@random_bytes(count, format: hex) 从操作系统读取熵。传入 1 到 65536 之间的整数字节数。小写十六进制每字节使用两个字符。base64url 格式使用 URL 安全字符且省略填充。两种格式都与 @random_seed() 无关。
<import package="KScript.Math" />
<let name="key" value="@random_bytes(16)" /> <!-- 32 hex characters -->
<let name="url_token" value="@random_bytes(16, format: base64url)" /> <!-- 22 characters -->import KScript.Math
$key = @random_bytes(16) // 32 hex characters
$url_token = @random_bytes(16, format: base64url) // 22 characters根据种子生成随机数
@random_generator(seed) 会生成一个生成器,在每台机器上、每个 KScript 版本中,对于相同的种子,它每次都给出相同的数字,因此由它生成的内容日后可以重建:例如为某个人制作的谜题,或测试数据。种子是至少 16 字节的十六进制文本,因此哈希值是很好的种子,而 ->hmac($secret) 可使不知道密钥的人无法推算出它。各部分之间使用 @char_of(0) 分隔,可使 'ab' + 'c' 与 'a' + 'bc' 互不干扰:
<import package="KScript.Math" />
<let name="rng" value="@random_generator(['2026', 'L1', 'player-7']->join(@char_of(0))->hmac('season-secret'))" />
<let name="roll" value="$rng->int(1, 6)" /> <!-- a whole number from 1 to 6 -->
<let name="is_rare" value="$rng->float() < 0.1" /> <!-- true one time in ten -->
<let name="colour" value="$rng->pick(['red', 'green'])" /> <!-- one of the items -->
<let name="order" value="$rng->shuffle([1, 2, 3, 4])" /> <!-- a shuffled copy -->import KScript.Math
$rng = @random_generator(['2026', 'L1', 'player-7']->join(@char_of(0))->hmac('season-secret'))
$roll = $rng->int(1, 6) // a whole number from 1 to 6
$is_rare = $rng->float() < 0.1 // true one time in ten
$colour = $rng->pick(['red', 'green']) // one of the items
$order = $rng->shuffle([1, 2, 3, 4]) // a shuffled copy->next() 返回 0 到 4294967295 之间的整数,->float() 返回小于 1 的小数。该生成器是 sfc32,以前 16 字节作为四个大端 32 位字进行播种,并先运行 15 次,因此以相同方式播种的 JavaScript sfc32 会给出相同的数字。它速度快且分布良好,但如果有人看到足够多的输出,就能推算出其余的数字:对于机密内容,请使用 @random_bytes()。
语句和参数的命名
所有包中的语句及其参数都遵循同一套规则,kscript check 和测试套件会检查内置语句是否符合这些规则:
| 规则 | 示例 |
|---|---|
执行某项操作或声明某项内容的语句,使用小写的 snake_case 单词。 |
input, table, before_each, expect_error, log_provider |
在 KScript.UI、KScript.Http 和 KScript.Document 中描述窗口、路由表或文档的语句使用 PascalCase。在 KScript.Data 中,Migration 及其架构步骤也使用 PascalCase。 |
Button, Routes, Get, Section, Migration, CreateTable |
参数使用 snake_case。任何名称都不含连字符。 |
max_tokens, must_exist, on_click, new_page |
into: 是接收结果的变量。 |
input(into: name), llm(into: reply), capture(into: out) |
to: 表示目标位置:文件、URL 或控制器。它绝不表示变量名。 |
Get(path: /, to: @home), Post(path: /notes, to: @notes.add) |
path: 是语句读取或操作的文件。 |
import(path: 'lib.kscript'), <include path="_nav.html">, <layout path="_layout.html"> |
at 是一个位置,如 for item at i in $list 中所示。 |
menu(into: choice, at: i) |
函数的写法为 @name,与表达式中的写法相同。 |
spawn(fn: @job), llm(tools: [@order_status]), Get(to: @people.show) |
有三类名称不是函数,保持裸写:控制器(Resource(to: people) 是脚本被导入时使用的名称)、中间件列表中的名称([log, throttle:30, my_check],其中内置项、分组和函数共享同一列表),以及被声明的变量或类型。在 XML 中,相同的参数以同名属性形式出现,函数则不带 @ 书写(<spawn fn="job" />);kscript convert 用于添加和移除它。
在页面中,on-click 及其他事件处理器位于 HTML 标签上(<button on-click="$count += 1">),因此保留 HTML 的连字符。在 KScript 自有元素上,例如 Button,参数为 on_click。
采用这些规则之前的旧名称会报错并提示新名称('to' is now into.),kscript check --fix 可将其重命名。允许语句被赋值($name = input "Name? ")尚未成为该语言的一部分。
终端输出
KScript.Terminal 的打印方式与 kscript 命令相同,因此脚本的输出看起来与该工具的其他部分一致。颜色仅在终端中使用:管道输出、文件和测试得到的是不含颜色的相同文本,NO_COLOR、FORCE_COLOR、--ansi 和 --no-ansi 的作用与其对 kscript 本身的作用相同。
<import package="KScript.Terminal" />
<let name="people" value="[{ name: 'Joan', age: 82 }, { name: 'Sam', age: 9 }]" />
<heading>Report</heading>
<detail name="People">{ $people->count() }</detail>
<task name="Adding up">
<let name="total" value="1 + 2" />
</task>
<table rows="$people" />
<info>Wrote [report.txt].</info>
<alert type="error">The file [data.csv] is empty.</alert>import KScript.Terminal
$people = [{ name: 'Joan', age: 82 }, { name: 'Sam', age: 9 }]
heading "Report"
detail(name: 'People') "{ $people->count() }"
task(name: 'Adding up') {
$total = 1 + 2
}
table(rows: $people)
info "Wrote [report.txt]."
alert(type: error) "The file [data.csv] is empty."Report
People .................................................... 2
Adding up .......................................... 2ms DONE
┌──────┬─────┐
│ name │ age │
├──────┼─────┤
│ Joan │ 82 │
│ Sam │ 9 │
└──────┴─────┘
INFO Wrote [report.txt].
ERROR The file [data.csv] is empty.标签中的 [bracketed] 部分以粗体显示。alert(type: error) 写入 stderr。表格中的数字右对齐;align: ['left', 'right'] 设置每一列。
分步完成的工作会显示进度条。progress(into: bar, total: n) 以其文本作为标签显示进度条,$bar->advance() 将其推进一步(->advance(5) 则推进五步)。在终端中会原地重绘;管道输出和测试则在达到总数时输出一行,与任务输出类似:
<import package="KScript.Terminal" />
<let name="files" value="['a.csv', 'b.csv', 'c.csv']" />
<progress into="bar" total="$files->count()">Importing</progress>
<for each="_file" in="$files">
<do>$bar->advance()</do>
</for>import KScript.Terminal
$files = ['a.csv', 'b.csv', 'c.csv']
progress(into: bar, total: $files->count()) "Importing"
for _file in $files {
$bar->advance()
}menu(multiple: true) 允许回答选择多个选项,例如 1, 3,并按菜单顺序存储它们的列表(以及 at: 存储它们位置的列表)。
语言模型:KScript.AI
KScript.AI 让脚本可以向 Claude 发起请求。API 密钥来自 ANTHROPIC_API_KEY 环境变量(或来自 ANTHROPIC_AUTH_TOKEN 中的令牌,或在安装了 ant 命令时由 ant auth login 保存的配置文件),而不是来自脚本本身。ANTHROPIC_BASE_URL 会把请求发送到其他主机,例如代理服务器。除非脚本指定了其他模型,或 KSCRIPT_AI_MODEL 指定了某个模型,否则脚本使用 claude-opus-5-5。
<import package="KScript.AI" />
<!-- One question, one answer. -->
<echo>{ @llm('Write a haiku about XML.') }</echo>
<!-- A prompt written as a template, with a system prompt. -->
<let name="customer" value="{ name: 'Ann' }" />
<let name="message" value="'My order is late arrived.'" />
<llm into="reply" system="You answer customer emails politely and briefly.">{$customer.name} wrote: {$message}</llm>
<!-- Structured output: the answer is a map with these fields. -->
<let name="report" value="'The login page spins forever on Safari.'" />
<llm into="ticket" schema="{ category: 'bug|feature|question', urgency: 'int 1-5', summary: 'one line' }">Triage this report: {$report}</llm>
<echo>{$ticket.category} ({$ticket.urgency}): {$ticket.summary}</echo>
<!-- Tools: the model may call your fn functions, and sees what they return. -->
<fn name="order_status" params="id: int" description="The shipping status of an order." value="$id == 42 ? 'shipped' : 'unknown'" />
<llm into="answer" tools="order_status">Where is order 42?</llm>
<!-- A conversation that remembers what was said. -->
<let name="chat" value="@chat('You are a patient maths tutor.')" />
<echo>{ $chat->ask('What is a prime number?') }</echo>
<echo>{ $chat->ask('Is 91 one?') }</echo>import KScript.AI
// One question, one answer.
echo "{ @llm('Write a haiku about XML.') }"
// A prompt written as a template, with a system prompt.
$customer = { name: 'Ann' }
$message = 'My order is late arrived.'
llm(into: reply, system: 'You answer customer emails politely and briefly.') "{$customer.name} wrote: {$message}"
// Structured output: the answer is a map with these fields.
$report = 'The login page spins forever on Safari.'
llm(into: ticket, schema: { category: 'bug|feature|question', urgency: 'int 1-5', summary: 'one line' }) "Triage this report: {$report}"
echo "{$ticket.category} ({$ticket.urgency}): {$ticket.summary}"
// Tools: the model may call your fn functions, and sees what they return.
/// The shipping status of an order.
fn order_status(id: int) => $id == 42 ? 'shipped' : 'unknown'
llm(into: answer, tools: [@order_status]) "Where is order 42?"
// A conversation that remembers what was said.
$chat = @chat('You are a patient maths tutor.')
echo "{ $chat->ask('What is a prime number?') }"
echo "{ $chat->ask('Is 91 one?') }"llm和@llm(prompt, ...)询问相同的问题,选项也相同:system、schema、tools(如[@order_status]这样的列表)、model和max_tokens(默认为 16,000)。唯一的区别在于提示从哪里来、答案放到哪里:llm语句以提示作为其文本,并将答案存入to:;而@llm()以提示作为一个值,并返回答案,因此可以放在表达式中使用。@llm()则按名称接收其选项:@llm($prompt, system: 'Be brief.', max_tokens: 500)。- 模式:每个字段都是必填的。
'string'、'number'、'int'、'bool'和'date'用于指定类型,'int 1-5'给出取值范围,'a|b|c'列出可选值,映射是嵌套对象,['string']是列表,其他任何文本都表示字符串字段。 - 工具是
fn函数。它们的params(包括id: int等类型)和description会告诉模型如何调用它们。如果某个工具失败,模型会收到错误信息,并可以继续执行。 - 测试使用
@fake_llm(replies)代替Claude:参见模拟语言模型。 - 错误的类型为
AI,因此可以使用try配合catch e来检查$e.type,并处理缺失的密钥、请求被拒绝,或回答因max_tokens被截断的情况。当 Claude 的安全检查拒绝某个请求时,API 会先用备用模型重试该请求。
脚本如何运行
kscript 会在每个语句块第一次运行时将其编译,因此循环或被多次调用的函数会作为 .NET 代码运行,而不必每次都重新读取。在函数体或循环体内,代码块声明的变量保存在编号槽位中,而不是作用域中,这使得以数字为主的代码(例如背包问题、网格搜索、模拟)快了数倍。包含循环的代码体,或已运行 64 次的代码体,随后会被再次编译为单个 .NET 方法,因此对数字的紧凑循环又快了约两倍。该方法中,若循环的工作内容是数字和列表(算术运算、比较、读取和设置列表项、if、while,以及对范围使用 for),还会生成第二个副本,该副本将其变量视为恰好是这种类型,因此速度还会快数倍;一旦某个值结果不是这种类型,循环就会从同一语句起,转入通用副本继续运行。若函数将 fn(x) => ... 传给诸如 ->map() 之类的方法,只要回调读取的每个变量在调用回调之前都已设置一次,该函数同样保留其槽位。诸如 0..1000000 之类的范围循环会直接计数遍历,而不生成列表。脚本本身的任何行为都不会改变:相同的值、在相同行列位置报出的相同错误;调试器仍会逐条语句单步执行,因为被调试的脚本始终是解释执行的。
有几个环境变量可用于比较它们,例如在报告仅在其中一种模式下出现的 bug 时:KSCRIPT_INTERPRET=1 会关闭编译,KSCRIPT_NO_REGIONS=1 会编译但将每个变量都保留在作用域中,KSCRIPT_NO_TREES=1 保留槽位但从不生成单个 .NET 方法,KSCRIPT_NO_LOOPS=1 会生成该方法但不生成其循环的第二个副本。
编写可移植的脚本
- 使用
@join_path(base: $dir, ['reports', 'file.txt'])(KScript.IO)构建路径,而不是硬编码\或/。 - 使用
@known_folder(downloads)(KScript.IO)查找用户的文件夹:home、desktop、documents、downloads、music、pictures、videos、appdata或temp。它会遵循各系统自身的设置,例如 Windows 的下载位置和 Linux 的user-dirs.dirs。 $os.name是windows、linux或macos,$os.home、$os.temp和$os.separator也在其中;$env.HOME用于读取环境变量。- 无论机器使用何种语言,数字始终以
.作为小数分隔符进行解析和输出。