Jump to content

Is it possible?


Go to solution Solved by kylomas,

Recommended Posts

While it's true in the general sense that a global variable should be declared as such, there might be a case for using a local declaration outside of a function.

Global variables are not available to your whole script if you are using include files in a non compiled script, so while AutoIt lacks a file scope declaration, I don't see any major harm in declaring a variable which is local to the current file/document.

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Link to comment
Share on other sites

There's no such thing as a global variable that's not available to the whole script, #includes included. You contradict yourself when you say there's no file scope and then go on to describe file scope. It's true, there's no file scope in AutoIt, and there's no such thing as a Local variable in a global scope. I don't give two shits what Valik wrote about it, because he was wrong when it comes to AutoIt whenever he ever said anything about local to the current scope. There just is no such thing in AutoIt, you have 2 scopes, Global (available everywhere in the script) and Local (available only to the presently running function). If we were talking about C++ then there's a difference, you have variables that are only valid inside a loop, or a function, or a file, or global, or anywhere that puts them inside 2 brackets, but AutoIt doesn't have that.

It's syntactic sugar to say anything else, when you say things like that it makes you look like you know more than you really do.

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

Anyone can waltz around on a wired up super crusade,  preaching that their way is the only and best.

I was wrong about a global not being available in another file, but I'm pretty sure a script would error out in earlier versions regarding that, where as now you just get a warning from scite about a possible undeclared global.

Here's a Fact though, It does not matter which Keyword you declare a variable with outside of a function or even if you use a Keyword at all. So that makes it a matter of preference regardless of personal opinion.

Regarding your comment about looking like I know more than I do when I make a mistake, I'll be sure to keep an eye on your own perfectly correct posts in the future.

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Link to comment
Share on other sites

@BrewmanNH, M23 - I might agree wth you if for no other reason than to add clarity to new users of the language. 

Given this snippet

#AutoIt3Wrapper_Add_Constants=y

local $gui010   =   guicreate('')
local $aSize    =   wingetclientsize($gui010)
local $lbl010   =   guictrlcreatelabel('',0,20,$aSize[0],50,$ss_sunken)
                    guisetstate()

while 1
    switch guigetmsg()
        case $gui_event_close
            Exit
    EndSwitch
WEnd

would you declare these variables "GLOBAL" because the keyword matches the scope?

Incidentally, I don't have a horse in this race, rather, I would like to code in some manner that is both consistent with the "heavy hitters" and lends clarity for the new commers.

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

@BrewmanNH, M23 - I might agree wth you if for no other reason than to add clarity to new users of the language. 

Given this snippet

#AutoIt3Wrapper_Add_Constants=y

local $gui010   =   guicreate('')
local $aSize    =   wingetclientsize($gui010)
local $lbl010   =   guictrlcreatelabel('',0,20,$aSize[0],50,$ss_sunken)
                    guisetstate()

while 1
    switch guigetmsg()
        case $gui_event_close
            Exit
    EndSwitch
WEnd

would you declare these variables "GLOBAL" because the keyword matches the scope?

Incidentally, I don't have a horse in this race, rather, I would like to code in some manner that is both consistent with the "heavy hitters" and lends clarity for the new commers.

kylomas

 

Well as someone new to autoit (Also new to programming) , after reading the Autoit wiki page for Global/Local, I would call all those "Global" because they are not in between a Func/EndFunc Pair.  Even though they say "Local", Autoit still makes them Global.  

That is my understanding.  From a noob standpoint.

Link to comment
Share on other sites

  • Moderators

JohnnyVolcom5,

 

Even though they say "Local", Autoit still makes them Global.

And that is exactly why I believe that declaring them as Local is not sensible - even though, as I said earlier, I can understand the argument that they should be. ;)

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

Regarding your comment about looking like I know more than I do when I make a mistake, I'll be sure to keep an eye on your own perfectly correct posts in the future.

That comment wasn't directed at you in the slightest.

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 guess it was aimed at me.

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

