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? (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).
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())
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.
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: