Hello everybody.

Please, could you tell me what's wrong with this code?

func generate_unique_numbers(total_numbers:int, start:int, end:int)->Array:
	
	#if total_numbers > end-start:
	# removed other checks for clarity
		#return []
	
	var temp = []
	
	while temp.size() < total_numbers:
		
		var r = randi_range(start, end)
	
		if temp.find(r) > -1:
			temp.append(r)
			
	return temp

var t = generate_unique_numbers(13, 0, 26)

Basically, this code crashes Godot, but I don't know why (maybe the problem is that I don't get enough sleep) :-)

Thanks

  • I see a couple of problems, but I'm not sure if they would cause a "crash".

    This appends r to the Array if r is found in the Array. Was that your intent?

    if temp.find(r) > -1:
        temp.append(r)

    The function is returning a reference to the local variable temp. I don't know if that reference remains valid after the function returns. You probably should return a copy of the Array by returning temp.duplicate(). (incorrect)

I see a couple of problems, but I'm not sure if they would cause a "crash".

This appends r to the Array if r is found in the Array. Was that your intent?

if temp.find(r) > -1:
    temp.append(r)

The function is returning a reference to the local variable temp. I don't know if that reference remains valid after the function returns. You probably should return a copy of the Array by returning temp.duplicate(). (incorrect)

    DaveTheCoder Arrays are reference types in Godot (Godot 3 at least, but I don't think that changed with Godot 4). Therefore the array will remain valid as long as there is at least one variable referencing it. No need to copy anything.

    Thanks. I just did a test that verified that Arrays behave as you describe.

    Nothing crashes here 🙂. It's just a good old endless loop. You probably want that > replaced with ==.

    Get in the habit of putting a print() statement inside loops that behave strangely. That way you'll se how many times the loop's body gets executed. It's one of the most basic and most useful debugging techniques.

      xyz Of course, I initially thought the problem was randi_range because I've seen different implementations, using randomize() and a RandomNumberGenerator (so, for a while, I suspected I needed to use randi_range in a different way). But, a little try ouside the loop, showed me I was in error. @DaveTheCoder question (Was that your intent?), shifted my attention to the if block. Thanks for your kind reply.

      I always considered printing a primitive debugging technique, but I print all the time, except when I haven't slept for 32 hours :-D

      Good night, @xyz