BrewManNH you can be sure that mentioned former developer didn't say anything wrong about variables scopes in AutoIt. If you think he said something wrong then you didn't understand what he was saying.

For example, this could be correctly written snippet that shows how to concatenate three strings to generate fourth to print:

Global Const $sFirstString = "ABC"
Global $sSecondString = "DEF"

Local Const $sThirdString = ".XYZ"
Local $sFourthString = $sFirstString & $sSecondString & $sThirdString

ConsoleWrite($sFourthString & @CRLF)
 

Variables scopes are one of the first things newbs should learn about and understand. After that they will know that the snippet posted above is simple (to the point) representation of this code:

Global Const $sFirstString = "ABC"
Global $sSecondString = "DEF"

ConsoleWrite(SomeFunc() & @CRLF)

Func SomeFunc()
    Local Const $sThirdString = ".XYZ"
    Local $sFourthString = $sFirstString & $sSecondString & $sThirdString
    Return $sFourthString
EndFunc
... or more correctly this one:

Global Const $sFirstString = "ABC"
Global $sSecondString = "DEF"

ConsoleWrite(SomeFunc($sFirstString, $sSecondString) & @CRLF)

Func SomeFunc($sFirstParam, $sSecondParam)
    Local Const $sThirdString = ".XYZ"
    Local $sFourthString = $sFirstParam & $sSecondParam & $sThirdString
    Return $sFourthString
EndFunc
... or this:

 

Global Const $sFirstString = "ABC"
Global $sSecondString = "DEF"

ConsoleWrite(SomeFunc($sFirstString, $sSecondString) & @CRLF)

Func SomeFunc($sFirstParam, $sSecondParam)
    Local Const $sThirdString = ".XYZ"
    Return $sFirstParam & $sSecondParam & $sThirdString
EndFunc
... or after further reduction really nothing.

 

It's simpification done for brevity. Anyone who would be confused by the first code snippet should really start from the beginning.

♡♡♡

.

eMyvnE

Link to comment
Share on other sites

  • Moderators

trancexx,

I cannot disagree with you more. How on earth you can say that using Local in that first snippet can be considered to be shorthand for replacing a function? :wacko:

A beginner is very likely to think that the variable is indeed Local to that part of the script and then something like this will happen:

Global $vVar_1 = "One"

Local $vVar_2 = "Two"

; I think this is Local to this section of the script
Local $vVar_3 = $vVar_1 & $vVar_2
; Yup, it seems to be
ConsoleWrite($vVar_3 & @CRLF)

_Func()

; And what do we get here
ConsoleWrite($vVar_3 & @CRLF)
; Oh dear - it was a Global variable after all!!!!!

Func _Func()
    ; Well obviously this variable is Local as it is in a function, so no need to declare it
    $vVar_3 = "Something else entirely"
EndFunc
The variable is Global in scope as far as AutoIt is considered and should be declared as such. Doing anything else is just asking for trouble and will confuse far more than it helps. :(

But then what would an old hobbyist coder like me know about it anyway. :P

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

That's not real code. It's short snippet that shows what how to concatenate three strings.
I could say that If I used all global variables then your beginner might think that he can't concatenate three strings from different scopes. Wouldn't that be just as confusing.

The variable is Global in scope as far as AutoIt is considered and should be declared as such. Doing anything else is just asking for trouble and will confuse far more than it helps. :(

No, that's false. In real code $sThirdString and $sFourthString are not global variables.

I can't speak for others so I will use one of the snippets I posted - for example, see >this code. $sAuthResponse in that snippet is declared as local because in some real script code that variable would be used inside some function to check whatever.
Using Global in snippet for variable that shouldn't be global just to make the snippet gramatically correct is teaching beginners bad programming manners. Snippets are there to show different things.

♡♡♡

.

eMyvnE

Link to comment
Share on other sites

  • Moderators

trancexx,

 

No, that's false

Look at what the code I posted returns - the variable is Global in scope despite its Local declaration. I do see how you can argue against that - what I said is demonstrably true for the AutoIt code as posted. :)

 

In real code $sThirdString and $sFourthString are not global variables

What is this "real code" you speak of? In AutoIt code they are Global variables as that snippet shows.

I have said many times that I understand the logical argument for declaring variables like that as Local - but only in the abstract sense. As far as AutoIt is concerned they are Global and declaring them as anything else is just confusing - and in fact as far as AutoIt is concerned just wrong. Whether we like it or not, the snippets posted on the forum are taken as correct by the majority of readers - so if you want to declare these variables as Local, put them inside functions so that they are actually correct. ;)

