While writing this little function, I made a number of big errors, making me wonder what was going on...
Instead of keeping my shame for me, I thought I should also share my errors, as seeing them may help some people to avoid these traps...
Here is the erroneous function:
debugF = debug.txt
; Same test code
IncrementName(nameNoExt)
{
MsgBox => %nameNoExt%`n%debugF%
FileAppend => %nameNoExt%`n, %debugF%
Loop
{
StringRight d, nameNoExt, 1
StringTrimRight nameNoExt, nameNoExt, 1
FileAppend %A_Index% - %d%`n, %debugF%
If d between 0 and 8
{
d++
dd = %d%%dd%
FileAppend %A_Index% - %dd%`n, %debugF%
Break
}
Else If (d = 9)
{
dd = 0%dd%
FileAppend %A_Index% - %dd%`n, %debugF%
}
Else
{
; Not a digit
nameNoExt = %nameNoExt%%d% ; put back non digit char
; Must add a 1
nameNoExt = %nameNoExt%1
Break
}
}
FileAppend => %nameNoExt%%dd%`n, %debugF%
Return %nameNoExt%%dd%
}
As you can see, since the MsgBox returned empty strings, I added some internal MsgBox and FileAppend to see what didn't worked...
I was stumped to see neither messages nor new file...
Do you know what were my errors (you can guess by comparing with the correct code, so don't look right now). There are three big mistakes.
.
.
.
First error: I still get bitten by the PHP-like scope of global variables.
I forgot to put a
global or
local d, dd declaration on top of the function. So debugF isn't visible and the FileAppend silently fails to append to an empty filename.
Second error: I like to omit the initial comma, it gives a Visual Basic flavor... I knew that the initial comma must be present if the first parameter is omitted (a quite rare case). But I fall into a not so obvious trap: MsgBox =xxx and FileAppend =xxx are really assignments of strings to variables having the same name as the commands... So they did nothing... Bad choice of debug string prefix!
Third error: I knew that
Return var and
Return %var% are synonym. I am not sure where I got this information as it is not documented in the Return page... Probably seen it in a script.
Anyway, Return argument must actually be an expression, except in the above exception. I wrote
Return %nameNoExt%%dd% which actually built a variable name corresponding to the concatenation of the strings, and returned the value of the variable, which was empty of course.
Note to Chris: the error message box showing lines from the faulty script have a curious problem that make me wonder if my function, returning empty string, was actually called.
For example:
x := F("z")
MsgBox %x%
F(_)
{
r = /%_%\
Return %r%t
}
I get:
---------------------------
test.ahk
---------------------------
Error: This variable or function name contains an illegal character. The current thread will exit.
Specifically: /z\t
Line#
012: x := F("z")
013: MsgBox,%x%
016: {
017: r = /%_%\
---> 018: Return,%r%t
019: }
020: Exit
020: Exit
---------------------------
OK
---------------------------
Good message, but the function name is absent!
Note also the duplicated Exit line (20)...