From fbbb62bd614e37ccec95b39f10af6aa1c23fca94 Mon Sep 17 00:00:00 2001 From: Sainan Date: Fri, 17 Nov 2023 21:29:45 +0100 Subject: [PATCH] Safe Navigation: Improve first example, note that null coal is used in the second example --- docs/New Features/Safe Navigation.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/New Features/Safe Navigation.md b/docs/New Features/Safe Navigation.md index 5af7402c7..e74e48283 100644 --- a/docs/New Features/Safe Navigation.md +++ b/docs/New Features/Safe Navigation.md @@ -3,9 +3,14 @@ sidebar_position: 17 --- Accessing deeply nested fields which can potentially be `nil` was problematic, because you'd need an unreasonable amount of guard clauses to prevent an "attempt to index nil" error. Pluto now offers this syntax: ```pluto showLineNumbers title="Basic Usage" -local value = a?.b?.c?.d +local person = { + name = "Alice" +} + +local pet_name = person.pet?.name ``` -In this example, every field is nil. However, this does not throw an error. It simply returns `nil`. Without safe table navigation, this would've returned several "attempt to index nil" errors. +In this example, `person.pet` is nil. However, this does not throw an "attempt to index nil" error. `pet_name` is simply set to `nil`. + ```pluto showLineNumbers title="Practical Usage" -- Pretend userConfig is parsed from a JSON file, or something. @@ -16,6 +21,8 @@ end print(get_color()) ``` +In this example, we also use the null coalescing operator `??`. + :::info These cannot be used for statements, like `a?.b?.c = 0`. They're only valid as expressions.