Search code examples
lualove2d

Lua math.random explain


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


Solution

  • 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.