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. e.g. If $var = 5 Then ...
== Equivalence operator. e.g. If $var == 5 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!")

Additionally, there is the Ternary Operator, which acts as a shorthand conditional statement. The Ternary operator allows a binary choice to be executed without the overhead of an If..Else...EndIf statement:

#include <MsgBoxConstants.au3>
MsgBox($MB_SYSTEMMODAL, "Result: 1=1", (1 = 1) ? "True" : "False")

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 code block we can have variables changing state for each iteration in the loop. AutoIt has four types of loops. For...Next, For Each In, While...Wend and Do ... Until

For ... Next

 For $i = 1 to 10 Step 2; in a For..Next loop, the For variable is automatically declared locally
     ConsoleWrite($i & @LF)
 Next

For Each In

The For Each In 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

While ... WEnd

 Local $var
 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.
Local $var
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

User defined functions

A function is a code block encapsulated by the keywords Func and EndFunc. Anytime you find yourself 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(); define a simple user defined function
    ; Your customized code will go in here
    ; then you can call this function and have your code executed or "run"
EndFunc

Passing data

MyUDFAcceptingArguments("Some string")

Func MyUDFAcceptingArguments($arg1, $arg2 = "Default Data")
    MsgBox(64, $arg1, $arg2)
EndFunc

Returning data

Global $sReturn = _MyUDF_ReturnResults()
ConsoleWrite($sReturn & @CR); Display what was returned, we add @CR or @LF to drop down a line break, remove to see what happens


Func _MyUDF_ReturnResults()
	Local $sTest = "Some information"; this will be returned
        ; The Return statement will tell the function to return the information in the $Is variable
	Return $sTest
EndFunc

File I/O

INI Files

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

Methods for writing to an INI:

IniWriteSection

With this method you can create a new ini file, or add an additional section to an existing file.

IniWriteSection("My.ini", "Section1", "Key1")

IniWrite

This method allows you to write a section, key or value to an existing ini file. If the file does not exist, this method will create it.

     IniWrite("FileName.INI", "Section1", "Key1", "MyVal")

IniRead

Allows for the reading of values beneath a specified section and key.

$sVal = IniRead("My.ini", "Section1", "Key1", Default)
	ConsoleWrite($sVal & @CRLF) ; If INI data missing, $MyVal will return "Default"

IniReadSection

This method will return a 2 dimensional array showing all of the key/value pairs for the specified section in an existing ini file.

#include <Array.au3>
$aArray = IniReadSection("My.ini", "Section1")
   _ArrayDisplay($aArray)

IniReadSectionNames

Returns a 1 dimensional array showing all of the section names for an existing ini file.

#include <Array.au3>
$aArray = IniReadSectionNames("My.ini")
   _ArrayDisplay($aArray)

IniRenameSection

Rename the specified section in an existing ini file. The flag parameter can be set to 0, causing the script to fail if the new section name already exists.

IniRenameSection("My.ini", "Section1", "Section2", 0)

IniDelete

Delete a key from the specified section in an existing ini file.

IniDelete("My.ini", "Section1", "Key1")

Sample "My.INI":

[Section1]
Key1=MyVal
Key2=YourVal
Key3=OurVal