Log In  

Aw man, I'm so sorry, I feel really silly... How on earth do you generate a random bool? I can't find any way to cast an int into a bool, so I'm down to doing the sort of stuff below:

randbool=flr(rnd(2))
if randbool==0 then randbool=false else randbool=true end

This feels really dirty and silly. What's the established way of doing this please? And apologies in advance.

Thanks,

Pedro.

P#113684 2022-06-26 18:03

The most concise way I know is:

randbool = rnd() < 0.5

or you can do the following, but it takes more tokens and virtual CPU time because it creates a table of two true and false elements each time.

rndbool = rnd{false,true}

You can avoid the wasted virtual CPU time by declaring a global:

bools = {false,true}

rndbool = rnd(bools)

but now this takes even more tokens.

P#113685 2022-06-26 18:08 ( Edited 2022-06-26 18:10)

Yes that's the way to do it.

You can also do:

randbool = rnd()<.5

which is a bit shorter

P#113687 2022-06-26 18:10

Yes! You posted your message as I was editing my post to simplify my original code to be the same as yours. :-)

P#113688 2022-06-26 18:11 ( Edited 2022-06-26 18:11)

Thank you!!!

P#113691 2022-06-26 18:46

the best solution was shown in previous posts: if you need a boolean (true or false) and you have an expression that evaluates to boolean (like collides(player,other) or rnd()<0.5), then use that boolean directly!

but for cases when you need to check a boolean then assign something else (like strings or numbers), there is a more convenient way than your initial if/then/else/end:
message = thing>2 and "string if true" or "string if false

P#113695 2022-06-26 20:57 ( Edited 2022-06-26 20:58)

Just because we are at it, that last thing @merwok showed is called "ternary" operator in other languages.

num = x==y and 1 or 0

I discovered recently that you can chain these as much as you want

num = x==y and 1  or  x>y and 2  or  3

Which means, if x==y then num=1. if x>y then num=2. Else num=3

P#113753 2022-06-28 08:43 ( Edited 2022-06-28 08:43)

technically it is not quite a ternary operator, but the combination of two binary operators. I learned it as «the and-or trick».

P#113754 2022-06-28 08:45

Can anyone explain how the "ternary operator" works in Lua (note I understand how it works in other languages)

Given the simple example:

num = x==y and 1 or 0

If x and y have the same value, the statement becomes:

num = true and 1 or 0

Why does this assign 1 to num ? I would have thought num would be assigned "true"

P#113765 2022-06-28 15:44
1

it’s explained here: https://www.lua.org/pil/3.3.html

in short: the expression evaluates to true and 1 → 1 or false or 0 → 0

P#113766 2022-06-28 15:46

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-03-28 21:59:14 | 0.019s | Q:25