GDScript - Idiosyncrasies

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

Hi all, I’m playing around with GDScript and some of it’s behaviours strike me as a bit odd, can anyone please help explain the correct way to achieve the following:

var a;
var b = a || "a is undefined"
print(b) #Expected: "a is undefined" Got: True
 
var a = [0,1,2,3]
print(a[4]) # Expected: undefined/null Got: An Error

var a = "abcd"
var b = a.split("")
print(b) #Expected: ["a", "b", "c", "d"] Got: ["abcd"]

Additionally, is there anyway to iterate over an array and get the element and index at the same time, i.e:

var a = [1,2,3]
for e, i in a:
 print(i, e)
#0, 1
#1, 2
#2, 3

Thanks!

Please, read the rules, this is not generic “chat” site.
You should form exact single (wherever it possible) question per topic and name it accordingly, thus exact problem could be covered and found by others.

Try https://gdscript.com/

sash-rc | 2022-07-27 13:02

:bust_in_silhouette: Reply From: omggomb

My take:
var b = a if a else "a is undefined" a.k.a ternary operator. There is a proposal for a null-coalescing operator: GDScript idea: add a null-coalescing operator, which returns first non-null value · Issue #7223 · godotengine/godot · GitHub

print(a[4] if 4 < len(a) else null) Giving an error is the correct behavior in my opinion. Out of bounds access is usually the sign of a bug.

For the third you need to use the RegEx class:

var regex = RegEx.new()
regex.compile(".")
var results = []
for result in regex.search_all("abcd"):
    results.push_back(result.get_string())
print(results)

I don’t think the forth one is possible. Will have to use plain old index for that:

for i in len(a):
   print("%d %s" % [i, a[i])

Sounds a bit like you’re used to Python. Keep in mind that GDScript only looks like Python but is actually a different language with different idioms. Reading through the docs is very worthwhile.