变量与输出
<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 接收的文本是唯一的例外:其中的 { } 会作为参数发送,而绝不会直接粘贴进去(参见 数据)。