Tutorial Core Language

From AutoIt Wiki
Jump to navigation Jump to search

This is a tutorial describing the core elements of the AutoIt language.

Comments

Two types of comments tend to exist in every language. Comments are simply lines/blocks of code that are meant as guidelines or notes to help understand what the code is doing.

Inline/Single-line comments may be added using a preceeding semicolon.

; This is a single-line comment
msgbox(1,"Title","Text") ; This is an inline comment

Where as multiline comments are a little less intuitive but just as effective...

#comments-start
  All code within this block is commented and will not be interpretted at compile/run time.
#comments-end

There's also a shorthand method to this.

#cs
 All code within this block is commented as well.
#ce

Variables

Declarations

A variable is a placeholder in memory where we can store some kind of data. In AutoIt the data is a string, number or reference to an array. AutoIt has three keywords to declare a variable. Namely Global, Local and Dim. When we declare a variable we set aside some memory for the variable. All variable names in AutoIt starts with a $ sign. So they are easy spotted in the code.

 Global $gVar
 Local $Var
 Dim $i

Arrays are simply collections of variables stored under a common name using addresses as a means of defining their position within memory. Similar to defining a variable, the only difference in defining an array is expressing the number of elements to be attributed to that collection.

Global $aarr[4] ; 4 elements allocated.
Local  $barr[1] ; 1 element allocated.
Dim    $carr[3] ; 3 elements allocated. ; Try to avoid Dim, use Global and Local.

For more on arrays visit the Arrays Tutorial page.

Scope

Generally speaking, scope pertains to the length of time for which a variable is visible or more precisely how long a variable is stored in memory before it returns to a free state. As such, the allocation(declaration) and deallocation(trash collection) of a variable is usually left up to the compiler/interpreter and occasionally is given to the user to play with. As a rule of thumb, all information stored in memory for a program is deallocated upon completion of the program.

Why is this important? Scope allows a developer to track and reuse variable names for multiple occurances. Imagine having to create a unique name for every single variable stored in memory at that point. You would have to compensate for all the variable names used in the operating system, other programs running parallel to yours, and every name in your own script. It wouldn't be long before randomly generated 256 character names would be more efficient than a list of used names.

With this in mind the three methods of declaring a variable explained above have different scopes in mind:

  • Global variables are given scope over the entire program's run.
  • Local variables have a scope that is immediately related to the block of code they're currently a member of.
  • Dim variables are hybrid-like depending upon whether or not the name is already defined in a global variable status:
    • Global variable exists of the same name
      • Overwrites the Global variable
    • Global variable does not exist
      • Creates a Local variable for that block

Assignment

Assigning a value to a variable is the only way to get things going. Fortunately, AutoIt uses loose typing...

Local $x = "Hi there!"  ; $x is a string
$x = 7                  ; $x is an integer
$x = .15                ; $x is a float
$x = 123456789          ; $x is a double
$x = "Hello again!"     ; $x is back to a string

Loose typing simply means a variable is malleable and its format can be changed to your liking, this also means that you have to watch your scope and what's going in and out of that variable.

Arrays are handled a bit differently. They may contain several different types and those types are loosely typed but the array must have a predetermined size.

Local $y[3]
$y[0] = 1        ; first address is an integer
$y[1] = "two"    ; second address is a string
$y[2] = 3.33333  ; third address is a float

Equivalently

Local $z[3] = [1,"two",3.3333]

Again, for more on arrays see the Arrays Tutorial.

You may also declare and assign several variables at the same time.

 Local $x = 1, $y = "", $z[3] = [1,2,3]

Operators

Assignment

= Assignment operator. e.g. $var = 5
&= Concatenation assignment. e.g. $var &= "Hello" equivalent to $var = $var & "Hello"

Mathematical Operation

+ Addition operator. e.g. 10 + 20
- Subtraction operator. e.g. 20 - 10
* Multiplication operator. e.g. 20 * 10
/ Division operator. e.g. 20 / 10
^ Powers operator. e.g. 2 ^ 4
+= Addition assignment. e.g. $var += 1 is equivalent to $var = $var + 1
-= Subtraction assignment. e.g. $var -= 1 is equivalent to $var = $var -1
*= Multiplicative assignment. e.g. $var *= 2 is equivalent to $var = $var * 2
/= Divisive assignment. e.g. $var /= 2 is equivalent to $var = $var / 2

Mathematical Comparison

= Equivalence operator for numerical values. e.g. If $var = 5 Then ...
== Equivalence operator for string values. e.g. If $string == "string" Then ...
<> Not equal operator. e.g. If $var <> 5 Then ...
> Greater-than operator. e.g. If $var > 5 Then ...
>= Greater-than-or-Equal-to operator. e.g. If $var >= 5 Then ...
< Less-than operator. e.g. If $var < 5 Then ...
<= Less-than-or-Equal-to operator. e.g. If $var <= 5 Then ...

String Comparison

= Equivalence operator. e.g. If $var = "Hi" Then ... ; case insensitive.
== Equivalence operator. e.g. If $var == "Bye" Then ... ; case sensitive.
<> Not equivalent operator. e.g. If $var <> "blah" Then ... ; case insensitive.
Not <>Not equivalent combinative operator. e.g. If Not $var <> "blah" Then ... ; case sensitive.

