Page 1 of 1

[solved] math.random problem

Posted: Tue Sep 06, 2011 3:45 am
by thebatzuk
Hey, I'm very new to Lua and LOVE and this forum ^^ ... so I've got this piece of code:

Code: Select all

function new_enemies()
	local enemy = {}
	for i = 1,nof_enemies do
		enemy.radius = math.random(10, 35)
		enemy.x = math.random(0 + enemy.radius, 800 - enemy.radius)
		enemy.y = math.random(0 + enemy.radius, 200)
		enemy.segments = math.random(4, 15)
		table.insert(enemies, enemy)
	end
end

math.randomseed(os.time())
enemies = {}
nof_enemies = 3
new_enemies()
print("i,   e.radius,  e.x,    e.y,    e.segments")
for i,e in ipairs(enemies) do
	print(i, e.radius, e.x, e.y, e.segments)
end

(I use that code inside some more code in a LOVE project but I put it alone to run it faster in Lua)

It's supposed to make three random 'enemies' with some properties (x, y, radius, ...) but it keep giving me three groups of the exact same numbers. If you run that on Lua you get something like this:

Code: Select all

C:\Users\Raul\p\lua>rnd.lua
i,   e.radius,  e.x,    e.y,    e.segments
1       27      216     43      8
2       27      216     43      8
3       27      216     43      8

C:\Users\Raul\p\lua>rnd.lua
i,   e.radius,  e.x,    e.y,    e.segments
1       15      643     22      8
2       15      643     22      8
3       15      643     22      8


I need the three groups to be different. I hope you can help me.

Re: math.random problem

Posted: Tue Sep 06, 2011 3:55 am
by BlackBulletIV
That's because you're using the same table for all three enemies. Tables don't get copied, they're referenced. What you should be doing is this:

Code: Select all

function new_enemies()
	for i = 1,nof_enemies do
		local enemy = {}
		enemy.radius = math.random(10, 35)
		enemy.x = math.random(0 + enemy.radius, 800 - enemy.radius)
		enemy.y = math.random(0 + enemy.radius, 200)
		enemy.segments = math.random(4, 15)
		table.insert(enemies, enemy)
	end
end
Also, I usually call math.random three times after setting the seed. I think some people have reported that on their system it takes a few uses for it to get random, though I believe it's a rare problem.

Re: math.random problem

Posted: Tue Sep 06, 2011 4:14 am
by thebatzuk
Wow, thank you very much. It's working now!

Maybe I'll post the complete code of my game when it's ready. It's something simple (and not very original) about a triangle as a spaceship and some polygons as asteroids enemies.

Re: [solved] math.random problem

Posted: Tue Sep 06, 2011 4:22 am
by BlackBulletIV
No worries. Good luck on your game!

Re: [solved] math.random problem

Posted: Tue Sep 06, 2011 5:20 am
by thebatzuk
If anyone got interested on my game, here's the .love

Like I said, is something very simple. Actually it's the second graphic game I ever do.