Thursday, September 4, 2008

AHK - Check if a folder exists

Very simple way of checking if a folder exists, and also making sure that it's an actual folder (not just a file without an extension).
If (InStr(FileExist("Path/YourFolder"),"D")
MsgBox Folder exists!
Else
MsgBox Folder doesn't exist
Forum Post

AHK - The Ternary Operator ( ?: )

This is a short faq/guide about the use of the Ternary Operator in AHK. If you think of anything I should add, please post a comment.
Enjoy :)

1.) What is a Ternary Operator?
A ternary operator is like a shortened if-else statement, that can be used in a one-line expression. For example:
Var := X ? 1 : 0
In English, this can be written as "If X is true, set Var to 1. Else, set Var to 0".


2.) What's the point?
Ternary operators can make code more readable (or sometimes less), and much more compact. For example, would you rather use the previous code or this in your really long script?
If (X)
Var := 1
Else
Var := 0

3.) Can I do if-elseif-else expressions too?
Sadly, no you can't. There is a rather easy workaround for this, but code readability goes downhill fast. The workaround is simply nesting the if statements, for example:
If (X == 1)
Var := 1
Else If (X == 2)
Var := 2
Else
Var := 0
Could be written as
If (X == 1)
Var := 1
Else {
If (X == 2)
Var := 2
Else
Var := 0
}
And as a ternary operator, it would look like this:
Var := X == 1 ? 1 : (X == 2 ? 2 : 0)

4.) Does the ternary operator lower speed/performance?
In some cases, it can, but usually by less than 10µs. What does this mean? Nobody but your computer will notice, and it just barely will.
[VxE]'s := guide ? ( to the ternary ) : ( operator ), Ternary Operator Documentation

AHK - GetGlobal()

This is a simple function for manipulating a global variable in a function that doesn't have assume-global mode on.
GetGlobal(var,newval="£NO_NEW_VAL£")
{
Global
If (!RegExMatch(var,"^[a-zA-Z0-9#_@\$\?\[]]{1,254}$"))
Return 0
If (newval == "£NO_NEW_VAL£")
Return % %Var%
Else {
%var% := newval
Return 1
}
}

Example:
FuBar = Hello World!
Message()

Message() {
MsgBox % GetGlobal("FuBar")
}

Tuesday, September 2, 2008

AHK - Send() - My custom send function

This function allows you to insert pauses in your text via "{_Sleep ####}" added anywhere in your text, where "####" is the number of milliseconds to sleep/pause. You can also set the mode (ie. play, event) with the Mode parameter, omit this parameter to use the default.
Send(Text,Mode="") {
If (Mode)
SendMode %Mode%
FoundPos := 0
Loop {
If (!FoundPos := RegExMatch(Text,"Ui).*\{_Sleep \d+\}",Match,++FoundPos))
Break
FoundPos += StrLen(Match) - 1
Send % RegExReplace(Match,"Ui)(.*)\{_Sleep \d+\}","$1")
Sleep % RegExReplace(Match,"Ui).*\{_Sleep (\d+)\}","$1")
}
Send % SubStr(Text,FoundPos)
}

Example:
Send("{_Sleep 2000}a{_Sleep 1000}b","Input")