Conditional index operator

Consider a script that needs to access the local player’s character’s head position. There are two ways to write this:

local position = game.Players.LocalPlayer and game.Players.LocalPlayer.Character and game.Players.LocalPlayer.Character:FindFirstChild('Head') and game.Players.LocalPlayer.Character.Head.Position

--- or ---

local localplayer = game.Players.LocalPlayer
local character = localplayer and localplayer.Character
local head = character and character:FindFirstChild('Head')
local position = head and head.Position

Both of these solutions are grotesquely verbose. I want an operator like javascript’s ?. that can conditionally access a value. With such an operator, the above code becomes easily readable:

local position = game.Players.LocalPlayer?.Character?:FindFirstChild('Head')?.Position

I want the operator to perform the index operation if the left-hand value is truthy. If it’s falsey, it should just return nil instead of performing an index.

19 Likes

This has previously been proposed in December and has been officially merged as a RFC, meaning it is coming!

https://github.com/Roblox/luau/blob/master/rfcs/syntax-safe-navigation-operator.md

18 Likes