Jump to content

Good coding practices in AutoIt


guinness
 Share

Recommended Posts

Is there a set standard for this, like using a certain format, combo of characters, underscore etc?

See Azijo's previous post ($gVar) and this link. Although this still doesn't address the issue entirely. It's still a leaky bucket.

Edited by czardas
Link to comment
Share on other sites

Yes that can be tricky without using globals. To most functions, I generally pass an array of values stored locally within a main function, or read values when I need them: for example from an ini file. It's not always possible to avoid using global declaration, but I believe it is good practice to avoid them.

Personally, I don't see any issue with script Globals, you just have to have guidelines you stick to.

I mostly only use Globals nowadays, never Dims anymore, but at need I will use Locals.

You just have to be wise how you name your variables - you need to have a regime you stick to that avoids issues.

I also declare all my Globals alphabetically at the beginning of my scripts, separating out those for Controls ... even written a helper program to do all that for me.

SciTE will usually always popup a variable anyway, but a quick check at the top of my script gives reassurance.

I even have a button on my SciTE toolbar program, that copies and adds text (variables) to the Clipboard, when working with a new block of code, which helps make it relatively pain free, when not relying on my helper program.

The only issue I see with Globals, is when others use them in a UDF or Include, and don't name them wisely.

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

@TheSaint : That's fine for personal use if you are careful. Problems may arise if you use other people's code. Another somewhat minor detail is that global variables always consume RAM, where as local variables release memory, so theoretically the code should run smoother. Depends on how you write it of course. :think:

Edited by czardas
Link to comment
Share on other sites

See Azijo's previous post ($gVar) and this link. Although this still doesn't address the issue entirely. It's still a leaky bucket.

No worries, thanks for that ... still working my way through all the posts, and making my own before forgetting what I want to say.

I believe I read all that once, when I considered creating a _Titlecase UDF, but decided I needed more time to take it all in, so left it for another day, which will probably never happen now.

That spec is excellent, and I hope enough people are aware and follow it.

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

@TheSaint : That's fine for personal use if you are careful. Problems may arise if you use other people's code. Another somewhat minor detail is that global variables always consume RAM, where as local variables release memory, so theoretically the code should run smoother. Depends on how you write it of course. :think:

Yes, that first is true, so I'm always careful with other people's code, and unless it's an Include/UDF, tend to modify it to my conventions ... giving credit of course where due.

I'm not sure you are right about memory release, unless you null it ... and even then .....

If I remember right, nothing is fully released until the script closes or perhaps when each portion of code completes execution ... I presume so anyway?

For instance, declaring a Dim or Local in your main section of script, that then calls other functions etc, would stay alive until the main section of code exits. Not sure about instances in the functions, etc ... perhaps they stay alive until the full script exits?

No doubt the wise informed ones here will comment on all that, so we know.

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

I'm not sure you are right about memory release, unless you null it ... and even then .....

If I remember right, nothing is fully released until the script closes or perhaps when each portion of code completes execution ... I presume so anyway?

This is what I'm referring to:

NoGlobalsNeeded()

Func NoGlobalsNeeded()
    Local $sValue = GetValue() ; Consume memory
    $sValue = 0 ; Release memory
EndFunc

Func GetValue()
    Local $sTemp = "Some very large value which consumes lots of memory"
    Return $sTemp ; After this $sTemp no longer exists
EndFunc
Edited by czardas
Link to comment
Share on other sites

This is what I'm referring to:

NoGlobalsNeeded()

Func NoGlobalsNeeded()
Local $sValue = GetValue() ; Consume memory
$sValue = 0 ; Release memory
EndFunc

That's nulling it, and obviously reducing it's size, but isn't it still something like a namespace until the script exits?

Func GetValue()
Local $sTemp = "Some very large value which consumes lots of memory"
Return $sTemp ; After this $sTemp no longer exists
EndFunc

Only if the script exits, by my reckoning. The calling script would still hold the value.

I guess we need to hear from one who definitely knows the inner workings.

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

The point is this: Had the variable been declared globally, the same value would be held twice in memory. After nulling there would still remain one (global) instance of the variable. This is not the case with my example where practically all memory holding these values is released before the script exits. If there is more code to run afterwards, then it ought to make a difference; even if turns out only to be a small difference.

You can find further useful discussion relating to Global Variables

Edited by czardas
Link to comment
Share on other sites

The only issue I see with Globals, is when others use them in a UDF or Include, and don't name them wisely.

