Search code examples
lua

Variable declaration that I don't understand in Lua


I was reading some Lua and doing a little course to use it with Löve 2D, in an example they give declare a variable this way, which I honestly do not understand:

ballDX = math.random(2) == 1 and 100 or -100

I've tried to google and read a bit but haven't found a place to specifically explain that. Looking at what it says I identify the obvious, BallDX is equal to a random number between 1 and 2, but from there I get quite confused, what does it mean that the random number is equal to 1 and 100 or -100?


Solution

  • This is a kinda interesting Lua concept

    The operator and returns its first argument if it is false; otherwise, it returns its second argument.

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

    In this case math.random(2) == 1 and 100 or -100 behaves exactly like a ternary operator, it can translate to:

    If math.random(2) equals to 1, set ballDX = 100, otherwise set ballDX = -100

    For example, assume you had a variable called c, and you want to assign it a value only if a variable is above 10, with a ternary operator you would do this: c = a > 10 ? a : b

    In Lua you would use c = a > 10 and a or b