Feature Request: Add Optional Chaining (?.) Operator to Factorio Lua
Posted: Fri Nov 29, 2024 9:15 am
I would like to request the addition of the optional chaining (?.) operator in the Lua environment used by Factorio. This feature, allows for safe property access on potentially nil values, helping to simplify and streamline code when dealing with deeply nested objects.
It would be a great addition to the scripting environment, making code more concise and reducing the need for multiple if checks for nil values. It would also improve error handling and code readability.
an example demonstrating the difference between using the `?.` (optional chaining) operator and not using it.
Here, we need to explicitly check each level (`player`, `player.gui`, and `player.gui.screen`) for `nil` before trying to access `main_frame`. If any of these is `nil`, accessing `main_frame` would result in an error.
In this case, if `player`, `player.gui`, or `player.gui.screen` is `nil`, `main_frame` will automatically be set to `nil` without throwing an error. This makes the code much cleaner and more readable, especially for deeply nested structures.
With ?. : The operator handles nil checks automatically, simplifying the code and improving readability.
It would be a great addition to the scripting environment, making code more concise and reducing the need for multiple if checks for nil values. It would also improve error handling and code readability.
an example demonstrating the difference between using the `?.` (optional chaining) operator and not using it.
Without Optional Chaining:
in environments like Factorio where `?.` is not available, you need to manually check if each part of the chain is `nil` before accessing properties.Code: Select all
-- Without optional chaining
local main_frame
if player and player.gui and player.gui.screen then
main_frame = player.gui.screen.main_frame
end
if main_frame then
-- Do something with main_frame
else
-- Handle the case where main_frame is nil
end
Here, we need to explicitly check each level (`player`, `player.gui`, and `player.gui.screen`) for `nil` before trying to access `main_frame`. If any of these is `nil`, accessing `main_frame` would result in an error.
With Optional Chaining (?.):
With the `?.` operator, this process becomes much more concise. You don't need to manually check each layer for `nil`, as the operator automatically returns `nil` if any part of the chain is `nil`.Code: Select all
-- With optional chaining
local main_frame = player?.gui?.screen?.main_frame
if main_frame then
-- Do something with main_frame
else
-- Handle the case where main_frame is nil
end
Summary:
Without ?. : You need to manually check each level of the object chain to prevent errors.With ?. : The operator handles nil checks automatically, simplifying the code and improving readability.