Skip to content

Commit

Permalink
Safe Navigation: Improve first example, note that null coal is used i…
Browse files Browse the repository at this point in the history
…n the second example
  • Loading branch information
Sainan committed Nov 17, 2023
1 parent e76ec26 commit fbbb62b
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions docs/New Features/Safe Navigation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.

Expand Down

0 comments on commit fbbb62b

Please sign in to comment.