Iterating over a string in a for loop

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By g
:warning: Old Version Published before Godot 3 was released.

I’m working with the following code:

	for digit in str(game.score_current):
	    var texture_frame = TextureFrame.new()
	    texture_frame.set_texture(sprite_numbers[int(digit)])
	    add_child(texture_frame)

When game.score_current is 0, two children are added. I have confirmed that the string is “0” (no spaces/padding) and that the for loop is entered twice. What am I doing wrong?

The code you posted looks fine.
Maybe the error is in another part of the script.
Do you get any error messages?
What exactly is sprite_numbers ?

atze | 2016-09-21 15:38

No error messages… sprite_numbersis an array containing textures:

const sprite_numbers = [
    preload("res://sprites/number_large_0.png"),
    preload("res://sprites/number_large_1.png"),
    preload("res://sprites/number_large_2.png"),
    preload("res://sprites/number_large_3.png"),
    preload("res://sprites/number_large_4.png"),
    preload("res://sprites/number_large_5.png"),
    preload("res://sprites/number_large_6.png"),
    preload("res://sprites/number_large_7.png"),
    preload("res://sprites/number_large_8.png"),
    preload("res://sprites/number_large_9.png")
]    

Maybe the problem is my understanding of the for loop? I just tested with for digit in "0" and I get the same result.

g | 2016-09-21 15:45

Hm,

for me the code:

for digit in "0":
	print(digit)

works just fine(only prints the number once). Did you check if the function just get called twice, by adding a print before the for loop and after it?

Nophlock | 2016-09-21 17:19

:bust_in_silhouette: Reply From: Hinsbart

This is a known issue and has already been fixed in the master branch.
The next 2.1.x maintenance release should include this fix.

Reference:
Issue
PR

Oh I switched to a nightly build a while ago, which explains why it worked for me. Good to know ^^

Nophlock | 2016-09-21 18:48