Clearing variables in a loop

Godot Version

4.2 stable

Question

I want to understand exactly how this thing works
I make a loop through some array and in it I add a variable to change it for each button when it is pressed:

for v: String in some_array:
	var new_button := BUTTON_SCENE.instantiate()
	new_button.name = v
	container.add_child(new_button)
	
	var state := false
	
	new_button.pressed.connect(func() -> void:
		state = !state
		print(state) # always true
	)

And the variable always prints false. I understand that at the end of each time in this loop the variables and other are cleared, but how the button refers to a variable that has already been cleared?

How exactly does it work and how to do it more correctly? And for example if it’s not an object and you can’t just add a meta to it

1 Like

Because the state variable reset in each loops, so do like this:

# CustomButton.gd
extends Button

var state: bool = false

func _ready():
	self.pressed.connect(_on_pressed)

func _on_pressed():
	state = !state
	print(state)

# Main script
for v: String in some_array:
	var new_button := preload("res://CustomButton.tscn").instantiate()  # Assuming you have a scene with CustomButton.gd attached
	new_button.name = v
	container.add_child(new_button)

Or also you can try like this

var state := false

for v: String in some_array:
	var new_button := BUTTON_SCENE.instantiate()
	new_button.name = v
	container.add_child(new_button)
	new_button.pressed.connect(func() -> void:
		state = !state
		print(state) # always false
	)

Note: The first way is generated by AI but the ^^^ second ^^^ way is by me

2 Likes

And how exactly does it work from the signal? A variable is created and the function in the signal is cleared… How does she see this variable and… where else can I put this variable? (I just don’t want to create a lot of scripts)

Most nodes inherit from Object including Button. Object has a set_meta() and get_meta() to create a variable-like entity inside your Object.

set_meta("state", false)   
print(get_meta("state"))   
set_meta("state", !get_meta("state"))

Note that there are some pitfalls with this method. Read the docs on the meta functions.

1 Like

rofl that ai generated one is bad, you can just use _pressed function