Math.random() get a nil value? (SOLVED)

Hi Guys

Here i have a new problem when i am trying use math.random() to create a random coordinate for the game object.

but the function always output a nil value.
i try all of these code below, but the result was all the same -nil

self.random_top = math.random(10,15)
self.random_top = math.random()
self.random_top = math.randomseed(10000)

[edit]
i put these functions in the update function ,will got a nil result
but in the init function ,it output a right value.

the problem is , i am trying to create a game object out of screen ,then it moves in.
so I have to get screen height or width value first in the render script, but in the init function ,the render is not run yet? so i cannot get the screen value

Have you tried printing directly?

print('Random:', math.random())

If you have variable passing issues, print these variables first and see if they are nil.

Can you post your update function?

sure ,the update code is

function update(self, dt)
	-- Add update code here
	-- Remove this function if not needed
	self.role_pos = role_position
	self.random_top = math.random(screenW+50,screenW+150)
	print(random_top)
	self.pos = vmath.vector3(random_top,screenH+50,0)
	
	self.to_role_angle = math.deg(math.atan2(self.role_pos.y - self.pos.y, self.role_pos.x - self.pos.x))
	print(to_role_angle)
end

to sergey.lerg
I also tried your ways,but not works ,too

	self.random_top = math.random(screenW+50,screenW+150)
	print(random_top)

The first line sets the variable “self.random_top” to a value.

The second prints a variable called “random_top”, which is a different variable. Since it has not been initiated yet it’s nil. Change this to print(self.random_top).

3 Likes

WOW,sorry,i make a rookie mistake…
Now I fixed it,thanks!

1 Like