Jump to content

Declaring variables and why?


Recommended Posts

Hello...

Can someone maybe please explain why you get so many different variable declarations and how to fully implement it?

Like all the definitions of:

Dim

Const

Global

Local

Int

Thank you it'll be much appreciated...

[u]My dream is to have a dream...[/u]

Link to comment
Share on other sites

Read the help file :oops:

The difference between Dim, Local and Global is the scope in which they are created:

Dim = Local scope if the variable name doesn't already exist globally (in which case it reuses the global variable!)

Global = Forces creation of the variable in the Global scope

Local = Forces creation of the variable in the Local/Function scope

AutoIt 3.3.14.2 X86 - SciTE 3.6.0WIN 8.1 X64 - Other Example Scripts

Link to comment
Share on other sites

Try to avoid using Dim and aim for either Local or Global. It boils down to this...

Global - Can been used and referenced throughout the entire script.

Local - Can only be used in the function it was declared in and is destroyed when leaving the function.

Source: https://en.wikipedia.org/wiki/Variable_scope (a good read, but a little heavy for a new user.)

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

scope?

Scope

A variable's scope is controlled by when and how you declare the variable. If you declare a variable at the start of your script and outside any functions it exists in the Global scope and can be read or changed from anywhere in the script.

If you declare a variable inside a function it is in Local scope and can only be used within that same function. Variables created inside functions are automatically destroyed when the function ends.

By default when variables are declared using Dim or assigned in a function they have Local scope unless there is a global variable of the same name (in which case the global variable is reused). This can be altered by using the Local and Global keywords to declare variables and force the scope you want.

Link to comment
Share on other sites

By the way it's best practice to declare Global variables at the top of your script and not in the middle of a Function.

Global $sGlobal = "Used anywhere"

Example()
DoIt()

Func Example()
    Local $sLocal = "Used only in this function"
    MsgBox(4096, "Local", $sLocal)
    Return MsgBox(4096, "Global", $sGlobal)
EndFunc   ;==>Example

Func DoIt()
    Return MsgBox(4096, "Global", $sGlobal)
EndFunc   ;==>DoIt

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

I might be new to the forum, but not new to autoit, new to programming in autoit but not new to coding, I just think it's time to extend my knowledge a but further use more complex stuff, to create more efficient Programs.

But thanks I researched A bit and now I understand why it's necessary to Declare Variables, different uses and different characteristics. Thanks m8

[u]My dream is to have a dream...[/u]

Link to comment
Share on other sites

Ah ok The local scope is used inside a function and global scope is used outside of a function like this returns the whole number

Global $f = Int(9.369)
MsgBox(4096, "Int", $f)

So it can be wriiten to file for saving when used by a different function outside the function, if it was used inside a function then the value shouldve been saved immediately before the function ends? hmmmm so all of this basically relates to expressions? Am I understanding this right?

[u]My dream is to have a dream...[/u]

Link to comment
Share on other sites

Well the Local scope can be declared outside of a function so long as the variable isn't used anywhere else. e.g.

Local $sLocalOutside = "Used only here and no where else e.g. other functions"

Example()
MsgBox(4096, "", $sLocalOutside)

Func Example()
    Local $sLocal = "Used only in this function"
    MsgBox(4096, "Local", $sLocal)
EndFunc   ;==>Example
See here for more details >>

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • 4 weeks later...

In general variables should be declared at the smallest scope possible for a lot of reasons...but a few are:

uses less memory

high counts can slow the script

memory leaks

easier to keep up with the variables in the script

Autoit forces you to use some globals..primarily in the GUI creation, but you can sidestep many of these

by declaring the function you wish to fire immediately below the creation of the event control

in event mode, eg:

GUICtrlCreateButton("Replace", 280, 40, 115, 25)

GUICtrlSetOnEvent(-1, "btnFindReplClk")

also, you can almost always pass variables between functions which also makes it possible to not create

globals, eg:

func checklines()

local $line = "all good men must come to the aid of their country in 2012"

local $t_arr = stringsplit($line," ")

local $tX

for $tX = 1 to $t_arr[0]

if num_chk($line) then

consolewrite("The line [" & $line & "] contains a number---> " & $t_arr[$tX] & @crlf)

endif

next

endfunc

;check if word passed from checklines function is a number

Func num_chk($val)

; return 0 if not a number or 1 if is a number

return StringRegExp($val, "[d.]",0)

EndFunc ;==>num_chk

and passing variables like this opens up options for your functions.

you may wish the function to do different things based upon the variable passed to it. For instance,

perhaps you have an application made that will do some kind of batch processing and you have preloaded

multiple files...you can pass these to your function with local variables..no need for globals.

func buttonclick()

;if button is clicked display open file dialog

OpenMyFile()