Logical

And Binary logical And operator. e.g. If $var > 5 And $var < 3 Then ...
Or Binary logical Or operator. e.g. If $var <> 5 Or $var <> 6 Then ...
Not Unary inversion operator. e.g. If Not $var > 5 Then ...

Precedence

All languages have a list of precedences that define when an operator is to be evaluated. Operators with equal precedence are evaluated from left to right.

From highest to lowest:
  '''Not'''
  ''' ^ '''
  '''* /'''
  '''+ -'''
  ''' & '''
  '''< > <= >= = <> =='''
  '''And Or'''

It should be noted that the use of And/Or operators evaluate from left to right such that

 If $x < 5 And $x > 3 Then

checks the $x < 5 first and if it returns false will not evaluate $x > 3.

Similarly for Or

 If $x <> 5 Or $x <> 6 Then

will evaluate $x <> 5 and if it returns true will not evaluate $x <> 6

All tables and information adapted from the AutoIt intro.

Branching

Branching is to let the computer compare something and based on the result let it execute a block of code. Autoit has three keywords for identifying branching. They are If, Select and Switch. In addition there are several sub keywords to identify the comparing code and assosiated block of code.

If-ElseIf-Else

When a test returns a true statement then execute code block down to the assosiated ElseIf, Else or EndIf keyword. If Else or Else if was encountered then jump to the EndIf Line.

Local $x = 1

If $x = 1 Then
   ;Code block
EndIf
 
If $x < 2 Then 
   ;Code block
ElseIf $x >= 3 Then 
   ;Code block
Else
   ;Code block
EndIf

There also exists a shorthand method of the If statement:

If true = 1 then MsgBox(1,"Is it true?","Yarp!")

Select

Select is simply a (arguably) more readable version of an if-elseif-else statement.

 Select 
     Case $var = 1
         ;Code block
     Case $var = 2
         ;Code block
     Case Else
         ;Code block
 EndSelect

Switch

The Switch statement contains an interesting difference to most languages. In AutoIt's case, it is equivalent to the Select statement. Once a block of code is executed the Switch statement exits. Unlike most other languages, a break is not required at the end of each case to avoid trickle-down. This may be considered disadvantageous due to the lack of multi-conditional executions that the Switch statement is generally used for.

Switch $var
    Case 1
        ;Code block
    Case 2
        ;Code block
    Case Else
        ;Code block
EndSwitch

Loops

A loop is used on a code block that we want to execute several times. In the codebloc we can have variables changing state for each iteration in the loop. AutoIt has four types of loops. For...Next, For Each, While...Wend and Do ... Until

For ... Next

 Local $i
 For $i = 1 to 10 Step 2
 Next

While ... WEnd

 While $var < 100
     Sleep(100)
     $var += 1
 WEnd

Do ... Until

A Do .. Until block will run at least once as the conditional check is done at the bottom of the block.
 Do
     Sleep(100)
     $var += 1
 Until $var = 100

The code inside this Do ... Until block should only run once

 Local $c
 Do
 	$c += 1
 	ConsoleWrite("Run nr " & $c & @crlf)
 Until True

This sample will run until we forcefully us a ExitLoop command to escape the loop

 Local $c
 Do
 	$c += 1
 	ConsoleWrite("Run nr " & $c & @crlf)
 	If $c = 2 Then ExitLoop
 Until False

This sample should run until $c equals 3

 Local $c
 Do
 	$c += 1
 	ConsoleWrite("Run nr " & $c & @crlf)
 Until $c=3

For Each

The For Each loop is often used for associative arrays however it is often handy when you don't know the size of your current array. In this case, the syntax and implementation is very similar to javascript which is slightly off the standard. Assume we have an array $arr of undetermined size:

Local $str = ""
for $stuff in $arr  ; for each item in our array
  $str &= $stuff    ; copy the item into our string
Next
MsgBox(1,"",$str)   ; displays the contents of our string

User defined functions

A function is a code block encapsulated by the keywords Func and EndFunc. Everytime you find yourselfe writing the same code again you can do three things. Write the code. Copy and paste the previously written code or wrap the code up in a function and call the function by name in your code.

Defining

 Func MySimplestUDF()
    ;This does nothing at the moment
 EndFunc

Passing data

 Func MyUDFAcceptingArguments($arg1, ByRef $arg2)
 EndFunc

Returning data

 Func MyUDFReturningResults($arg1, ByRef $arg2)
     Local $ret = 1
     ;Changing $arg2 is a way of returning data
     If IsNumeric($arg2) Then
         $arg2 = 2*$arg2
     Else
         $arg2 &= @CRLF & $arg2
     EndIf
     Return $ret
 EndFunc

File I/O

INI Files

Using IniWrite & IniRead to store values. Useful for scripts that run from independent source (network, USB Drive, etc..).

Write:

     IniWrite("FileName.INI", "Section", "Key", "Value")

Read:

     $MyVar = IniRead("FileName.INI", "Section", "Key", "Default"); If INI data missing, $MyVar set to "Default"

Sample "FileName.INI":

[Section]
Key=Value

***TODO: File I/O stuffs***