Skip to content

GDScript: make Self reference the current script (i.e. class)

Bernhard Liebl requested to merge github/fork/poke1024/gdscript-self-class into master

In GDScript scripts, to reference a script class itself, one needs to call get_script():

extends Reference

class A:
	...

func something_new(C):
	return C.new()

func my_func():
	var x = something_new(A)
	var y = something_new(get_script())

This is a bit ugly, as inner classes are referenced by their name (as in any other language), but the script itself needs get_script().

This PR suggests adding a constant Self that refers to the script/class, making the code above read:

extends Reference

class A:
	...

func something_new(C):
	return C.new()

func my_func():
	var x = something_new(A)
	var y = something_new(Self)

This constant is only added on demand when it's first accessed. I believe it adds a lot of consistency as it makes up for the missing script class name in a consistent way.

This change works fine and is small; my one mini-caveat is that this might add a circular reference somewhere that hinders the script from deleting; not completely sure about that (codegen.script->constants takes a plain GDScript* though).

Might address part of https://github.com/godotengine/godot/issues/12719 by var Base = Self (though I'm not sure I really understand it fully).

Merge request reports