Page 1 of 1

ShortIf

Posted: Mon Sep 28, 2020 11:17 am
by Jac de Lad
Hi,
I know this from other languages and would like to see it here too: ShortIf (or whatever it would be called). This is a statement with a single command if it is true. No endif, no else or whatever. This shortens instructions that only need one call after the condition:

Code: Select all

If IsImage(image)
  FreeImage(image)
EndIf
or

Code: Select all

If IsImage(image):FreeImage(image):EndIf
would become

Code: Select all

ShortIf IsImage(image):FreeImage(image)

Re: ShortIf

Posted: Mon Sep 28, 2020 11:27 am
by #NULL
Why not name if ShorterIf instead? Then it's 1 character longer than the normal version instead of 1 character shorter :mrgreen:

Re: ShortIf

Posted: Mon Sep 28, 2020 11:44 am
by chi
I'd prefer something similar to the ternary operator from C/C++ so we could write an If/Else statement in one line!

Re: ShortIf

Posted: Mon Sep 28, 2020 12:02 pm
by Kiffi
I bet that this can be solved with a macro.

Re: ShortIf

Posted: Mon Sep 28, 2020 12:23 pm
by BarryG
As Kiffi said, a macro can do this:

Code: Select all

Macro ShortIf(condition,action)
  If condition : action : EndIf
EndMacro

CreateImage(0,640,480)

Debug IsImage(0) ; 37685600
ShortIf(IsImage(0),FreeImage(0))
Debug IsImage(0) ; 0
And this is what happens if it fails:

Code: Select all

Macro ShortIf(condition,action)
  If condition : action : EndIf
EndMacro

CreateImage(0,640,480)

Debug IsImage(0) ; 37685600
ShortIf(IsImage(1),FreeImage(0)) ; Image 1 doesn't exist, so FreeImage is ignored.
Debug IsImage(0) ; 37685600

Re: ShortIf

Posted: Mon Sep 28, 2020 12:24 pm
by BarryG
chi wrote:I'd prefer something similar to the ternary operator from C/C++ so we could write an If/Else statement in one line!
What do you mean? You can do this already.

Re: ShortIf

Posted: Mon Sep 28, 2020 1:51 pm
by chi
BarryG wrote:
chi wrote:I'd prefer something similar to the ternary operator from C/C++ so we could write an If/Else statement in one line!
What do you mean? You can do this already.
Yes, we can! But only with If:Else:Endif keywords or by creating a Macro + Procedure (for each data type) and I'm talking about the shortest possible syntax...


Something like this

Code: Select all

If a < b : c = 34 : Else : c = 12 : EndIf
or this

Code: Select all

Procedure IIFEval(boolean, y, n)
  If boolean : ProcedureReturn y : Else : ProcedureReturn n : EndIf
EndProcedure

Macro IIF(expr, y, n)
  IIFEval((Bool(Not(Bool(expr)))), n, y)
EndMacro

c = IIF(a < b, 34, 12)
would become

Code: Select all

c = (a < b) ? 34 : 12
and should also work for strings (floats, doubles, ...)

Code: Select all

c.s = (a < b) ? "true" : "false"
c.f = (a < b) ? 0.34 : 0.12