Why is my for loop code not working as i expected?

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

Hi i just came back to godot after using unity and still a little fresh on the c# coding.So what happened was , i was making an inventory system using for loop to check each slot’s script to check wheter the variable item in that script is null and if it is add self to that inventory but when i run the code i expected it to go through one slot(The first one)then add itself as the child and stop the code but instead it ran through every slot and added itself as i child in the last slot (Expected as i expected but in backwards order)so i was wondering what went wrong?
var a = [a.item,b.item,c.item]

extends Node2D

Declare member variables here. Examples:

var a = 2

var b = “text”

onready var a = get_parent().get_node(“GridContainer/Panel”)
onready var b = get_parent().get_node(“GridContainer/Panel”)
onready var c = get_parent().get_node(“GridContainer/Panel3”)
onready var d = get_parent().get_node(“GridContainer/Panel4”)
onready var e = get_parent().get_node(“GridContainer/Panel5”)
var G = [a.item,b.item,c.item,d.item,e.item]
func _ready():
pass # Replace with function body.

Called every frame. ‘delta’ is the elapsed time since the previous frame.

#func _process(delta):

func _on_TextureButton_pressed():
for x in G:
if x == 42:

this is my code rn to check how things work so far it doesnt even work
so the basic premise here is to check how the for loop runs but it doesnt work for that
because the premise of onbase nil on the array g so it basically couldnt find the .item part

It’s a typo in op or you really have if a == null: in your code? It should be if f == null:

Reloecc | 2020-09-13 05:42

when its indented right it should work.

var a = [a.item,b.item,c.item]

for f in a:
   if a == null:

this could shed some light on it. just setp into when execution is halted.

klaas | 2020-09-13 08:51

As Reloecc pointed out, a will never be null because it’s already the array.

Magso | 2020-09-13 09:26

I think your intent was to write something like:

onready var slots = $Inventory/Slots

func add_item(item):
   for slot in slots:
      if slot.item == null:
         slot.item = item

But you’ve shown no code, we can’t help you without more info.

Reloecc | 2020-09-13 17:48

Yea i tried but it says on base nil or something like that plus pretty sure it will go through all the slots before running the code

AwYiss | 2020-09-14 04:12

sorry yea its a typo

AwYiss | 2020-09-14 04:13

:bust_in_silhouette: Reply From: Reloecc

onready var is executed after var G = [..]

When the G is being prepared all variables from a to eare nulls. You may keep var G: Array in its current line, but move G = [..] beneath func _ready():