Jump to content

Good coding practices in AutoIt


guinness
 Share

Recommended Posts

czardas,

Here you are >>

#include <Array.au3>

Global $aArray[2] = [1, 2]

SomeFunc()

Func SomeFunc()
    ReDim $aArray[3] ; Re-size the array and keep its content.
    _ArrayDisplay($aArray)

    Global $aArray[2] ; Erase the contents of $aArray and re-size it.
    _ArrayDisplay($aArray)
EndFunc   ;==>SomeFunc
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

Dim and ReDim are two totally different things.

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

Dim and ReDim are two totally different things.

Even so, etimology suggests at least a very strong link. I didn't like the Global declaration within your function. It seems to go against the grain. In any case I won't be needing this so it's a mute moot point to me.

Edited by czardas
Link to comment
Share on other sites

 

I won't be needing this so it's a mute point to me.

 

OK?! So there was no need for me to respond then?

This is easier to read.

#include <Array.au3>

Global $g_aArray[2] = [1, 2]

SomeFunc()

Func SomeFunc()
    ReDim $g_aArray[3] ; Re-size the array and keep its content.
    _ArrayDisplay($g_aArray)

    Local $aArrayN[2] ; Create a new array.
    $g_aArray = $aArrayN ; Assign to the Global variable.
    $aArrayN = 0 ; Destroy array contents.
    _ArrayDisplay($g_aArray)
EndFunc   ;==>SomeFunc
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 meant no disrespect. I would also do it differently. :)

How I might approach this, though I'm not sure which is best.

#include <Array.au3>

Global $aArray[2] = [1, 2]

SomeFunc()
_ArrayDisplay($aArray)

Func SomeFunc()
    ReDim $aArray[3] ; Re-size the array and keep its content.
    _ArrayDisplay($aArray)

    ReDim $aArray[1] ; Re-size to one element
    ReDim $aArray[4] ; Re-size the array
    _ArrayDelete ($aArray, 0) ; Remove the only remaining assigned value.
EndFunc   ;==>SomeFunc

Did I say mute point earlier - that should be moot point. :whistle:

Edited by czardas
Link to comment
Share on other sites

I generally avoid using globals like the plague.

How to make a variable visible to all functions?

Dim shouldn't ever be used.

The first option looks more compact.

#include <Array.au3>
#include <File.au3>

Global $aFiles2D
_FuncName1(@SystemDir & '\config')
_FuncName2(@SystemDir & '\config')

Func _FuncName1($sPath)
    Local $aFiles = _FileListToArray($sPath, "*.*", 1)
    If @error Then Return
    Dim $aFiles2D[$aFiles[0] + 1][2] = [[$aFiles[0] + 1]]
    For $i = 1 To $aFiles[0]
        $aFiles2D[$i][0] = $aFiles[$i]
        $tmp = FileGetAttrib(@WindowsDir & '\' & $aFiles[$i])
        If Not @error Then $aFiles2D[$i][1] = $tmp
    Next
    _ArrayDisplay($aFiles2D, 'Array')
EndFunc   ;==>_FuncName

Func _FuncName2($sPath)
    Local $aFiles = _FileListToArray($sPath, "*.*", 1)
    If @error Then Return
    ReDim $aFiles2D[1]
    ReDim $aFiles2D[$aFiles[0] + 1][2]
    $aFiles2D[0][0] = $aFiles[0] + 1
    For $i = 1 To $aFiles[0]
        $aFiles2D[$i][0] = $aFiles[$i]
        $tmp = FileGetAttrib(@WindowsDir & '\' & $aFiles[$i])
        If Not @error Then $aFiles2D[$i][1] = $tmp
    Next
    _ArrayDisplay($aFiles2D, 'Array')
EndFunc   ;==>_FuncName
Link to comment
Share on other sites

Notable mention is using prefix to indicate the type of expected variable.

.

$aStuff ;array
$sStuff ;string
$oStuff; object
$hStuff; handle
$bStuff ; binary, true/false
$iStuff ; integer
$nStuff ;number
$g*stuff ; global variable
$c*stuff ; constant

If there is a more complete list, a link would be appreciated. I think there is a name for that syntax after some old school programmer, but for the life of me can't remember.

I used to be really bad at doing that, and still revert to bad syntax when throwing out examples.

I don't know what is a normal prefix for static, I never saw that keyword before perusing this thread.

At first I didn't even get why people put those prefixes in, then once I got it I thought it would slow me down. Now I can't see myself doing anything halfway serious without it.

Edited by DicatoroftheUSA
Link to comment
Share on other sites

How to make a variable visible to all functions?

Passing the value through arguments. Though in some cases such as event or callback functions, there may not be an alternative.

But I still prefer using local/passed argument variables, because cause/effect is easier to trace in my opinion.

Link to comment
Share on other sites

Notable mention is using prefix to indicate the type of expected variable.

If there is a more complete list, a link would be appreciated.

http://www.autoitscript.com/autoit3/udfs/UDF_Standards.htm

I think there is a name for that syntax after some old school programmer, but for the life of me can't remember.

Are you thinking of Hungarian notation? Probably one of the most confusing ways to name a variable. Edited by BrewManNH

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

How to make a variable visible to all functions?

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.

Edited by czardas
Link to comment
Share on other sites

The ini file was just an example of reading a value instead of having it declared globally. I generally do something like this:

Instead of this:

Global $gArg1 = True, $gArg2 = False

Func _main()
    _1of2($gArg1)
    _2of2($gArg2)
EndFunc

Func _1of2($vParam)
    ; some algorithm
EndFunc

Func _2of2($vParam)
    ; some algorithm
EndFunc

Try to do something like this:

Func _main()
    Local $aArgs[2] = [True, False]
    _1of2($aArgs[0])
    _2of2($aArgs[1])
EndFunc

Func _1of2($vParam)
    ; some algorithm
EndFunc

Func _2of2($vParam)
    ; some algorithm
EndFunc

This is the simplest example I can think of. Instead of using global, try to use local variables.

Edited by czardas
Link to comment
Share on other sites

If everything was so primitive.

Basic for clarity. I'm not suggesting it is always possible to avoid using global variables, only that it's generally good practice.

The phrase in English is 'If everything was so simple'. You have the Russian version. :)

Edited by czardas
Link to comment
Share on other sites

The reason is that you accidentally used a reserved name?

Yes, I think this is the main reason, especially if someone tries to combine different UDFs which use conflicting global constants. That can get really quite awkward. The fewer globals, the better.

Edited by czardas
Link to comment
Share on other sites

There are many uses of Global variables in most of the included UDFs, definitely not a no-no to the devs. Every XXconstants.au3 file is nothing but global variables. It all depends on what you need the variable for that decides its scope.

Very true, perhaps I should have said, that if you have to use a Global in a UDF or Include, that you damn well better make sure it is uniquely named and extremely unlikely to be used in a script that could use them.

I've never created either, but I have very carefully modified a few, and encountered the perils of Globals in them.

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

EDIT

I never make changes to the Includes that come with the AutoIt install, certainly never permanently.

It's mostly ones other people have whipped up. If I have to alter an AutoIt original, it is never to one in the Include folder, but to a copy in my script folder, for a one off scenario.

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