Jump to content

Recommended Posts

Posted (edited)

Few days back i made an associative array UDF for a project as autoit does not have associative array/PHP style array support.it does not keep up to the quality of the example scripts posted in this forum.
I hope it may be useful to other amateur developers like me.
 
 
Main UDF file:
associative_arrays.au3
 
 


 




 
CHM help file:
 
associativearray_chm.zip
 
 
list of main functions:

_SetAssociativeArray()
_AddAssociativeArray()
_AssociativeArray()
print_r()
array2json()
Json2Array()

example script:


#include <associative_arrays.au3>

$datas = '' ; creates a variable

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;                                            ;;
;;  Associative_array exmples                 ;;
;;                                            ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


;first example: seting an array value
$value = _SetAssociativeArray($datas, 'roger->royal->datar', '','changedatata=>>inprogressd', True)
    ConsoleWrite(@CR&'first example: seting an array value'&@CR)
If $value > -1 Then 
    print_r($datas)
Else
    ConsoleWrite("Failed: " & $value)
EndIf


$value = _AddAssociativeArray($datas, 'roger->royal->datar->0',  -1, 'changedatata=>>inprogress', True) ;makes a sub array
ConsoleWrite(@CR&'creating a non existent array path roger->royal->datar->0'&@CR)
If $value > -1 Then 
    print_r($datas)
Else
    ConsoleWrite("Failed: " & $value)
EndIf

;second example: pushing an element to the end of an array
$value = _AddAssociativeArray($datas, 'roger->royal->datar',  -1, 'changedatata=>>inpro', True)
ConsoleWrite(@CR&'second example: pushing an element to the end of an array'&@CR)
If $value > -1 Then 
    print_r($datas)
Else
    ConsoleWrite("Failed: " & $value)
EndIf

;third example: adding an element to the 2nd index position in the associative array
$value = _AddAssociativeArray($datas, 'roger->royal->datar',  2, 'added element to 2nd position', True)
ConsoleWrite(@CR&'third example: adding an element to the 2nd index position in the associative array'&@CR)
If $value > -1 Then 
    print_r($datas)
Else
    ConsoleWrite("Failed: " & $value)
EndIf

;fourth example: changing the element in the 2nd index position in the associative array
$value = _SetAssociativeArray($datas, 'roger->royal->datar',  2, '2nd element changed')
ConsoleWrite(@CR&'fourth example: changing the element in the 2nd index position in the associative array'&@CR)
If $value > -1 Then 
    print_r($datas)
Else
    ConsoleWrite("Failed: " & $value)
EndIf

;fifth example:  changing the element in the first index position in the associative array
$value = _SetAssociativeArray($datas, 'roger->royal->datar',  1, 'first element changed')
ConsoleWrite(@CR&'fifth example: changing the element in the first index position in the associative array'&@CR)
If $value > -1 Then 
    print_r($datas)
Else
    ConsoleWrite("Failed: " & $value)
EndIf

_SetAssociativeArray($datas, 'list', '', 'echo', True);makes another array in the root

$value = _AssociativeArray($datas, 'roger->royal->datar')
_ArrayDisplay($value, 'sixth example: reading an array at the position roger->royal->datar')

ConsoleWrite(@CR & 'seventh example: reading the second element of an array'& @CR &_AssociativeArray($datas, 'roger->royal->datar', 2))

$value = _AssociativeArray($datas, 'roger->royal->data')
_ArrayDisplay($value, 'eighth example: trying to read an array which doesnt exist')
;print_r($datas)

$test_json = '{"0":"again0","1":"again1","5":{"0":"test1","male":["asf","s:dfs,f"," boo\r\n hoo"],"1":"test2","2":"test\t3","3":"dgdg \\n fdgd"},"6":"test4","7":"test5"}'
$json_test_array = ''

$value = Json2Array($json_test_array, $test_json)
ConsoleWrite(@CR&'Converting a json to an associative array'&@CR)
If $value > -1 Then 
    print_r($json_test_array)
Else
    ConsoleWrite("Failed: " & $value)
EndIf


ConsoleWrite(@crlf&'Converting an associative array to json'&@CR& array2json($json_test_array)&@CRLF)
ConsoleWrite(Get_Ass_Array($json_test_array, '0', 0, True)&@CR) 

Do let me know if there are any bugs..
Thank you..

Edited by b47chguru
Posted

You're using Dim in the functions, you shouldn't. Especially since the variable names that you're using it with are fairly common names and I can easily foresee a name clash if someone declared a global with the same name. You should always check your script with this directive in it to see if there are any issues.

#AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 6

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

Posted

 

