1

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

1
  • Another common way to do a 50-50 chance is to use math.random() < 0.5. Commented Sep 28, 2022 at 16:47

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

2 Comments

Only correct if first is truthy.
@LMD you're right, didn't think of that
0

For a better understanding, a look at lua documentation helps a lot : https://www.lua.org/pil/3.3.html

You can read: The operator or returns its first argument if it is not false; otherwise, it returns its second argument:

So if the random number is 1 it will return the first argument (100) of the "or" otherwise it will return the second argument (-100).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.