One line if statements

Propose new features and changes
User avatar
PuzzledGreatly
Posts: 1303
Joined: 29 Sep 2013, 22:18

One line if statements

09 Nov 2013, 02:48

The answer is probably no, but could this be possible:

Instead of

Code: Select all

if EG is not number
	EG = 6
Could we just use a single line:

Code: Select all

if EG is not number,  EG = 6
User avatar
nnnik
Posts: 4500
Joined: 30 Sep 2013, 01:01
Location: Germany

Re: One line if statements

09 Nov 2013, 03:13

Have you heard about our awesome ternary operator?

Code: Select all

EG:= (eg~="^\d$"?EG:6)
Recommends AHK Studio
User avatar
PuzzledGreatly
Posts: 1303
Joined: 29 Sep 2013, 22:18

Re: One line if statements

09 Nov 2013, 04:02

nnnik wrote:Have you heard about our awesome ternary operator?

Code: Select all

EG:= (eg~="^\d$"?EG:6)
Thanks, I hadn't. I'm finding that code you gave hard to grasp. Help says there should be a space on either side of the ? but I notice there isn't in your code.
User avatar
smorgasbord
Posts: 493
Joined: 30 Sep 2013, 09:34

Re: One line if statements

09 Nov 2013, 04:23

the same code works for me fine :)
EG := A
MsgBox % EG:= (eg~="^\d$"?EG:6)

EG := 0
MsgBox % EG:= (eg~="^\d$"?EG:6)
John ... you working ?
Coco
Posts: 771
Joined: 29 Sep 2013, 20:37
Contact:

Re: One line if statements

09 Nov 2013, 05:00

You can use one-liner if statement(s) in AHK v2
Help says there should be a space on either side of the ?
it's for compatibility reasons , as per help file. It's up to you if you put spaces or not. I prefer to put spaces..:D
Option(s) aside from RegEx:

Code: Select all

MsgBox, % (Abs(var) != "") ? "Number" : "Not a number"
MsgBox, % (var+0 == var) ? "Number" : "Not a number"
Or to imitate if var is number:

Code: Select all

MsgBox, % (var ~= "^[-+]?\d+(\.\d+)?$") ? "Number" : "Not a number"
User avatar
nnnik
Posts: 4500
Joined: 30 Sep 2013, 01:01
Location: Germany

Re: One line if statements

09 Nov 2013, 07:09

You'll have to update AHK if you need the spaces.
Recommends AHK Studio
Wade Hatler
Posts: 60
Joined: 03 Oct 2013, 19:49
Location: Seattle Area
Contact:

Re: One line if statements

09 Nov 2013, 12:31

Agree on the ternary operator. I use it about 90% of the time when I would be tempted to make a 1-line if statement. In fact, I usually do that even in languages that do have 1-line if statements.

One minor caution. The examples above are just how I do it, but eg~="^\d$" is not the same as eg is number. It only checks for positive integers. If you want to simulate is number it needs to be a more sophisticated regex, or you need to make an IsNumber function (there's an example in the help).

Return to “Wish List”

Who is online

Users browsing this forum: No registered users and 54 guests