name.remove() problem with @ symbol in an array

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

This is my function that detects what loot I got and add the corresponding bonus. When I have lots of loot on screen, they get the “@num” that screws my function, so I made this workaround to remove the @ and the numbers from the name, and it works:

func _picked_item(name,value):
	name = name.replace("@","")
	var replace_array:Array = ["0","1","2","3","4","5","6","7","8","9"]
	for i in replace_array.size():
		name = name.replace(i,"")
  prints------> name

But for some reason, if I add the “@” to the array (and remove

name = name.replace("@","")

from the start), it no longer removes the “@” from names… It makes no sense to me

func _picked_item(name,value):
	var replace_array:Array = ["@","0","1","2","3","4","5","6","7","8","9"]
	for i in replace_array.size():
		name = name.replace(i,"")
 prints---->  @name@

I know it’s not a big deal, I just really want to understand why the “@” inside the array wont remove it, but will outside the array normally…

the rest of the function goes like:

if name == "ShieldDrop": immunity_duration += value if immunity_duration < 0.75 else 0.0
if name == "HealthDrop": PlayerData.health += value if PlayerData.health < PlayerData.MAX_HEALTH else 0
if name == "SpeedDrop": shoot_rate -= value if shoot_rate > 0.2 else 0.0
if name == "DoubleShotDrop": bullet_type = value
if name == "TripleShotDrop": bullet_type = value
:bust_in_silhouette: Reply From: MrEliptik

It works in the first case because your loop is using i which is a number, because you’re looping from 0 to the array size. In the second case it doesn’t work because I will be 0, 1, 2, etc… but not @. If you want to correctly use the values of your array you have two choices:

for val in replace_array:
    name = name.replace(val, "")

Or

for i in range(replace_array.size()):
    name = name.replace(replace_array[i], "")

thanks! I see what you did there :wink:

Surtarso | 2021-03-20 20:51