It is my firm belief that the majority of people we see here are learning and we owe it to them to confuse them as little as possible - using incorrect scope declarations will not teach them anything other than that coding is too hard for them when their variables are all wrongly assigned. But I fear that, as usual, we will never agree and so continuing the argument is pointless. You go your way and I will go mine. :)

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

I was once of the same opinion, thinking declaring variables as local outside a function was somewhat confusing for a beginner. I have since changed my opinion about this, after listening to guinness. The problem is that many global declarations given in example code generally belong inside a function. Examples should generally only demonstrate a single proceedure, and scope declaration is often unrelated to that. It's never wrong to declare a variable as local anywhere in your script (as I understand it), but the same can not be said for declaring variables as global. I believe that practicing writing correct syntax avoids more confusion in the long term.

Edited by czardas
Link to comment
Share on other sites

And the correct syntax is if it's not in a function, it's global even if you declare it using aardvark as the declaration statement (if that were ever valid of course ;)). Declaring every variable using Local, even when it's not in a function, is entirely valid but incorrect or at least confusing. There's even a parameter for Au2Check that looks for Local declaration in a Global scope.

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

Using globals is generally discouraged. When everything you learned is suddenly turned on its head because your code is so badly written with loads of incorrect declarations, you can blame the examples you copied from and say look: even an MVP declared these variables as global.

Edited by czardas
Link to comment
Share on other sites

Using Globals but calling them Local is even worse in my opinion. There are uses for Global variables, there's no uses for calling them Local to avoid the stigma of the word 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

Global variables are not bad, they have their purpose, but variable should be declared as global only if it needs to be global and surely never from within function. Using Local for global variable is plain wrong. The purpose of using Local in global scope (not for global variable) is to teach the beginners what variable should and what variable shouldn't be declared and used as global variable. That's much more important than to be anal about Local.

@Melba23, real script code is implemented code of course. Code snippets are like brushing teeth. You don't brush teeth for brushing teeth.

Au3Check is approximation, it's not worth mentioning here.

Edited by trancexx

♡♡♡

.

eMyvnE

Link to comment
Share on other sites

Using Local for global variable is plain wrong.

 

Then I perhaps misinterpreted the following words: 'local implies local to the current scope'. In any case I don't do that because I would confuse myself too much. ㋛

Global variables are not bad, they have their purpose, but variable should be declared as global only if it needs to be global and surely never from within function.

 

I think this covers the important information everyone needs to know.

Edited by czardas
Link to comment
Share on other sites

As a 'B' grade programmer or simple Hobby one (take your pick), I would like to know the harm in Globalizing all your variables at the top of your script, which is something I always do? This is presuming that none need to be Local for your script to work properly.

That said, at need, I do use Local, so I understand when it is needed ... at least in a basic sense.

P.S. I do what I do, for simplicity sake. That means, I don't think about declaration scope for each variable, only when it's obvious, that it needs to be declared Local. It just makes life easier for me to approach it that way, and after many years and no obvious side-effects in my programs, I question that it is harmful.

Is there some overhead to my programs, perhaps making them run slow or inefficient in some meaningful way?

EDIT

Many years ago, I came to AutoIt, with a background of using Dim most of the time, then a few years back, Valik gave an excellent discussion on why Dim shouldn't be used, and that Global was better. I have followed that ever since, but obviously I have never had any formal learning in programming, and so many terms and concepts fly right over my head.

Edited by TheSaint

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

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