How to use inner classes properly?

Godot Version

4.2

Question

extends Node2D

class Test:
	func _init(a: int, b: String) -> void:
		self.a = a
		self.b = b

func _ready() -> void:
	var c = Test.new(0, "abc")
	print(c.a, c.b)

Why doesn’t the code run as intended? :face_with_diagonal_mouth: (This is the minimal reproducible example of my other code)
I got the error Invalid set index 'a' (on base: 'RefCounted (Test)') with value of type 'int'. I have no idea what the message mean, and I failed to find anything related to this in the documentation (GDScript reference — Godot Engine (stable) documentation in English).


Thanks in advance. :grinning:

Because your inner class doesn’t declare those variables. You need var a and var b below class Test:

1 Like
class Foo:
	var a:int
	var b:int
	func _init(a:int, b:int):
		self.a = a
		self.b = b

Class needs fields. The index is a field in a class object.

1 Like

Thanks! Problem solved! :grinning: :grinning: :grinning:

extends Node2D

class Test:
	var a: int
	var b: Array[int]
	
	func _init(a, b) -> void:
		self.a = a
		self.b = b
	
	func test_method():
		return self.b

func _ready() -> void:
	var c = Test.new(0, [1, 2, 3])
	print(c.test_method())


Can I ask a followup question? Why is assigning a ok, but assigning b failed? It’s so strange. :thinking: Thanks for your reply. :+1:

Probably because [1, 2, 3] is a Variant, not an explicitly typed array. Try [1, 2, 3] as Array[int]
It’s also good to type the parameters of functions.

func _init(a: int, b: Array[int]) -> void:
2 Likes

As a followup to the answer above which is correct. is dynamic in basically any language, runtime languages like gd script have type inference, that is why you thought it would work.

Although to have strict typing the compiler needs to know what the arguments(passed into the method)types are for the inference to happen, it doesn’t read the item’s type in the Array, it needs the explicit type which is given by:

b: Array[int]

then

as Array[int]

is the compiler argument type cast(hint).

1 Like

@Efi @teotigraphix Thanks! It worked after adding the type! But what about Array[Array[int]]? (Error: Nested typed collections are not supported.)

Sadly, that kind of typing is not available. You’ll have to type it as Array or Variant and enforce the typing at runtime. =/

1 Like