Omit Function Parameter Under Condition?

Get help with using AutoHotkey (v2 or newer) and its commands and hotkeys
User avatar
Coiler
Posts: 114
Joined: 29 Nov 2020, 09:06

Omit Function Parameter Under Condition?

Post by Coiler » 09 Apr 2021, 07:36

How would I do something like the following?

Code: Select all

SubStr( str, start, (stop==0 ? () : (stop - start)) )
My intention is to access the remainder of the string in cases where stop==0. As far as I can tell, SubStr() doesn't have any specific value that represents "the rest of the string", other than omitting the value. Is there a special AHK value that I can send to represent nothing?

Thanks!

Edit: Just to make sure I'm clear, I'm wondering if I can accomplish this by specifying some type of null input:

Code: Select all

SubStr( str, start, (stop==0 ? (StrLen(str) + -start + 1) : (stop - start)) )
User avatar
boiler
Posts: 16957
Joined: 21 Dec 2014, 02:44

Re: Omit Function Parameter Under Condition?

Post by boiler » 09 Apr 2021, 08:42

You could do this:

Code: Select all

str := "hello there"
start := 2
stop := 0
MsgBox SubStr(str, start, stop = 0 ? StrLen(str) - start + 1 : stop - start + 1)
(notice also the correction on the math)
lexikos
Posts: 9592
Joined: 30 Sep 2013, 04:07
Contact:

Re: Omit Function Parameter Under Condition?

Post by lexikos » 09 Apr 2021, 22:55

In general, a sub-expression must always produce a single value, or the stack would become unbalanced and the expression would fail to be evaluated correctly. (Load-time syntax checking should prevent this by prohibiting cases like stop==0 ? () : (stop - start).)

If there isn't a better alternative (like boiler showed for SubStr), there are at least two options:
  1. Use two separate function calls - one with the parameter and one without.
  2. Use a variadic call. The array of parameters can be conditional, or you can prepare the array before the call.

    Code: Select all

    Loop 2
        MsgBox SubStr("abc", 2, (A_Index=1 ? [] : [1])*)

    Code: Select all

    Loop 2 {
        args := []
        if A_Index = 2
            args.Push 1
        MsgBox SubStr("abc", 2, args*)
    }
User avatar
kczx3
Posts: 1640
Joined: 06 Oct 2015, 21:39

Re: Omit Function Parameter Under Condition?

Post by kczx3 » 10 Apr 2021, 07:00

@lexikos neat! I hadn’t considered passing an empty array. Good tip.
Post Reply

Return to “Ask for Help (v2)”