The main issue I see with globals is script complexity. If any and all functions can alter a global variable then that makes your script hard to analyze mentally. As I previously stated I think a best practice is to reduce the amount of variables that can be altered. Also functions should be what I've seen called as referentially transparent. A function should return the same value given the same arguments every single time. Of course with less expressive languages we have to make compromises but I believe it is doable for at least more than what I've seen and done in the past.

http://en.wikipedia.org/wiki/Referential_transparency_%28computer_science%29

Edited by jaberwocky6669
Link to comment
Share on other sites

Every variable created locally in a function is released once the function is exited.

That's why it's better to initialize the heaviest data in the global scope (or in your Main function) and then use it in your functions (or to pass it as ByRef), because it's not efficient (takes more time) if you are often calling your function.

Link to comment
Share on other sites

Come on guys, there is no need for speculation. Write a small test script instead of expecting a Dev to drop by, it's what I did >>

#include <WinAPIEx.au3>

SomeFunc()
MemoryCheck('Return from function, local array destroyed')

Func SomeFunc()
    Local Const $iCount = 999999
    Local $aArray[$iCount]
    For $i = 0 To UBound($iCount) - 1
        $aArray[$i] = $i
    Next
    MemoryCheck('Local array created')
    $aArray = 0
    MemoryCheck('Local array destroyed')
    Local $aArray[$iCount]
    For $i = 0 To UBound($iCount) - 1
        $aArray[$i] = $i
    Next
    MemoryCheck('Local array created again')
    Return True
EndFunc   ;==>SomeFunc

Func MemoryCheck($sData)
    Local $aMem = _WinAPI_GetProcessMemoryInfo(@AutoItPID)
    ConsoleWrite($sData & ': ' & _ByteSuffix($aMem[7]) & @CRLF)
    $aMem = 0
EndFunc   ;==>MemoryCheck

Func _ByteSuffix($iBytes, $iRound = 2) ; By Spiff59
    Local $iIndex, $aArray[9] = [' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB']
    While $iBytes > 1023
        $iIndex += 1
        $iBytes /= 1024
    WEnd
    Return Round($iBytes, $iRound) & $aArray[$iIndex]
EndFunc   ;==>_ByteSuffix
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

Is there a set standard for this, like using a certain format, combo of characters, underscore etc?

If you look at the Globals that are used in the UDFs they're usually named after the UDF they're in. The Excel globals all start with $xl... for example, the ListView constants start with $__LISTVIEWCONSTANT..., etc.

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

Question: What if I want to retain variable data once returned from a Function and only use that variable in that particular Function, can't it be declared as Global then?

Answer: Static variables.

Example()

Func Example()
SomeFunc() ; This will display a message box of 1, 1.
SomeFunc() ; This will display a message box of 1, 2.
SomeFunc() ; This will display a message box of 1, 3.
EndFunc ;==>Example

Func SomeFunc()
; This initialises a Static variable in Local scope. When a variable is declared just in Local scope (within a Function,)
; it's destroyed when the Function ends/returns. This isn't the case for a Static variable. The variable can't be
; accessed from anywhere else in the script apart from the Function it was declared in.
Local Static $vVariableThatIsStatic = 0
Local $vVariableThatIsLocal = 0
$vVariableThatIsLocal += 1 ; This will always be 1 as it was destroyed once returned from SomeFunc.
$vVariableThatIsStatic += 1 ; This will increase by 1.
MsgBox(4096, $vVariableThatIsLocal, $vVariableThatIsStatic)
EndFunc ;==>SomeFunc

....WHAT?! There were static variables in AutoIt all this time?!!? I wish I'd have known this sooner! It would have saved me a lot of work.
Link to comment
Share on other sites

It was added:

18th December, 2009 - v3.3.2.0

Added #508: Static keyword.

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

Don't use undocumented/documented magic numbers if a (descriptive) name constant is available:

; Imagine you're a new user to AutoIt and you come across this code, where would you find -3, -4 or -5 in the help file?
; Since AutoIt is relatively a new concept to you, your first thought isn't to search through all the include files, I mean
; why would you, the help file is there for a reason.
Example()

Func Example()
    Local $hGUI = GUICreate('')
    GUICtrlCreateLabel('Why magic numbers are counter productive.', 5, 5)
    GUICtrlSetState(Default, 128) ; Does this hide, show or disable it?
    GUICtrlSetState(Default, 64) ; Does this hide, show or disable it?
    GUISetState(@SW_SHOW, $hGUI)

    While 1
        Switch GUIGetMsg()
            Case -3 ; Doesn't really tell much about what it does.
                ExitLoop

            Case -4, -5 ; Again, no idea what these are. MouseMove? MouseClick? Restore?
                MsgBox(4096, '', 'Do something when this action takes place.') ; What is 4096?

        EndSwitch
    WEnd

    GUIDelete($hGUI)
