godot: GDScript 2.0: typed variables no longer nullable?

Godot version

4.0 beta 2

System information

Windows 10, x64, standard build

Issue description

In Godot 3, it was possible to have a typed variable be null. You could for example define a variable as null and later assign a String, or you could pass null to a function that takes a typed parameter such as Material. In Godot 4, this causes a type error.

Steps to reproduce

The following script worked in Godot 3 (replace instantiate with instance):

extends Node

var next_screen_path = null

func _physics_process(_delta):
	if next_screen_path != null:
		var new_screen_res = load(next_screen_path) as PackedScene
		
		if !new_screen_res:
			push_error("No scene at " + next_screen_path)
			next_screen_path = null
			return
		
		var child = get_child(0)
		
		if child:
			child.free()
		
		var new_screen = new_screen_res.instantiate()
		add_child(new_screen)
		
		next_screen_path = null
		return

func set_screen(screen_path : String):
	next_screen_path = screen_path

In Godot 4, this gives Line 7: Invalid argument for "load()" function: argument 1 should be String but is null.

Changing line 3 to var next_screen_path : String = null also does not work: Trying to assign value of type 'Nil' to a variable of type 'String'.

Can types no longer be nullable in GDScript 2? What would it take to make them nullable again? Perhaps we need nullable syntax like in C# (int?), or is this simply a bug in the interpreter?

Minimal reproduction project

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 2
  • Comments: 15 (15 by maintainers)

Most upvoted comments

Object-based variants (Object, RefCounted, Resource, Node, etc.) can be null. var something: Node = null is a valid code. You can even have a method argument like that and pass nulls to methods that take Object-based arguments.

Non-object variants (String, int, Array, etc.) can’t be null. You can assign a null to a variable that is not typed though. var something = null - valid var something: String = null - not valid

There is a proposal to make everything nullable: https://github.com/godotengine/godot-proposals/issues/162

btw most of the validation is done on the GDScript side. Internally a String property can have null assigned sometimes, but this is a bug.