Lua math.random explain

Viewed 61

sorry for asking this question but I couldn't understand it

-- but i don't understand this code
ballDX = math.random(2) == 1 and 100 or -100
--here ballDY will give value between -50 to 50 
ballDY = math.random(-50, 50)

I don't understand the structure what is (2) and why it's == 1

Thank you a lot

3 Answers

math.random(x) will randomly return an integer between 1 and x.

So math.random(2) will randomly return 1 or 2.

If it returns 1 (== 1), ballDX will be set to 100.

If it returns 2 (~= 1), ballDX will be set to -100.

A simple way to make a 50-50 chance.

In lua

result = condition and first or second

basically means the same as

if condition and first ~= nil and first ~= false then
    result = first
else
    result = second
end

So in your case

if math.random(2) == 1 then
    ballDX = 100
else
    ballDX = -100
end

in other words, there is a 50/50 chance for ballDX to become 100 or -100

That is a very common way of assigning variables in Lua based on conditionals. It’s the same you’d do, for example, in Python with “foo = a if x else b”: The first function, math.random(2), returns either 1 or 2. So, if it returns 1 the part math.random(2) == 1 is true and so you assign 100 to the variable ballDX. Otherwise, assign -100 to it.

Related