Lynn Len
Lynn Len

Reputation: 111

godot invalid get index '-1'(on base 'array') during A.P.I

I'm making an A.P.I. that displays dialogue, choices, sprites, audio etc. etc., i was able to do it after looking up this video on youtube but i keep getting this error invalid get '-1' (on base 'array') here's my code so you can see

    extends Control 

onready var bg_rect = get_node("Media_Sys/BG_Rect")
onready var char_sprite = get_node("Media_Sys/Sprite")
onready var text_box = get_node("Dialog_Sys/Dialog_Text")
onready var text_nam = get_node("Dialog_Sys/Label/Name")
onready var click = get_node("ClickManager")

var player = []

var lu = "Lu"
var ciel = "Ciel"

func _ready():
    click.request_ready()


func write(char_name_str, text_str=null):

    if text_str == null:

        text_str = char_name_str
        char_name_str = ""

    player.push_front({"type": "dialogue","name": char_name_str, "text": text_str})

func write_component():

    text_nam.clear()
    text_box.clear()
    text_nam.add_text(player[player.size() - 1]["name"])#the debugger says the problem is here
    text_box.add_text(player[player.size() - 1]["text"])#as well as here if you remove the first line.
    player.pop_back()

func _input(event):

    if event is InputEventMouseButton:

        write_component()

I have some people say that it's because i didn't define the size of the array, i have some people say that it's really weird that my code somehow set the player as an integer. I've check the array docs page for this and came up with nothing, I've changed some minor things in the code but it still churns out the same invalid error.

extends Node

onready var g = get_parent()

var lu = "Lu"
var ciel = "Ciel"


func _ready():
    g.write(lu, "hello")

One thing to note is that it does display the dialogue and name, i just get the error immediantly afterwards.

Upvotes: 0

Views: 4866

Answers (1)

Nikolaj Baer
Nikolaj Baer

Reputation: 359

You initialize the player variable to be an empty list. Then, in write_component you attempt to access this list with the calculated index [player.size() - 1]. The issue is that if player is empty, this ends up as [0-1] or [-1] as an index, which is not valid in GDScript. Your code assumes Write will be called first (and it may, some of the time) so that player is not empty by the time write_component is called.

The most immediate solution is to check if player.size() == 0 before attempting to access the last element.

func write_component():
    text_nam.clear()
    text_box.clear()
    if player.size() > 0:
        text_nam.add_text(player[player.size() - 1]["name"])
        text_box.add_text(player[player.size() - 1]["text"])        
        player.pop_back()

Upvotes: 1

Related Questions