loly66

Global - Local - Dim

14 posts in this topic

hey guys I don't understand what Global - Local - Dim do for example here

#include <Constants.au3> ; only required for MsgBox constants
 
Global $Var_1 = "Variable 1"
Global $Var_2 = "Variable 2"
 
; Read the variables
MsgBox($MB_ICONINFORMATION + $MB_TOPMOST, "Reading", "In The Main Script" & @CRLF & @CRLF & "Variable 1 = " & $Var_1 & @CRLF & "Variable 2 = " & $Var_2)
 
; Read the variables in a function
_Function()
 
; And now read the variables again - see that $iVar_2 has changed
MsgBox($MB_ICONINFORMATION + $MB_TOPMOST, "Reading", "Back In The Main Script" & @CRLF & @CRLF & "Variable 1 = " & $Var_1 & @CRLF & "Variable 2 = " & $Var_2)
 
Func _Function()
    ; Read the variables
    MsgBox($MB_ICONINFORMATION + $MB_TOPMOST, "Reading", "In The Function" & @CRLF & @CRLF & "Variable 1 = " & $Var_1 & @CRLF & "Variable 2 = " & $Var_2)
    ; Now let us change one of the variables WITHIN the function
    $Var_2 = "Changed Variable 2"
EndFunc

 I have copied it and used it works fine then I removed " Global " and still it works fine same as before nothing changes so what does global do hope someone will explain what they do exactly and sorry for bad english thank you.

Share this post


Link to post
Share on other sites



Welcome to AutoIt and the forum!

Did you have a look in the help file? Section "Variables" describes how the scope works.


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

Did you read the wiki page? Before you say no, please read it and look at the examples. If you did then best to search a little more as this topic comes up once a month on average.

Article: https://www.autoitscript.com/wiki/Variables_-_using_Global,_Local,_Static_and_ByRef

Note: Copying the example without reading is only part of learning.


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

Share this post


Link to post
Share on other sites

first thanks, and I did read yes but I don't understand because i removed Global and function still working fine same as before nothing changes

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

first thanks, and I did read yes but I don't understand because i removed Global and function still working fine same as before nothing changes

This means you haven't read & understood the page yet as it is clearly stated what the default scope is:

 

We scope variables by using the Global, Local and Static keywords when the variables are first declared - look at the examples below. By default, AutoIt scopes any variables declared in the main body of a script (that is not between a Func and EndFunc pair) as Global and any variables declared within function declarations as Local. But it is a good idea to explicitly declare your variables to make sure that you get what you want.

 

So try taking the time to read and understand it as this is a fundamental thing to understand. ;)

Jos

Edited by Jos

Visit the SciTE4AutoIt3 Download page for the latest versions        Beta files                                                          Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites

i have read yes but i don't understand but thanks very much i will take my time yes to understand

Share this post


Link to post
Share on other sites

It may be strange, but I probably don't properly understand it either... much like that Assembly class I took in college.

I just Global declare all vars I use at the beginning of the script.

Of course, sometimes I don't declare all vars (I might forget one) and SyntaxCheck still passes, which means those "undeclared" in my Global section as actually being declared Local in the code. Usually I try my best to Global everything, it seems to work just fine.

Share this post


Link to post
Share on other sites

One good way to learn could be to use

Opt("MustDeclareVars", 1)

at the top of the script, and then check errors  :D

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

The Wiki link guinness best details it all but here is another crude example.

Global $sText1 = "Global String"
Local $sText2 = "Local String outside of any Function"
_A()
ConsoleWrite("----Variables outside Function A----" & @CRLF)
ConsoleWrite($sText1 & @CRLF)
ConsoleWrite($sText2 & @CRLF)
ConsoleWrite($sTextFuncA1 & @CRLF)
ConsoleWrite($sTextFuncA2 & @CRLF)
Func _A()
   Local $sText1 = "Local String inside Function A"
   Global $sTextFuncA1 = "Global String inside Function A"
   Local $sTextFuncA2 = "Local String inside Functioin A"
   ConsoleWrite("----Variables inside Func A----" & @CRLF)
   ConsoleWrite($sText1 & @CRLF)
   ConsoleWrite($sText2 & @CRLF)
   ConsoleWrite($sTextFuncA1 & @CRLF)
   ConsoleWrite($sTextFuncA2 & @CRLF)
   ConsoleWrite(@CRLF)
   $sText2 = "'Global' String changed withing Function A"
EndFunc

At the beginning of the script I declared a Global and a Local Variable.  Both of these variables are treated as global as they reside outside of any functions. 

I then call function A.  Inside function A I declare a Local variable of the same name as the Global variable $sText1 and set a different value.  You will notice when I exit function A I write the original variable value to the console which still has the Global variable value set.  Inside Function A I also changed the value of $sText2 as well as declared a Global variable which is accessible outside of the function.

When the function completes I write the vars listed under the function call _A(); notice that the local variable $sTextFuncA2 produces an error.

Essentially it works like this.  Variables defined as Global are accessible anywhere in the script (inside or outside of functions).

Variables defined as local that reside within functions are only accessible within those functions.

There is no real difference declaring a variable as Global or Local when they are declared outside of a function, as described by JohnOne above.

Edited by spudw2k

Share this post


Link to post
Share on other sites

One good way to learn could be to use

Opt("MustDeclareVars", 1)

at the top of the script, and then check errors  :D

In the wiki article it suggests to use Au3Check with additional params.


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

Share this post


Link to post
Share on other sites
Global $sText1 = "Global String"
Local $sText2 = "Local String outside of any Function"

This instance of the use a Local variable has always bothered me.  Yes, I understand the mechanics ... which others have clearly pointed out.  But I've concluded that about 9 times out of 10, an occurrence of a Local outside of a function means that statements have been pasted in or moved without considering the scope of variables ... and made somewhat worse by the fact that the code actually works with them that way.

Wouldn't it be reasonable for the compiler to always flag these occurrences? ... in the same way it flags that a variable might be undefined when it is actually defined further down in a script?

I seems that could prevent a misstep in development every now and then.  Leaving it "as is" only confuses anyone taking a first look at a particular script ... or at AU3, for that matter.

 

Share this post


Link to post
Share on other sites

Seems you (qwert) and I are on the same page. This is my take on the whole Local in "Global scope" >>


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

Share this post


Link to post
Share on other sites

No scope declaration in local scope = Local

Not as easy as it seems.

For this case it depends on if there is already a global variable with the same name. If yes - this global variable is used - if not a local variable gets declared.

Share this post


Link to post
Share on other sites

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