EndFunc   ;==>Example

Did you understand the numbers were these:

#include <GUIConstantsEx.au3>
#include <MsgBoxConstants.au3>

Example()

Func Example()
    Local $hGUI = GUICreate('')
    GUICtrlCreateLabel('Why magic numbers are counter productive.', 5, 5)
    GUICtrlSetState(Default, $GUI_DISABLE) ; Better, this is documented in the help file.
    GUICtrlSetState(Default, $GUI_ENABLE) ; Better, this is documented in the help file.
    GUISetState(@SW_SHOW, $hGUI)

    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE ; Better, this is documented in the help file. Ah, it's the close action.
                ExitLoop

            Case $GUI_EVENT_MINIMIZE, $GUI_EVENT_RESTORE ; ; Better, this is documented in the help file.
                MsgBox($MB_SYSTEMMODAL, '', 'Do something when this action takes place.') ; Oh, it's a system modal message box.

        EndSwitch
    WEnd

    GUIDelete($hGUI)
EndFunc   ;==>Example

Don't just take my word for it: https://en.wikipedia.org/wiki/Magic_number_(programming)

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

Use ByRef in custom functions when passing variables with large data to the function:

#include <WinAPIEx.au3>

SomeFunc()

Func SomeFunc()
    Local Const $iCount = 999999
    Local $aArray[$iCount]
    For $i = 0 To UBound($iCount) - 1
        $aArray[$i] = $i
    Next

    MemoryCheck('Array before passing to normal function')
    ArrayFuncNormal($aArray)
    MemoryCheck('Array after passing to normal function')

    ConsoleWrite(@CRLF)

    MemoryCheck('Array before passing to ByRef function')
    ArrayFuncByRef($aArray)
    MemoryCheck('Array after passing to ByRef function')

    $aArray = 0
    Return True
EndFunc   ;==>SomeFunc

Func ArrayFuncByRef(ByRef $aArray)
    $aArray[0] = 0
    MemoryCheck('Array inside the ByRef function')
EndFunc   ;==>ArrayFuncByRef

Func ArrayFuncNormal($aArray)
    $aArray[0] = 0
    MemoryCheck('Array inside the normal normal function')
EndFunc   ;==>ArrayFuncNormal

Func MemoryCheck($sData)
    Local $aMem = _WinAPI_GetProcessMemoryInfo(@AutoItPID)
    ConsoleWrite($sData & ': ' & _ByteSuffix($aMem[7]) & @CRLF)
    $aMem = 0
EndFunc   ;==>MemoryCheck

Func _ByteSuffix($iBytes, $iRound = 2) ; By Spiff59
    Local $iIndex, $aArray[9] = [' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB']
    While $iBytes > 1023
        $iIndex += 1
        $iBytes /= 1024
    WEnd
    Return Round($iBytes, $iRound) & $aArray[$iIndex]
EndFunc   ;==>_ByteSuffix

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

  • 2 weeks later...

There is no requirement to declare the iteration count variable in a loop.

; Correct
Local Const $iCount = 99
Local $aArray[$iCount]
For $i = 0 To UBound($aArray) - 1 ; $i is only used in the loop, so there is no requirement to declare it.
    $aArray[$i] = $i
Next

; Incorrect
Local Const $iCount = 99
Local $aArray[$iCount]
Local $i ; This is only used to store the iteration count value in the loop and therefore doesn't need to be declared. This is known as loop scope.
For $i = 0 To UBound($aArray) - 1
    $aArray[$i] = $i
Next
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

Internal mechanism declares a variable $i as a local. You can use this variable later on, as it is a normal variable.

Global $i = 0
_i_To_11()
_MsgBox()
_i_To_4()
_MsgBox()

Func _i_To_11()
    For $i = 10 To 11
        Sleep(10)
    Next
    MsgBox(0, 'Local ', $i)
EndFunc

Func _i_To_4()
    $i = 4
EndFunc

Func _MsgBox()
    MsgBox(0, '_MsgBox, Global', $i)
EndFunc
Link to comment
Share on other sites

@guinness

According to the best POSTING practices. <_<

I suggest you create a PDF or Word doc. to attach in the first post, that gathers them all in 1 document.

That's easy for everyone to use as a reference manual that visits the thread.

Rgds

ptrex

Link to comment
Share on other sites

Good idea, I will do that when there is enough examples to warrant spending time on it.

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