How do I add "fallback" values if initial value is null?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Y_VRN

I came from using Lua, and in the language, I can do something like this:

local X = nil
local Y = "Yes" -- "fallback"

local Z = X or Y -- This

If X is nil/null, then check if Y should be used. I can even make it a long chain too:

local X, Y, Z, A, B, C = nil, nil, nil, 2, "String", true

local Final = X or Y or Z or A or B or C

print(Final) -- should print the value of A, since it is the first variable in the chain to have a value.

Currently, I’m stuck in GDScript trying to achieve something similar to Lua. What I have in mind only is to use if-statements, but that would be too messy for me. Is there a way to do something similar to Lua? As in…

func Function(Name):
    var N = Name or "Default"

GDScript always outputs a boolean (mostly “True”) instead of the value I want.

Thanks in advance.

:bust_in_silhouette: Reply From: Ninfur

As far as I know this is not currently possible in GDScript. There is however an open issue on github for adding support for a null-coalescing operator.

Your best bet right now is probably a combination of default arguments, if-statements and the ternary operator.

Thanks for the GitHub link, looks like I found something that works close to what I wanted! Although a tiny bit messier than what I was expecting, it works.

The given workaround goes like this…

var A = null
var B = 3

var C = A if A else B # B is chosen.

Y_VRN | 2022-07-01 09:04