Recursive spawner



I have a factory which creates every X second a game object in a liste of positions possible. I used a recursive function to spawn each elements but nothing gets created. That’s my piece of code:

local spawned = { nil, nil, nil, nil, nil, nil, nil }

function spawn(position)
	position_id = math.random(table.getn(positions)) -- position is an array of coordinates

	if spawned[position_id] ~= nil then
		position.x = positions[position_id][1] -- position is declared with local in update() and has the value: go.get_position()
		position.y = positions[position_id][2]
		position.z = 1
		spawned[position_id] = true

		return { position, position_id }

From test I made, it seems that it nevers gets in the ifbut gets into the else, creating an infinity loop.




My bad, the condition was the issue:

if spawned[position_id] ~= nil then

This should have been:

if spawned[position_id] == nil then

EDIT: although, sometimes, I have this error: attempt to index local 'p' (a nil value). pis used this way: p = spawn(). Does anyone know where it could come from?

EDIT 2: after logging spawned, I get those kind of arrays:

{ --[[000001FB297DA500]]
  1 = true,
  2 = hash: [/instance3],
  3 = hash: [/instance3],
  4 = true,
  5 = hash: [/instance2],
  6 = true,
  7 = true

Why aren’t all values booleans?

EDIT 3: adding the line spawned_detritus[self.d] = new_detritus was the issue. Sorry for this topic. I guess sharing helped and made me think and test to try to give the more information here. Things are working fine now :slight_smile: .

EDIT 4: I thought that everything was okay but in fact, it was the logging of the array which made “hid” the errors. I still have attempt to index local 'p' (a nil value). I really don’t get it :slightly_frowning_face: .



Share an updated version of the code so that we can take a look.



The ”else” part of the if statement doesn’t return anything specific, so it returns nil.



That was it, thank you :smiley: ! I’m sorry I didn’t see it.

1 Like