Page 1 of 1
is there a simple one-line way to write an if statement?
Posted: 26 Jan 2022, 23:46
by cgx5871
Ask a simple question weakly, is there a simple one-line way to write an if statement? For example: if a=1 then gosub xxx
Re: is there a simple one-line way to write an if statement?
Posted: 26 Jan 2022, 23:58
by flyingDman
or with "else" condition
Code: Select all
a := a=1 ? 2 : "" ; if a is = 1 then a = 2 else a is an empty string
Re: is there a simple one-line way to write an if statement?
Posted: 27 Jan 2022, 00:32
by amateur+
I think you may mean ? instead of &&
Re: is there a simple one-line way to write an if statement?
Posted: 27 Jan 2022, 00:40
by cgx5871
flyingDman wrote: ↑26 Jan 2022, 23:58
or with "else" condition
Code: Select all
a := a=1 ? 2 : "" ; if a is = 1 then a = 2 else a is an empty string
That was not what I meant
like this:
if a=1 then gosub xxx
Re: is there a simple one-line way to write an if statement?
Posted: 27 Jan 2022, 00:42
by flyingDman
@amateur+ No, I meant &&
Run this:
Re: is there a simple one-line way to write an if statement? Topic is solved
Posted: 27 Jan 2022, 00:51
by flyingDman
You can try:
Code: Select all
gosub % a = 1 ? "label1" : "label2"
Re: is there a simple one-line way to write an if statement?
Posted: 27 Jan 2022, 02:11
by william_ahk
Alternatively, there's a two line way to write this:
Re: is there a simple one-line way to write an if statement?
Posted: 27 Jan 2022, 02:50
by BoBo
That was not what I meant
like this:
if a=1 then gosub xxx
Code: Select all
!a::
Random, a, 0, 1
(a=1) ? goSub(1) : goSub(0)
SoundBeep
Return
goSub(x) {
MsgBox % x
}
JFTR
Re: is there a simple one-line way to write an if statement?
Posted: 27 Jan 2022, 04:08
by boiler
amateur+ wrote: ↑
I think you may mean ? instead of &&
It works as an “if” condition because
short-circuit evaluation is applied by
&& and
||.
Re: is there a simple one-line way to write an if statement?
Posted: 27 Jan 2022, 08:34
by amateur+
@flyingDman, @boiler, wow that's nice. I even didn't know about this trick, thanks!
Also we can use (a = 1) || a := 3 as alternatives to:
If a != 1
a := 3
or
(a != 1) && a := 3
It is strange that (a = 1) ? a := 2 also works although ternary operator is built to include false-branch too.