Only String or StringName can be used as index for type "Node", but received a "int"

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

I get this error: Only String or StringName can be used as index for type “Node”, but received a “int”

Here is the code:

func _on_word_timer_timeout():
var poemText := get_node(“Text”)
var text := poemText

if (charCount + 1 < text.length() && (text[charCount] != '\n' || text[charCount + 1] != '\n') || charCount + 1 == text.length()):
	if text[charCount] != '\n':
		poemText.visible_characters += 1
	charCount += 1
	pageLock = false
	charCount += 1
:bust_in_silhouette: Reply From: HyperlinkYourHeart

The variable text is a Node because you just set it the same as poemText, so it can’t be indexed with an int. Did you mean to do:

var text := poemText.text

When I use this [var text:= poemText.text]

I get the error :Cannot infer the type of “text” variable because the value doesn’t have a set type.

givenmnisi6 | 2023-06-12 15:43

You just need to skip the type inference then:

var text = poemText.text

HyperlinkYourHeart | 2023-06-12 15:53

what is type inference? i do not know it please clarify more

givenmnisi6 | 2023-06-12 15:55

When you use the := operator to set the value of a variable, you are saying that the variable will only be used for values of the same type you are setting it to. This is called “type inference” because the type is inferred from the value you are setting it to, instead of declaring it explicitly.

There are two alternatives. You can declare the type of the variable explicitly, like this:

var text: String

Or, you can initialise the variable with no type, using the = operator:

var text = poemText.text

The error you got is telling you that the text property of poemText doesn’t have a set type, so the type can’t be inferred from it - you have to leave your text variable untyped.

You can read more about variables and types here.

HyperlinkYourHeart | 2023-06-12 16:04

Oh okay, I understand, now it works. Thank you, you are a star!

givenmnisi6 | 2023-06-12 16:09