endfunc

func buttonclick1()

;open array if exists or display file dialog

local $filelist = "C:myfile1.txt|C:myfile2.txt||"

OpenMyFile($filelist)

endfunc

func filelist($txt = "")

if $txt <> "" then

local $t_arr = stringsplit($txt,"|")

local $tX

for $tX = 1 to $t_arr[0]

;pass each array item to function

OpenMyFile($t_arr[$tX])

next

else

;if no array passed, show dialog by passing nothing to openmyfile function

OpenMyFile()

endif

endfunc

;optional variables in function calls do not need declared beyond the parenthesis

Func OpenMyFile($txt = "")

local $_FILENAME

;if empty item sent, open file dialog

If $txt = "" Then

$_FILENAME = FileOpenDialog("Open file...", "", "Text files (*.txt)")

Else

$_FILENAME = $txt

Endif

;pass filename to yearcheck function

yearcheck($_FILENAME)

endfunc

func yearcheck($tfile)

Local $file = FileOpen($tfile)

;read entire file to local variable

Local $txt = FileRead($file)

fileclose($file)

if stringinstr(string($txt),"2011") then

$txt = stringreplace($txt,"2011","2012")

$file = FileOpen($tfile,2)

filewrite($file,$txt)

fileclose($file)

endif

endfunc

all that above is for demo only, there are better ways to do that kind of check..but it demo the idea

of passing variables instead of using globals. Then when the function is completed and the file is closed, the buffer of the file

contents is destroyed..releasing memory

as for DIM...

the only real use I have found for it is to reset an array quickly.

Instead of

redim $myarray[1]

$myarray[0] = ""

use dim $myarray[1]..its tons faster and it clears out the old values that may have previously existed

anyhow, that's my 0.02. I hope it helps open up ways around global variables.

Edited by brycetech
Link to comment
Share on other sites

also, fwiw

if you prefix your variables in some way that is suitable to you, you will always be able to tell if its a global or a local.

for instance, I use $t_ or $t in front of variables ..indicating to me its a temporary variable (local).

;)

Link to comment
Share on other sites

brycetech - I'd just like to say that I find info like this incredibly useful. I have been using AutoIT for quite a few years but as it's only for a small part of my work, I dont have time to research more than I need to achieve a desired result.

I have been using variables but without understanding (or considering) that alternatives can sometimes be better. Whilst I'm no coder, I always try and make things as neat, efficient and elegant as I can, so I will try and impement this info into my future thinking Thank you

[font='Comic Sans MS']Eagles may soar high but weasels dont get sucked into jet engines[/font]

Link to comment
Share on other sites

brycetech,

Just a quick observation when posting AutoIt code it's always best to post between [autoit][/autoit] tags, it just makes the post easier to read.

For naming conventions I use this Wiki entry by Mat as a guide.

Edit: Oh and using Dim is a bad idea, try to stick to Local and Global respectively.

Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Well the Local scope can be declared outside of a function so long as the variable isn't used anywhere else. e.g.

Using the Local phrase when declaring a variable outside any function is overridden and created as a Global, is it not?

It can be redeclared as Local inside a function, discarded, and outside the function the original (Global) value is retained. So, there's really no such thing as a Local outside a function. It can be written as "Local", but it will default to Global scope.

No one ever addressed the "Const" option in the OP's original post. It is easily understood that adding Const to a declaration like: Global Const $sValue = "Hello World" creates a read-only variable whose value can not be modified. But one might ask "Why bother?". Const variables add a little bit of self-documentation to your program, and I believe they generate a couple less instructions, making them slightly faster when referenced. No big deal, really.

Edited by Spiff59
Link to comment
Share on other sites

No one ever addressed the "Const" option in the OP's original post. It is easily understood that adding Const to a declaration like: Global Const $sValue = "Hello World" creates a read-only variable whose value can not be modified. But one might ask "Why bother?". Const variables add a little bit of self-documentation to your program, and I believe they generate a couple less instructions, making them slightly faster when referenced. No big deal, really.

One reason to use Const for a variable, at least for me, is in case you accidentally reuse a variable name.

For an example, you create a label you're using to display a timer, you reference the controlID using $Timer (Global $Timer = GUICtrlCreateLabel()). Later in the script, you want to time something using TimerInit/TimerDiff and forget you've already used $Timer for your label so you reuse $Timer for the timer ($Timer = TimerInit()), you've just overwritten the controlID pointing to your label and now your label doesn't update and you're trying to figure out why that is. If you had used Const for the control, you would immediately find out that $Timer can't be updated and you'll know why. Of course, if I had used the recommendations in Mat's wiki entry, you'd have used $idTimer for the label, and $nTimer for the timer and this would be a moot point. ;)

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

  • 1 month later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...