You're using Dim in the functions, you shouldn't. Especially since the variable names that you're using it with are fairly common names and I can easily foresee a name clash if someone declared a global with the same name. You should always check your script with this directive in it to see if there are any issues.

#AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 6

Thankyou brewman for the reply,

i am new to autoit.can you show with an example how using dim on a variable declared locally in a function change it if declared globally later...

 

Posted

AutoIt beta help file!

#AutoIt3Wrapper_Au3Check_Parameters=-q -d -w- 3 -w- 6 ; already declared var=off , warn when using Dim=off

#include <Constants.au3>

Dim $vVariableThatIsGlobal = "This is a variable that has ""Program Scope"" aka Global."

MsgBox($MB_SYSTEMMODAL, "", "An example of why Dim can cause more problems than solve them.")

Example()

Func Example()
    ; That looks alright to me as it displays the following text: This is a variable that has "Program Scope" aka Global.
    MsgBox($MB_SYSTEMMODAL, "", $vVariableThatIsGlobal)

    ; Call some random function.
    Local $vReturn = SomeFunc()

    ; The Global variable ($vVariableThatIsGlobal) changed because I totally forgot I had a duplicate variable name in "SomeFunc".
    MsgBox($MB_SYSTEMMODAL, $vReturn, "The variable has now changed: " & $vVariableThatIsGlobal)
EndFunc   ;==>Example

Func SomeFunc()
    ; This should create a variable in Local scope if the variable name doesn"t already exist.
    ; For argument sake I totally forgot that I declared a variable already with the same name.
    ; Well I only want this to be changed in the function and not the variable at the top of the script.
    ; Should be OK right? Think again.
    Dim $vVariableThatIsGlobal = ""

    For $i = 1 To 10
        $vVariableThatIsGlobal &= $i ; This will return 12345678910 totally wiping the previous contents of $vVariableThatIsGlobal.
    Next
    Return $vVariableThatIsGlobal
EndFunc   ;==>SomeFunc

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

Posted

I'm wondering did you test you own example and did it work for you?

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

Posted

 

AutoIt beta help file!

#AutoIt3Wrapper_Au3Check_Parameters=-q -d -w- 3 -w- 6 ; already declared var=off , warn when using Dim=off

#include <Constants.au3>

Dim $vVariableThatIsGlobal = "This is a variable that has ""Program Scope"" aka Global."

MsgBox($MB_SYSTEMMODAL, "", "An example of why Dim can cause more problems than solve them.")

Example()

Func Example()
    ; That looks alright to me as it displays the following text: This is a variable that has "Program Scope" aka Global.
    MsgBox($MB_SYSTEMMODAL, "", $vVariableThatIsGlobal)

    ; Call some random function.
    Local $vReturn = SomeFunc()

    ; The Global variable ($vVariableThatIsGlobal) changed because I totally forgot I had a duplicate variable name in "SomeFunc".
    MsgBox($MB_SYSTEMMODAL, $vReturn, "The variable has now changed: " & $vVariableThatIsGlobal)
EndFunc   ;==>Example

Func SomeFunc()
    ; This should create a variable in Local scope if the variable name doesn"t already exist.
    ; For argument sake I totally forgot that I declared a variable already with the same name.
    ; Well I only want this to be changed in the function and not the variable at the top of the script.
    ; Should be OK right? Think again.
    Dim $vVariableThatIsGlobal = ""

    For $i = 1 To 10
        $vVariableThatIsGlobal &= $i ; This will return 12345678910 totally wiping the previous contents of $vVariableThatIsGlobal.
    Next
    Return $vVariableThatIsGlobal
EndFunc   ;==>SomeFunc

 

I'm wondering did you test you own example and did it work for you?

 

 

Hi guinness, first of all sorry for the late reply..

and thanks for the example, i get the point...but is there any alternative to Dim?

yes i have tested and my example works perfectly..

i am using autoit version v3.3.6.1

Posted

i am using autoit version v3.3.6.1

Well the majority of us are using v3.3.8.1 (as well as the beta) and I don't think it does, because _ArrayDisplay requires a variable to be passed as a reference. Unless _ArrayDisplay was coded differently in that version?

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

Posted

yes _ArrayDisplay function in this version also requires array passed as reference but somehow it works even if it is not supplied in that way...

_ArrayDisplay(Const ByRef $avArray [, $sTitle = "Array: ListView Display" [, $iItemLimit = -1 [, $iTranspose = 0 [, $sSeparator = "" [, $sReplace = "|" [, $sHeader = ""]]]]]])

Posted (edited)

That's a bug then that was fixed in v3.3.8.1, strange as I didn't see anything in the changelog. Anyway, I'm just telling you the example doesn't work for those of us who use the current version.

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

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
×
×
  • Create New...