From b09e2a787554c139a92946448bc3c26a8287c890 Mon Sep 17 00:00:00 2001 From: ValKmjolnir Date: Thu, 6 Jun 2024 23:45:27 +0800 Subject: [PATCH] :memo: update tutorial about new operators --- doc/tutorial.md | 21 +++++++++++++++++++++ doc/tutorial_zh.md | 19 +++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/doc/tutorial.md b/doc/tutorial.md index 2cfef5a..d2af8fc 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -164,6 +164,27 @@ a &= 0xca; a |= 0xba; ``` +Operator `??` is used to check left hand side value is `nil` or not, if not, +return the right hand side value: + +```javascript +print(nil??"should get this string"); +``` + +The example above will print `should get this string`. + +Operator `?.` is used to get hash member if left hand side value is not `nil`. +And if left hand side value is not `nil` and not `hash`, +will cause error and exit. + +```javascript +var a = nil; +print(a?.try_get); # nil + +var a = {try_get: "congrats!"}; +print(a?.try_get); # "congrats!" +``` + ## Definition As follows. diff --git a/doc/tutorial_zh.md b/doc/tutorial_zh.md index b6f7070..9500456 100644 --- a/doc/tutorial_zh.md +++ b/doc/tutorial_zh.md @@ -159,6 +159,25 @@ a &= 0xca; a |= 0xba; ``` +`??` 运算符用于检查左侧值是否为 `nil`,如果不是则返回右侧的值: + +```javascript +print(nil??"should get this string"); +``` + +上面的例子会输出 `should get this string`。 + +`?.` 运算符用于先检查左侧不为 `nil`,如果左侧不是 `nil` 则尝试获取 hash 的字段。 +当然如果左侧此时也不是 `hash` 类型,则报错退出。 + +```javascript +var a = nil; +print(a?.try_get); # nil + +var a = {try_get: "congrats!"}; +print(a?.try_get); # "congrats!" +``` + ## 定义变量 如下所示。