Jump to content

global variable or function?


pcjunki
 Share

Recommended Posts

Valik has discussed about this in the past, in the Dev Chat Forum.

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 tried running the 2nd example from  "Variables - using Global, Local, Static and ByRef"

and it seems that you have to dimension $Var_3 outside the function any way.

Try running this as it is presented here.

#include <Constants.au3> ; only required for MsgBox constants

 Global $Var_1 = "Variable 1"
 ; Read the variable
 MsgBox($MB_ICONINFORMATION + $MB_TOPMOST, "Reading", "In The Main Script" & @CRLF & @CRLF & "Variable 1 = " & $Var_1)

 ; Now run a function
 _Function()

 ; And now try to read Variable 3 OUTSIDE the function
 MsgBox($MB_ICONINFORMATION + $MB_TOPMOST, "Reading", "Back In The Main Script" & @CRLF & @CRLF & "Variable 1 = " & $Var_1 & @CRLF & "Variable 3 = " & $Var_3)

 Func _Function()
    ; Declare a LOCAL variable
    Local $Var_3 = "Variable 3"
    ; Read the variables
    MsgBox($MB_ICONINFORMATION + $MB_TOPMOST, "Reading", "In The Function" & @CRLF & @CRLF & "Variable 1 = " & $Var_1 & @CRLF & "Variable 3 = " & $Var_3)
 EndFunc

It will throw an undeclared variable warning

If I declare it local w/o a value outside the function it will run.

MEASURE TWICE - CUT ONCE

Link to comment
Share on other sites

It's teaching you scope, that is what is suppose to happen. :geek:

If you read it you would have seen:

You should have got errors telling you that $Var3 was "possibly used before declaration" and an "undeclared global variable". This is because $Var3 exists only within the function - when the function ends it is destroyed.

Even before the example it says this:

Here is a simple example showing how Local variables are only visible inside their own function:

everything cleared up? ;)

Edited by MikahS

Snips & Scripts


My Snips: graphCPUTemp ~ getENVvars
My Scripts: Short-Order Encrypter - message and file encryption V1.6.1 ~ AuPad - Notepad written entirely in AutoIt V1.9.4

Feel free to use any of my code for your own use.                                                                                                                                                           Forum FAQ

 

Link to comment
Share on other sites

It's not supposed to be able to run that way, that was the point of the example.

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

  • Moderators

reb,

The whole idea is that script will NOT run - to show that you cannot access a Local variable outside the function in which it is declared. The initial error is flagged bu Au3Check, but if you add #AutoIt3Wrapper_Run_AU3Check=n at the top of the script AutoIt itself will error saying:

"M:\Program\Au3 Scripts\test.au3" (13) : ==> Variable used without being declared.:
MsgBox($MB_ICONINFORMATION + $MB_TOPMOST, "Reading", "Back In The Main Script" & @CRLF & @CRLF & "Variable 1 = " & $Var_1 & @CRLF & "Variable 3 = " & $Var_3)
MsgBox($MB_ICONINFORMATION + $MB_TOPMOST, "Reading", "Back In The Main Script" & @CRLF & @CRLF & "Variable 1 = " & $Var_1 & @CRLF & "Variable 3 = " & ^ ERROR
I wrote that example to prove the point - it is not supposed to run as the comment after it shows:

You should have got errors telling you that $Var3 was "possibly used before declaration" and an "undeclared global variable".
Indeed, I would have been very concerned if it had run! :D

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

@guinness - "bug" or design choice?

It's of my opinion that it's a bug, but then I didn't implement it, so it could be a design choice, hopefully the later.

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

Design choice from everything I've read.

There's only 2 scopes in AutoIt, local and global, it's going to be either one or the other. No file scope, no block scope, just local and global.

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

But "Global scope" as we know it is its own scope. Think of it as main() in C or C++, but without the need to explicitly create a function called main (how wonderful is AutoIt with all that wonderful help it provides). If you think of it like this, then my point as mentioned previously makes sense, Locals in this function are only available in main. There is no issue (if the coder has thought about it) of declaring Global variables inside a function, we just say don't do that because more often than not the coder hasn't thought about it (point noted above).

; The following code here...    
Global $g_sVar = ""
Local $sVar = "" ; This variable shouldn't be seen in Example. Hence why I say it's a bug that wasn't thought about, as they didn't see people using Local in this scope.

Example()
SomeFunc()

GUICreate(...)
GUISetState()

Func Example()
    $g_sVar = "Some string that is called $g_sVar"
EndFunc

Func SomeFunc()
    Return True
EndFunc

; Should be thought of as this...
; AutoIt adds a function wrapper called Main around the "Global" scope space.

Main()

Func Main()
    Global $g_sVar = ""
    Local $sVar = "" ; This variable can't be seen in Example.
    
    Example()
    SomeFunc()

    GUICreate(...)
    GUISetState()
EndFunc

Func Example()
    $g_sVar = "Some string that is called $g_sVar"
EndFunc

Func SomeFunc()
    Return True
EndFunc
In my little world it makes a ton of sense. 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

I'll try to make this informative, but things like this can be mystifying at first sight.

Let's begin by declaring a few variables.

; All these variables are global
$pseudo = Null ; No explicit declaration.
Local $local ; Local to the current scope.
Global $g_FLAG ; Write it like it is!
Static $expression ; I'm not sure what justification exists for using a static variable in global scope.
; Several other methods exist to create global variables.

;

After a while... things start to improve.

Global $g_FLAG = True ; This is the only global variable in this script (the rest are all local).

MsgBox(0, "", Example())

Func New()
    Local $local = $g_FLAG ; There's nothing wrong here!
    Return $local
EndFunc

Func Pseudo()
    $pseudo = $g_FLAG ? Null : False ; Bad coding practice - missing Local keyword.
    Return $pseudo
EndFunc

Func Example()
    Return New() = Pseudo()
EndFunc

;

These are just examples. Notice that using a Local declaration allows you to change the scope of a variable during development without having to alter the syntax.

Edited by czardas
Link to comment
Share on other sites

Your comment after the second variable declaration is incorrect.

Local $local ; Local to the current scope.

There's no such thing as the "current scope" in this case, it's global and can be seen everywhere in the script. It's not local to anything, the variable is declared using the wrong declarative keyword, you're going to end up confusing people that read this years later. 

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

Yes, it is local to the current scope which is "global".  Confusing to users from other languages and new commers.  I'm starting to agree with guinness.  Have a "var" statement and make it the users responsibility to keep track of scope (I hope that is what you were saying, guinness).

edit: spelling

Edited by kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

I disagree. I take my information from the following post.

By definition: Local scope = Current scope

The only Local scope is inside a function, in AutoIt, there's nothing that would correspond to current scope other than inside a function.

Calling it local outside of a function is only syntactic sugar, it makes it easier for a human to see that this variable is going to only be used in the global scope and never inside a function. To AutoIt it's still a Global variable that can be used in a function, but it's up to the programmer to decide whether he is going to do that. In other programming languages, I'm not sure how that would be handled, but those other languages also have file scopes, block scopes, etc. that AutoIt doesn't have.

Don't confuse people by using the wrong keyword, and then referencing something that has nothing whatever to do with AutoIt, if AutoIt was like other languages with more than 2 scopes it would make sense to use Local this way, but AutoIt doesn't.

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

I understand what you are saying, but I think it would be wrong to redefine terminology simply because certain variable scope options are not available in AutoIt. Sure it makes sense to follow standard coding practices and I see no significant reason to use the Local keyword in global scope with finished code projects (while it makes no difference to the interpreter).

As regards code examples, I agree with Valik's ideology about not using Global declarations for variables which really ought to be declared using the Local keyword. Regardless of context, good coding practice needs to be apparent in how examples are presented. If variables are declared using the wrong keyword, this will compromise the value of an example and encourage bad habits which may also hinder learning other languages later on. The code and declarations may be out of context, but it's also nice to be able to copy and paste working code anywhere in your script when you're a beginner. This coin has two sides.

Edited by czardas
Link to comment
Share on other sites

Yes, it is local to the current scope which is "global".  Confusing to users from other languages and new commers.  I'm starting to agree with guinness.  Have a "var" statement and make it the users responsibility to keep track of scope (I hope that is what you were saying, guinness).

 

edit: spelling

Yeah, if there was only Var as a declaration keyword then outside of a function it would be global (so BrewManNH would be correct) and in a function it would be local. I guess using Dim and correct variable naming for local and global variables is what I am actually proposing when I think about it.

 

Actually now when I really think about users were probably having similar variable names in both global and function scopes (aka local) and wanted keywords to differentiate between $iAge (outside of functions) and $iAge (inside a function). Of course these days that global variable would be $g_iAge, to differentiate that it's global and not local.

 

I guess if you're not used to the likes of C/C++/Java/C#, this whole "current to the scope" comment can be a little confusing. I wish Valik had implemented that "threat" he made, as even though I pay attention to scope myself e.g. if I only use a variable inside an if statement then I declare only there, would mean developers would start to pay close attention to scope, more so than they do now.

 

#AutoIt3Wrapper_Run_Au3Check=N
Switch True
    Case True
        Local $vVar = "Some string" & @CRLF ; This would only be visible in the case statement.
    Case False ; Happens once in a million trillion times, thus the developer will only see the undeclared error once in a blue moon.
        ; As the variable $vVar isn't created, then the ConsoleWrite() line will cause an error.
EndSwitch
ConsoleWrite($vVar) ; As bugs like this wouldn't exist anymore if the expression was false and not true.
 

I understand what you are saying, but I think it would be wrong to redefine terminology simply because certain variable scope options are not available in AutoIt. Sure it makes sense to follow standard coding practices and I see no significant reason to use the Local keyword in global scope with finished code projects (while it makes no difference to the interpreter).

 

As regards code examples, I agree with Valik's ideology about not using Global declarations for variables which really ought to be declared using the Local keyword. Regardless of context, good coding practice needs to be apparent in how examples are presented. If variables are declared using the wrong keyword, this will compromise the value of an example and encourage bad habits which may also hinder learning other languages later on. The code and declarations may be out of context, but it's also nice to be able to copy and paste working code anywhere in your script when you're a beginner. This coin has two sides.

Which has been the case for many years, hence my pursuit to discuss this subject which in the passed has been glossed over because AutoIt is just a "scripting language".

 

So czardas and kylomas seem to be agreeing with me on this whole subject of the meaning of Local in "Global scope".

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

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...