Sign in to follow this  
Followers 0
hezi

clearing Array

6 posts in this topic

is there fast and nice way to clear array? (clear all elements and probably free some memory....)

i can loop to delete element until end but i look for more elegant way :)

maybe delete and recreate array (if possible didnt find this option)

thanks!

Share this post


Link to post
Share on other sites



hezi,

Just redeclare the array and it is emptied for you: :)

#include <Array.au3>

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

_ArrayDisplay($aArray)

Global $aArray[3]

_ArrayDisplay($aArray)

If you want to get rid of the array completely, just declare it as a simple variable - $aArray = 0. ;)

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______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

Share this post


Link to post
Share on other sites

Cool !

thanks for quick reply!

Thanks Melba23

Share this post


Link to post
Share on other sites

Another approach that will pass the Au3Check with advanced parameters >>

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 -w 7
#include <Array.au3>

Global $aArray[3] = [1, 2, 3]
Global $aBackup[UBound($aArray)] ; Create a blank array.

_ArrayDisplay($aArray)

$aArray = $aBackup

_ArrayDisplay($aArray)

_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

Share this post


Link to post
Share on other sites

Or another way is this >>

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 -w 7
#include <Array.au3>

Global $a1D[5] = [1, 2, 3, 4, 5]

_ArrayDisplay($a1D)

_ArrayClear($a1D)

_ArrayDisplay($a1D)

Func _ArrayClear(ByRef $aArray)
    Local $iCols = UBound($aArray, 2)
    Local $iDim = UBound($aArray, 0)
    Local $iRows = UBound($aArray, 1)
    If $iDim = 1 Then
        Local $aArray1D[$iRows]
        $aArray = $aArray1D
    Else
        Local $aArray2D[$iRows][$iCols]
        $aArray = $aArray2D
    EndIf
EndFunc   ;==>_ArrayClear

_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

Share this post


Link to post
Share on other sites

thanks guinness!

Share this post


Link to post
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
Sign in to follow this  
Followers 0

  • Similar Content

    • cabrunco
      _GDIPlus_GraphicsDispose for an array of graphics
      By cabrunco
      Dear all, suppose I define an array of graphics using _GDIPlus_GraphicsCreateFromHWND. At the end of the script, when calling _GDIPlus_GraphicsDispose, is it ok to pass the array as an argument, or do I need to write a loop for each array element? For example:
      _GDIPlus_GraphicsDispose($GraphsArray) 
       
      OR
       
      For $i 0 to 10
          _GDIPlus_GraphicsDispose($GraphsArray[$i])
      Next
      I did both and can see no difference. In fact, if I do not call _GDIPlus_GraphicsDispose I don't see anything going, to be frank. Thank you for any help,
      Cabrunco
    • czardas
      ArrayWorkshop
      By czardas
      ArrayWorkshop is what I like to think of as the 'Leibnitzian' approach to multidimensional arrays: formulaic beyond 3 dimensions. Most of the functions allow you to target the dimension in which you want processing to be done. It shouldn't take too long to figure out how this works after you've run some examples. _ArrayAttach treats multidimensional arrays as if they were lego bricks - any array can be attached regardless of bounds or dimensions.*
      BETA RELEASE - currently no known bugs
      ; #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7 #include-once ; #INDEX# ====================================================================================================================== ; Title .........: ArrayWorkshop (beta release) ; AutoIt Version : 3.3.14.2 ; Language ......: English ; Description ...: Multidimensional array functions. ; Notes .........: In this library, an array region is defined as follows: ; 1. items within a one dimensional array ; 2. item collections within a two dimensional array (rows or columns) ; 3. tables within a three dimensional array ; 4. cuboidal areas within a four dimension array ; 5. four dimensional cuboids within a five dimensional array ; etc... ; To reduce bloat, several functions access part of the script referred to (in the comments) as 'Remote Loops'. ; Arrays containing zero elements are not supported and will cause functions to return an error. ; Author(s) .....: czardas ; ============================================================================================================================== ; #CURRENT# ==================================================================================================================== ; _ArrayAttach [current limit = 9 dimensions] ; _ArrayFlatten [current limit = 9 dimensions] ; _Predim [current limit = 9 dimensions] ; _ShuffleArray [current limit = 9 dimensions] ; _UniqueRegion [current limit = 5 dimensions] ; ============================================================================================================================== ; #INTERNAL_USE_ONLY#=========================================================================================================== ; __CountElements ; __FloodFunc ; __GetBounds ; __HiddenIndices ; ___NewArray ; ___Read1D ; __ResetBounds ; __Shuffle1D ; ___FloodXD ; ============================================================================================================================== ; #FUNCTION# =================================================================================================================== ; Name...........: _ArrayAttach ; Description ...: Joins two arrays together. ; Syntax.........: _ArrayAttach($aTarget, $aSource [, $iDimension = 1]) ; Parameters.....; $aTarget - [ByRef] Target array to which the source array will be concatenated. ; $aSource - The array to attach to the target. ; $iDimension - [Optional] Integer value - the dimension in which concatenation occurs. Default = 1st dimension ; Return values .: Success - Returns the modified array ByRef. ; Failure sets @error as follows: ; |@error = 1 $aTarget is not a valid array. ; |@error = 2 Dimension limit exceeded. ; |@error = 3 Arrays must contain at least one element. ; Author ........: czardas ; Comments ......; This function is limited to arrays of up to nine dimensions. ; Extra dimensions are added to the target when: ; 1. the source array has more dimensions than the target [or] ; 2. the 3rd parameter ($iDimension) is greater than the number of dimensions available. ; ============================================================================================================================== Func _ArrayAttach(ByRef $aTarget, $aSource, $iDimension = 1) If Not IsArray($aTarget) Then Return SetError(1) ; the target must be an array Local $aBoundSrc[1] If Not IsArray($aSource) Then ; convert $aSource into an array $aBoundSrc[0] = $aSource ; use $aBoundSrc as a temporary array to preserve memory $aSource = $aBoundSrc ; conversion by assignment EndIf $aBoundSrc = __GetBounds($aSource, 9) ; get the bounds of the source array If @error Then Return SetError(3) ; $aSource must contain at least one element Local $aBoundTgt = __GetBounds($aTarget, 9) ; get the bounds of the target array If @error Then Return SetError(3) ; $aTarget must contain at least one element $iDimension = ($iDimension = Default) ? 1 : Int($iDimension) If $aBoundTgt[0] > 9 Or $aBoundSrc[0] > 9 Or $iDimension > 9 Or $iDimension < 1 Then Return SetError(2) ; dimension limit exceeded Local $iDim = ($aBoundSrc[0] > $aBoundTgt[0]) ? $aBoundSrc[0] : $aBoundTgt[0] ; minimum number of dimensions needed for the output If $iDimension > $iDim Then $iDim = $iDimension ; the specified dimension may not yet exist Local $aBoundNew[$iDim +1] ; output bounds $aBoundNew[0] = $iDim ; element 0 contains the number of dimensions For $i = 1 To $iDim ; get the minimum bounds within all dimensions If $i <> $iDimension Then $aBoundNew[$i] = ($aBoundSrc[$i] > $aBoundTgt[$i]) ? $aBoundSrc[$i] : $aBoundTgt[$i] Else ; expansion within the explicit dimension is determined differently $aBoundNew[$i] = $aBoundSrc[$i] + $aBoundTgt[$i] ; add the number of subitems together EndIf $aBoundSrc[$i] -= 1 ; convert to the final index value in each dimension of the source array Next _Predim($aTarget, $iDim) ; add more dimensions if needed __ResetBounds($aTarget, $aBoundNew) ; ReDim the target to make space for more elements Local $sTransfer = '$aSource' & __HiddenIndices($aBoundSrc[0], $iDimension), _ ; to access elements at their original indeces $iFrom, $aFloodFill = __FloodFunc() $aBoundSrc[$iDimension] = 0 ; whichever loop this relates to must only run once on each encounter For $iRegion = $aBoundTgt[$iDimension] To $aBoundNew[$iDimension] - 1 ; to the new bounds of the specified dimension $iFrom = $iRegion - $aBoundTgt[$iDimension] ; adjusted to begin transfer from source element 0 $aFloodFill[$iDim]($aTarget, $aBoundSrc, $iDimension, $iRegion, $iFrom, $aSource, $sTransfer) ; flood the region Next EndFunc ;==>_ArrayAttach ; #FUNCTION# =================================================================================================================== ; Name...........: _ArrayFlatten ; Description ...: Turns a multidimensional array into a one dimensional array while maintaining all the data. ; Syntax.........: _ArrayFlatten($aArray) ; Parameters.....; $aArray - The original array. ; Return values .: Returns the modified array ByRef. ; Failure sets @error as follows: ; |@error = 1 The parameter is not a valid array. ; |@error = 2 Dimension limit exceeded. ; |@error = 3 Arrays must contain at least one element. ; Author.........: czardas ; Comments ......; This function works for up to 9 dimensions. ; ============================================================================================================================== Func _ArrayFlatten(ByRef $aArray) ; [MISSING COMMENTS] If Not IsArray($aArray) Then Return SetError(1) Local $aBound = __GetBounds($aArray, 9) If @error Then Return SetError(3) ; $aArray must contain at least one element If $aBound[0] > 9 Then Return SetError(2) If $aBound[0] = 1 Then Return ; array is already one dimensional For $i = 1 To 9 $aBound[$i] = ($i > $aBound[0]) ? 0 : $aBound[$i] -1 Next Local $aTarget[__CountElements($aArray)], $iCount = 0, _ $sExpression = '$aArray' & StringLeft('[$1][$2][$3][$4][$5][$6][$7][$8][$9]', $aBound[0] *4) For $9 = 0 To $aBound[9] For $8 = 0 To $aBound[8] For $7 = 0 To $aBound[7] For $6 = 0 To $aBound[6] For $5 = 0 To $aBound[5] For $4 = 0 To $aBound[4] For $3 = 0 To $aBound[3] For $2 = 0 To $aBound[2] For $1 = 0 To $aBound[1] $aTarget[$iCount] = Execute($sExpression) $iCount += 1 Next Next Next Next Next Next Next Next Next $aArray = $aTarget EndFunc ;==> _ArrayFlatten ; #FUNCTION# =================================================================================================================== ; Name...........: _Predim ; Description ...: Changes the size of an array by adding, or removing, dimensions. ; Syntax.........: _Predim($aArray, $iDimensions [, $iPush = False]) ; Parameters.....; $aArray - The original array. ; $iDimensions - The number of dimensions in the returned array. ; $bPush - [Optional] If set to True, new dimensions are created on, or removed from, the left [see comments]. ; Return values .: Returns the modified array ByRef. ; Failure sets @error as follows: ; |@error = 1 The first parameter is not an array. ; |@error = 2 The requested array has more than 9 dimensions. ; |@error = 3 The original array has more than 9 dimensions. ; |@error = 4 Arrays must contain at least one element. ; Author.........: czardas ; Comments ......; This function works for up to 9 dimensions. ; By default, new dimensions are added to the right in a standard sequence: $aArray[7][6] ==> $aArray[7][6][1] ; Dimensions are removed in reverse sequence: $aArray[7][6] ==> $aArray[7] ; When the $bPush parameter is set to True, the original array will be pushed to higher dimensions: ; $aArray[7][6] ==> $aArray[1][7][6], or the process reversed: $aArray[7][6] ==> $aArray[6] ; ============================================================================================================================== Func _Predim(ByRef $aArray, $iDimensions, $bPush = False) If Not IsArray($aArray) Then Return SetError(1) $iDimensions = Int($iDimensions) If $iDimensions < 1 Or $iDimensions > 9 Then Return SetError(2) Local $iPreDims = UBound($aArray, 0) ; current number of dimensions If $iPreDims = $iDimensions Then Return ; no change If $iPreDims > 9 Then Return SetError(3) ; too many dimensions Local $aBound = __GetBounds($aArray) ; get the size of each original dimension If @error Then Return SetError(4) ; $aArray must contain at least one element $aBound[0] = $iDimensions ; overwrite this value with the new number of dimensions Local $sTransfer = '[$a[1]][$a[2]][$a[3]][$a[4]][$a[5]][$a[6]][$a[7]][$a[8]][$a[9]]' ; array syntax to be sent to the remote loop region If $bPush Then ; prefix dimensions, or delete from the left Local $iOffset = Abs($iDimensions - $iPreDims) If $iPreDims > $iDimensions Then ; lower dimensions get deleted For $i = 1 To $iDimensions ; shift elements to lower indices $aBound[$i] = $aBound[$i + $iOffset] Next $sTransfer = '$aSource' & StringLeft('[0][0][0][0][0][0][0][0]', $iOffset * 3) & StringLeft($sTransfer, $iDimensions * 7) Else ; lower dimensions are created ReDim $aBound[$iDimensions + 1] ; make space for more dimensions For $i = $iDimensions To $iOffset + 1 Step -1 ; shift elements to higher indices $aBound[$i] = $aBound[$i - $iOffset] Next For $i = 1 To $iOffset ; assign the size of each additional dimension [1][1][1]... etc... $aBound[$i] = 1 Next $sTransfer = '$aSource' & StringMid($sTransfer, 1 + $iOffset * 7, $iPreDims * 7) EndIf Else ; Default behaviour = append dimensions, or delete from the right ReDim $aBound[$iDimensions + 1] ; modify the number of dimensions [according to the new array] For $i = $iPreDims + 1 To $iDimensions ; assign the size of each new dimension ...[1][1][1] etc... $aBound[$i] = 1 Next $sTransfer = '$aSource' & StringLeft($sTransfer, $iPreDims * 7) EndIf ; add or remove dimensions Local $aNewArray = ___NewArray($aBound) For $i = 1 To $iDimensions $aBound[$i] -= 1 ; convert elements to the maximum index value within each dimension Next ; access the remote loop region Local $iSubitem = 0, $aFloodFill = __FloodFunc() $aFloodFill[$iDimensions]($aNewArray, $aBound, 0, $iSubitem, '', $aArray, $sTransfer) $aArray = $aNewArray EndFunc ;==>_Predim ; #FUNCTION# =================================================================================================================== ; Name...........: _ShuffleArray ; Description ...: Shuffles multidimensional regions within an array, or items within multidimensional regions. ; Syntax.........: _ShuffleArray($aArray [, $iDimension = 1 [, $bFruitMachineStyle = False]]) ; Parameters.....; $aArray - The original array. ; $iDimension - [Optional] - The dimension used to define the regions to be shuffled. ; $bFruitMachineStyle - [Optional] Shuffles all items within regions as defined by the dimension. ; Return values .: Returns the modified array ByRef. ; Failure sets @error as follows: ; |@error = 1 The first parameter is not a valid array. ; |@error = 2 The first parameter contains the wrong number of dimensions. ; |@error = 3 The second parameter does not relate to any of the dimensions available. ; |@error = 4 Arrays must contain at least one element. ; Author.........: czardas ; Comments ......; This function works for arrays of up to 9 dimensions. ; Setting $iDimension = 0 overrides the 3rd parameter and shuffles everything - anywhere within the array. ; Example .......; _ShuffleArray($aArray, 2, True) ; ==> This is a fruit machine! ; ============================================================================================================================== Func _ShuffleArray(ByRef $aArray, $iDimension = 1, $bFruitMachineStyle = False) ; [MISSING SOME COMMENTS] If Not IsArray($aArray) Then Return SetError(1) Local $aBound = __GetBounds($aArray) ; get the bounds of each dimension If @error Then Return SetError(4) ; $aArray must contain at least one element If $aBound[0] > 9 Then Return SetError(2) ; nine dimension limit $iDimension = ($iDimension = Default) ? 1 : Int($iDimension) If $iDimension > $aBound[0] Or $iDimension < 0 Or $iDimension > 9 Then Return SetError(3) ; out of bounds dimension Local $aTemp = $aBound ; regional bounds For $i = 1 To $aBound[0] $aBound[$i] -= 1 Next Local $iSubitem, $iFrom, $aFlatArray, $sTransfer, $aFloodFill = __FloodFunc() If $iDimension > 0 Then ; shuffle regions or elements within regions If $aBound[0] > 1 Then $aTemp[$iDimension] = 1 Local $aRegion = ___NewArray($aTemp) ; to store extracted regions Local $sIndices = __HiddenIndices($aBound[0], $iDimension) $aTemp = $aBound $aTemp[$iDimension] = 0 ; set to loop once [one region at a time] If $bFruitMachineStyle Then ; contents will be shuffled within each region For $iSubitem = 0 To $aBound[$iDimension] ; loop through all indices within the dimension $sTransfer = '$aSource' & $sIndices ; array syntax $aFloodFill[$aBound[0]]($aRegion, $aTemp, $iDimension, 0, $iSubitem, $aArray, $sTransfer) ; extract region $aFlatArray = $aRegion _ArrayFlatten($aFlatArray) ; convert region to a 1D array __Shuffle1D($aFlatArray) ; shuffle the contents $sTransfer = '___Read1D($aSource, $iFrom)' ; instructions used to repopulate the array region $iFrom = -1 ; increment count for use with ___Read1D $aFloodFill[$aBound[0]]($aArray, $aTemp, $iDimension, $iSubitem, $iFrom, $aFlatArray, $sTransfer) ; flood the region Next Else ; regions will be shuffled within the dimension Local $iRandom $sTransfer = '$aSource' & $sIndices For $iSubitem = 0 To $aBound[$iDimension] $aFloodFill[$aBound[0]]($aRegion, $aTemp, $iDimension, 0, $iSubitem, $aArray, $sTransfer) $sTransfer = '$aTarget' & $sIndices $iRandom = Random(0, $aBound[$iDimension], 1) $aFloodFill[$aBound[0]]($aArray, $aTemp, $iDimension, $iSubitem, $iRandom, $aArray, $sTransfer) $sTransfer = '$aSource' & $sIndices $aFloodFill[$aBound[0]]($aArray, $aTemp, $iDimension, $iRandom, 0, $aRegion, $sTransfer) Next EndIf Else ; not a multidimensional array __Shuffle1D($aArray) ; shuffle the contents EndIf Else ; totally random - ignoring dimension bounds $aFlatArray = $aArray _ArrayFlatten($aFlatArray) ; convert to a 1D array __Shuffle1D($aFlatArray) ; shuffle the contents $iSubitem = 0 ; set to loop through the whole array $iFrom = -1 ; increment count for use with ___Read1D $sTransfer = '___Read1D($aSource, $iFrom)' ; instructions used to repopulate the array $aFloodFill[$aBound[0]]($aArray, $aBound, 0, $iSubitem, $iFrom, $aFlatArray, $sTransfer) ; flood the array EndIf EndFunc ;==> _ShuffleArray ; #FUNCTION# =================================================================================================================== ; Name...........: _UniqueRegion ; Description ...: Removes duplicate items from an array (or duplicate regions from a multidimensional array). ; Syntax.........: _UniqueRegion($aArray [, $bCaseSense = False [, $iDimension = 1]]) ; Parameters.....; $aArray - The array containing duplicate regions to be removed. ; $bCaseSense - [Optional] Set to true for case sensitive matches. Default value = False ; $iDimension - [Optional] Integer value - the dimension to which uniqueness applies. Default = 1st dimension ; Return values .: Success - Returns the unique array [ByRef]. ; Failure sets @error as follows: ; |@error = 1 The 1st parameter is not an array. ; |@error = 2 The 1st parameter has too many dimensions. ; |@error = 3 The 3rd parameter is not a valid dimension. ; |@error = 4 Arrays must contain at least one element. ; Author ........: czardas ; Comments ......; This function is limited to (medium sized) arrays of up to five dimensions. ; All elements within a region must be duplicated (in juxtaposed positions) before removal takes place. ; Integers of the same magnitude are treated as duplicates regardless of data type. ; This function does not remove regions containing objects, DLLStructs or other arrays. ; If you modify _UniqueRegion, avoid using variable names that could collide with internally generated names. ; Example .......; _UniqueRegion($aArray, Default, 2) ; [$iDimension = 2] ; ==> deletes duplicate COLUMNS from a 2D array ; ============================================================================================================================== Func _UniqueRegion(ByRef $aArray, $bCaseSense = Default, $iDimension = 1) If Not IsArray($aArray) Or UBound($aArray, 1) = 0 Then Return SetError(1) ; not a valid array Local $iDim = UBound($aArray, 0) ; get the number of dimensions If $iDim > 5 Then Return SetError(2) ; wrong number of dimensions $iDimension = ($iDimension = Default) ? 1 : Int($iDimension) If $iDimension < 1 Or $iDimension > $iDim Then Return SetError(3) ; [or override ambiguous input with $iDimension = 1] Local $aBound[6] For $i = 1 To $iDim $aBound[$i] = UBound($aArray, $i) -1 ; get the max index in each dimension If $aBound[$i] = -1 Then Return SetError(4) ; $aArray must contain at least one element. Next If $aBound[$iDimension] < 1 Then Return ; the array is already unique For $i = $iDim + 1 To 5 $aBound[$i] = 0 ; set the upper bounds of dimensions to be added Next _Predim($aArray, 5) ; adding more dimensions introduces some latency - too bad because this reduces complexity! Local $sExpression = '$aArray' ; to access elements at their original indeces For $i = 1 To 5 If $i <> $iDimension Then $sExpression &= '[$' & $i & ']' ; default expression = '$aArray[$iFrom][$2][$3][$4][$5]' Else $sExpression &= '[$iFrom]' EndIf Next $aBound[0] = $aBound[$iDimension] ; the first loop will run to the bounds of the specified dimension $aBound[$iDimension] = 0 ; whichever loop this relates to must only run once on each encounter Local $iItems = 0, $aFunction[1] = [0], $vElement, $iInt, $sName If $bCaseSense = Default Then $bCaseSense = False Local $sTransfer = '$aTarget' & __HiddenIndices(5, $iDimension) For $iFrom = 0 To $aBound[0] $sName = '' ; clear previous name For $5 = 0 To $aBound[5] For $4 = 0 To $aBound[4] For $3 = 0 To $aBound[3] For $2 = 0 To $aBound[2] For $1 = 0 To $aBound[1] $vElement = Execute($sExpression) ; get the data contained in each element ; use non-hexadecimal characters (other than x) as datatype identifiers and convert the data to hexadecimal where necessary Switch VarGetType($vElement) Case 'String' If Not $bCaseSense Then $vElement = StringUpper($vElement) ; generates a case insensitive name segment $sName &= 's' & StringToBinary($vElement, 4) ; UTF8 [$SB_UTF8] Case 'Int32', 'Int64' ; use decimal without conversion ; the minus sign of a negative integer is replaced with 'g': to distinguish it from the positive value $sName &= ($vElement < 0) ? 'g' & StringTrimLeft($vElement, 1) : 'i' & $vElement Case 'Double' ; may be an integer $iInt = Int($vElement) $sName &= ($vElement = $iInt) ? (($iInt < 0) ? 'g' & StringTrimLeft($iInt, 1) : 'i' & $iInt) : 'h' & Hex($vElement) Case 'Bool' ; True or False $sName &= ($vElement = True) ? 't' : 'v' Case 'Binary' $sName &= 'y' & $vElement Case 'Ptr' $sName &= 'p' & $vElement Case 'Keyword' ; Default or Null (other variable declarations are illegal) $sName &= ($vElement = Default) ? 'w' : 'n' Case 'Function', 'UserFunction' ; string conversion will fail For $k = 1 To $aFunction[0] ; unique functions are stored in a separate array If $vElement = $aFunction[$k] Then ; this function has been encountered previously $sName &= 'u' & $k ContinueLoop 2 EndIf Next $aFunction[0] += 1 If $aFunction[0] > UBound($aFunction) - 1 Then ReDim $aFunction[$aFunction[0] + 10] $aFunction[$aFunction[0]] = $vElement $sName &= 'u' & $aFunction[0] Case Else ; Array, Object or DLLStruct $sName = False ; set to ignore ExitLoop 5 EndSwitch Next Next Next Next Next If $sName Then If IsDeclared($sName) = -1 Then ContinueLoop ; [$DECLARED_LOCAL] this region has been seen previously Assign($sName, "", 1) ; [else] declare each unique region as a new variable name EndIf ; overwrite the next region (assumes that the first duplicate region will be found quite quickly) ___Flood5D($aArray, $aBound, $iDimension, $iItems, $iFrom, '', $sTransfer) ; access the remote loop region $iItems += 1 Next _Predim($aArray, $iDim) ; remove the extra dimensions $aBound[0] = $iDim ; reset the number of dimensions For $i = 1 To 5 ; reset the bounds $aBound[$i] +=1 Next $aBound[$iDimension] = $iItems ; new bounds of the explicit dimension __ResetBounds($aArray, $aBound) ; remove the remaining duplicate array regions EndFunc ;==>_UniqueRegion #Region - Miscellaneous ; #INTERNAL_USE_ONLY# ========================================================================================================== ; Name...........: __CountElements ; Description ...: Return the total number of elements contained within a multidimensional array. ; ============================================================================================================================== Func __CountElements($aArray) Local $iCount = 1 For $i = 1 to UBound($aArray, 0) $iCount *= UBound($aArray, $i) Next Return $iCount EndFunc ;==> __CountElements ; #INTERNAL_USE_ONLY# ========================================================================================================== ; Name...........: __FloodFunc ; Description ...: Return an array of functions used for populating multidimensional array elements. ; ============================================================================================================================== Func __FloodFunc() Local $aFloodFunc = ['', ___Flood1D, ___Flood2D, ___Flood3D, ___Flood4D, ___Flood5D, ___Flood6D, ___Flood7D, ___Flood8D, ___Flood9D] Return $aFloodFunc EndFunc ;==> __FloodFunc ; #INTERNAL_USE_ONLY# ========================================================================================================== ; Name...........: __GetBounds ; Description ...: Get the bounds of each available dimension in a multidimensional array. ; ============================================================================================================================== Func __GetBounds($aArray, $iHypothetical = 0) Local $iMaxDim = Ubound($aArray, 0) Local $aBound[($iHypothetical ? $iHypothetical : $iMaxDim) +1] ; [or ==> Local $aBound[9]] $aBound[0] = $iMaxDim For $i = 1 To $iMaxDim $aBound[$i] = Ubound($aArray, $i) If $aBound[$i] = 0 Then Return SetError(1) Next If $iHypothetical Then For $i = $iMaxDim +1 To $iHypothetical $aBound[$i] = 1 ; imaginary dimensions Next EndIf Return $aBound EndFunc ;==> __GetBounds ; #INTERNAL_USE_ONLY# ========================================================================================================== ; Name...........: __HiddenIndices ; Description ...: Return a fragment of code which is the format for the $sTransfer parameter in ___FloodXD. ; ============================================================================================================================== Func __HiddenIndices($iBound, $iDimension) Local $sSyntax = '' ; to access elements at their original indeces For $i = 1 To $iBound If $i <> $iDimension Then $sSyntax &= '[$a[' & $i & ']]' ; default ==> '$aSource[$iFrom][$a[2]][$a[3]][$a[4]][$a[5]] etc...' Else $sSyntax &= '[$iFrom]' EndIf Next Return $sSyntax EndFunc ;==> __HiddenIndices ; #INTERNAL_USE_ONLY# ========================================================================================================== ; Name...........: ___NewArray ; Description ...: Create an array of between one and nine dimensions using predefined bounds. ; ============================================================================================================================== Func ___NewArray($aBound) Switch $aBound[0] Case 1 Local $aArray [$aBound[1]] Case 2 Local $aArray [$aBound[1]] [$aBound[2]] Case 3 Local $aArray [$aBound[1]] [$aBound[2]] [$aBound[3]] Case 4 Local $aArray [$aBound[1]] [$aBound[2]] [$aBound[3]] [$aBound[4]] Case 5 Local $aArray [$aBound[1]] [$aBound[2]] [$aBound[3]] [$aBound[4]] [$aBound[5]] Case 6 Local $aArray [$aBound[1]] [$aBound[2]] [$aBound[3]] [$aBound[4]] [$aBound[5]] [$aBound[6]] Case 7 Local $aArray [$aBound[1]] [$aBound[2]] [$aBound[3]] [$aBound[4]] [$aBound[5]] [$aBound[6]] [$aBound[7]] Case 8 Local $aArray [$aBound[1]] [$aBound[2]] [$aBound[3]] [$aBound[4]] [$aBound[5]] [$aBound[6]] [$aBound[7]] [$aBound[8]] Case 9 Local $aArray [$aBound[1]] [$aBound[2]] [$aBound[3]] [$aBound[4]] [$aBound[5]] [$aBound[6]] [$aBound[7]] [$aBound[8]] [$aBound[9]] EndSwitch Return $aArray EndFunc ;==> ___NewArray ; #INTERNAL_USE_ONLY# ========================================================================================================== ; Name...........: ___Read1D ; Description ...: For use with ___FloodXD functions. ; ============================================================================================================================== Func ___Read1D($aSource, ByRef $iFrom) $iFrom += 1 ; for element 0 start with $iFrom = -1 Return $aSource[$iFrom] EndFunc ;==> ___Read1D ; #INTERNAL_USE_ONLY# ========================================================================================================== ; Name...........: __ResetBounds ; Description ...: ReDim arrays of different dimensions. ; ============================================================================================================================== Func __ResetBounds(ByRef $aArray, $aBound) Switch $aBound[0] Case 1 ReDim $aArray [$aBound[1]] Case 2 ReDim $aArray [$aBound[1]] [$aBound[2]] Case 3 ReDim $aArray [$aBound[1]] [$aBound[2]] [$aBound[3]] Case 4 ReDim $aArray [$aBound[1]] [$aBound[2]] [$aBound[3]] [$aBound[4]] Case 5 ReDim $aArray [$aBound[1]] [$aBound[2]] [$aBound[3]] [$aBound[4]] [$aBound[5]] Case 6 ReDim $aArray [$aBound[1]] [$aBound[2]] [$aBound[3]] [$aBound[4]] [$aBound[5]] [$aBound[6]] Case 7 ReDim $aArray [$aBound[1]] [$aBound[2]] [$aBound[3]] [$aBound[4]] [$aBound[5]] [$aBound[6]] [$aBound[7]] Case 8 ReDim $aArray [$aBound[1]] [$aBound[2]] [$aBound[3]] [$aBound[4]] [$aBound[5]] [$aBound[6]] [$aBound[7]] [$aBound[8]] Case 9 ReDim $aArray [$aBound[1]] [$aBound[2]] [$aBound[3]] [$aBound[4]] [$aBound[5]] [$aBound[6]] [$aBound[7]] [$aBound[8]] [$aBound[9]] EndSwitch EndFunc ;==>__ResetBounds ; #INTERNAL_USE_ONLY# ========================================================================================================== ; Name...........: __Shuffle1D ; Description ...: Shuffle a one dimensional array. ; ============================================================================================================================== Func __Shuffle1D(ByRef $aArray) Local $vTemp, $iRandom, $iBound = UBound($aArray) -1 For $i = 0 To $iBound $iRandom = Random(0, $iBound, 1) $vTemp = $aArray[$i] $aArray[$i] = $aArray[$iRandom] $aArray[$iRandom] = $vTemp Next EndFunc ;==> __Shuffle1D #EndRegion - Miscellaneous #Region - Remote Loops ; #INTERNAL_USE_ONLY# ========================================================================================================== ; Name...........: ___Flood1D, ___Flood2D, ___Flood3D, ___Flood4D, ___Flood5D, ___Flood6D, ___Flood7D, ___Flood8D, ___Flood9D ; Description ...: Flood the region of a multidimensional array defined by the subitem within the specified dimension. ; Syntax.........: ___FloodXD($aTarget, $aBound, $iDimension, $iSubitem, $iFrom, $aSource, $sTransfer) ; Parameters.....; $aTarget - Array to populate. ; $aBound - Array containing the bounds of each dimension. ; $iDimension - Integer value defining the dimension. ; $iSubitem - Integer value of the subitem within the dimension. ; $iFrom - [Hidden] Integer value defining a subitem within $aSource. ; $aSource - [Hidden] Array containing data which may be used to populate the target array. ; $sTransfer - String of instructions used to acquire data. ; Return values .: [ByRef] The target array after the region has been flooded. ; Author ........: czardas ; Comments ......; Using remote loops cuts out several hundred lines of duplicated code. ; Recursively targeting a custom function, whichever dimension, is straight forward and reasonably optimal. ; The approach may introduce a small circumstantial speed deficit, which seems a fair trade-off. ; The sequence of loops runs backwards: optimized for higher dimensions with less bounds. ; Only the elements associated with the specified subitem within the defined dimension are overwritten. ; Setting $iDimension to 0 causes the functions to overwrite all the elements within the target array. ; The $sTransfer parameter must be runnable code. ; Unused hidden parameters should be passed as empty strings. ; $aBound[0] can also be used as a wild card. ; ============================================================================================================================== Func ___Flood1D(ByRef $aTarget, $aBound, $iDimension, ByRef $iSubitem, $iFrom, $aSource, $sTransfer) ; [still experimental] #forceref $iDimension, $iFrom, $aSource ; $iDimension would normally not apply here (special case) Local $a[10] = ['',0,0,0,0,0,0,0,0,0] ; loop iteration count [or indeces of higher dimensions within the source array] For $a[1] = $iSubitem To $aBound[1] ; from the start to the bounds of the 1st dimension (special case) ; only one operation is needed in this special case $aTarget[$a[1]] = Execute($sTransfer) ; hidden parameters may appear in the code being executed Next ; the next line could possibly be removed $iSubitem = $aBound[1] ; may indicate to the calling function that the process is complete [kick back effect] EndFunc ;==> ___Flood1D ; ============================================================================================================================== ; the following functions are slightly different ; ============================================================================================================================== Func ___Flood2D(ByRef $aTarget, $aBound, $iDimension, $iSubitem, $iFrom, $aSource, $sTransfer) #forceref $iFrom, $aSource ; hidden parameters Local $a[10] = ['',0,0,0,0,0,0,0,0,0] ; loop iteration count [or indeces of higher dimensions within the source array] For $a[2] = 0 To $aBound[2] For $a[1] = 0 To $aBound[1] $a[$iDimension] = $iSubitem ; override the iteration count (fast method) - $a[0] has no influence $aTarget[$a[1]][$a[2]] = Execute($sTransfer) ; hidden parameters may appear in the code being executed Next Next EndFunc ;==> ___Flood2D ; ============================================================================================================================== ; see previous description and comments ; ============================================================================================================================== Func ___Flood3D(ByRef $aTarget, $aBound, $iDimension, $iSubitem, $iFrom, $aSource, $sTransfer) #forceref $iFrom, $aSource ; as above Local $a[10] = ['',0,0,0,0,0,0,0,0,0] ; as above For $a[3] = 0 To $aBound[3] For $a[2] = 0 To $aBound[2] For $a[1] = 0 To $aBound[1] $a[$iDimension] = $iSubitem ; as above $aTarget[$a[1]][$a[2]][$a[3]] = Execute($sTransfer) ; as above Next Next Next EndFunc ;==> ___Flood3D ; ============================================================================================================================== ; see previous description and comments ; ============================================================================================================================== Func ___Flood4D(ByRef $aTarget, $aBound, $iDimension, $iSubitem, $iFrom, $aSource, $sTransfer) #forceref $iFrom, $aSource Local $a[10] = ['',0,0,0,0,0,0,0,0,0] For $a[4] = 0 To $aBound[4] For $a[3] = 0 To $aBound[3] For $a[2] = 0 To $aBound[2] For $a[1] = 0 To $aBound[1] $a[$iDimension] = $iSubitem $aTarget[$a[1]][$a[2]][$a[3]][$a[4]] = Execute($sTransfer) Next Next Next Next EndFunc ;==> ___Flood4D ; ============================================================================================================================== ; see previous description and comments ; ============================================================================================================================== Func ___Flood5D(ByRef $aTarget, $aBound, $iDimension, $iSubitem, $iFrom, $aSource, $sTransfer) #forceref $iFrom, $aSource Local $a[10] = ['',0,0,0,0,0,0,0,0,0] For $a[5] = 0 To $aBound[5] For $a[4] = 0 To $aBound[4] For $a[3] = 0 To $aBound[3] For $a[2] = 0 To $aBound[2] For $a[1] = 0 To $aBound[1] $a[$iDimension] = $iSubitem $aTarget[$a[1]][$a[2]][$a[3]][$a[4]][$a[5]] = Execute($sTransfer) Next Next Next Next Next EndFunc ;==> ___Flood5D ; ============================================================================================================================== ; see previous description and comments ; ============================================================================================================================== Func ___Flood6D(ByRef $aTarget, $aBound, $iDimension, $iSubitem, $iFrom, $aSource, $sTransfer) #forceref $iFrom, $aSource Local $a[10] = ['',0,0,0,0,0,0,0,0,0] For $a[6] = 0 To $aBound[6] For $a[5] = 0 To $aBound[5] For $a[4] = 0 To $aBound[4] For $a[3] = 0 To $aBound[3] For $a[2] = 0 To $aBound[2] For $a[1] = 0 To $aBound[1] $a[$iDimension] = $iSubitem $aTarget[$a[1]][$a[2]][$a[3]][$a[4]][$a[5]][$a[6]] = Execute($sTransfer) Next Next Next Next Next Next EndFunc ;==> ___Flood6D ; ============================================================================================================================== ; see previous description and comments ; ============================================================================================================================== Func ___Flood7D(ByRef $aTarget, $aBound, $iDimension, $iSubitem, $iFrom, $aSource, $sTransfer) #forceref $iFrom, $aSource Local $a[10] = ['',0,0,0,0,0,0,0,0,0] For $a[7] = 0 To $aBound[7] For $a[6] = 0 To $aBound[6] For $a[5] = 0 To $aBound[5] For $a[4] = 0 To $aBound[4] For $a[3] = 0 To $aBound[3] For $a[2] = 0 To $aBound[2] For $a[1] = 0 To $aBound[1] $a[$iDimension] = $iSubitem $aTarget[$a[1]][$a[2]][$a[3]][$a[4]][$a[5]][$a[6]][$a[7]] = Execute($sTransfer) Next Next Next Next Next Next Next EndFunc ;==> ___Flood7D ; ============================================================================================================================== ; see previous description and comments ; ============================================================================================================================== Func ___Flood8D(ByRef $aTarget, $aBound, $iDimension, $iSubitem, $iFrom, $aSource, $sTransfer) #forceref $iFrom, $aSource Local $a[10] = ['',0,0,0,0,0,0,0,0,0] For $a[8] = 0 To $aBound[8] For $a[7] = 0 To $aBound[7] For $a[6] = 0 To $aBound[6] For $a[5] = 0 To $aBound[5] For $a[4] = 0 To $aBound[4] For $a[3] = 0 To $aBound[3] For $a[2] = 0 To $aBound[2] For $a[1] = 0 To $aBound[1] $a[$iDimension] = $iSubitem $aTarget[$a[1]][$a[2]][$a[3]][$a[4]][$a[5]][$a[6]][$a[7]][$a[8]] = Execute($sTransfer) Next Next Next Next Next Next Next Next EndFunc ;==> ___Flood8D ; ============================================================================================================================== ; see previous description and comments ; ============================================================================================================================== Func ___Flood9D(ByRef $aTarget, $aBound, $iDimension, $iSubitem, $iFrom, $aSource, $sTransfer) #forceref $iFrom, $aSource Local $a[10] = ['',0,0,0,0,0,0,0,0,0] For $a[9] = 0 To $aBound[9] For $a[8] = 0 To $aBound[8] For $a[7] = 0 To $aBound[7] For $a[6] = 0 To $aBound[6] For $a[5] = 0 To $aBound[5] For $a[4] = 0 To $aBound[4] For $a[3] = 0 To $aBound[3] For $a[2] = 0 To $aBound[2] For $a[1] = 0 To $aBound[1] $a[$iDimension] = $iSubitem $aTarget[$a[1]][$a[2]][$a[3]][$a[4]][$a[5]][$a[6]][$a[7]][$a[8]][$a[9]] = Execute($sTransfer) Next Next Next Next Next Next Next Next Next EndFunc ;==> ___Flood9D #EndRegion - Remote Loops This UDF and all examples can be downloaded in the zip archive below.
      ArrayWorkshop.7z
    • antmar904
      How to display multiple Excel columns in array
      By antmar904
      Hi all,
      I am trying to disply columns B and F in an array but its not working.
       
      #include <Excel.au3> #include <Array.au3> #include <File.au3> $oExcel = _Excel_Open ("", "", "", "", True) $Book = _Excel_BookOpen($oExcel, @ScriptDir & "\LNExport.xlsx") $Range1 = $Book.Activesheet.Range("B2").EntireColumn $Range2 = $Book.Activesheet.Range("F2").EntireColumn $Result = _Excel_RangeRead($Book, "Sheet 1", $Range1:$Range2) _ArrayDisplay($Result) _Excel_Close($Book) _Excel_Close($oExcel)  
      I can successfully display either column B or column F but I cannot display them both at the same time.
    • ahha
      [Solved] Memory Leak
      By ahha
      I'm basically processing text files where I'm reading them from a disk file into an input array, going through the input array and skipping what I don't want and writing it out to an output array and then writing the output array to a disk file.  I encountered an "Error allocating memory" message.  I have stripped down the program to illustrate how the memory usage grows in a looping routine (__ReadFiles).  I have tried a _ReduceMemory routine (from https://www.autoitscript.com/forum/topic/134831-is-there-a-way-to-free-up-memory-being-used/ ) and it helps somewhat, however the peak working set continues to grow regardless.  I believe I'm releasing resources (resetting arrays to 0) and am trying to figure out if the leak is from FileFindNextFile or something else I'm doing.   To illustrate the program creates a subdirectory with 50000 simple text files and then runs showing the growing memory usage, Ctrl+q will pause program.  Rerunning the program uses the already created files so it does not have to be re-created.  Any help appreciated.
      ; use this to debug in console window <--- LOOK #AutoIt3Wrapper_run_debug_mode=Y ;#AutoIt3Wrapper_Run_Debug=off ;#AutoIt3Wrapper_Run_Debug=on #include <Array.au3> #include <File.au3> #include <MsgBoxConstants.au3> #include <GUIConstantsEx.au3> #include <EditConstants.au3> HotKeySet ( "^q", "EndProgram" ) ;v2e - added HotKeySet ( "^q", "EndProgram" ); CTRL+q so can pause/exit script Global $hEdit ;for scrolling text box Global $textarray[1] ;1 element $textarray[0] = 0 ;initial count Global $newtextarray[1] ;1 element $newtextarray[0] = 0 ;initial count Global $dir Global $k ;loop count Global $aMemory ;v1g for use in __ShowMemoryUsage("Location: In FileFindNextFile While 1 loop.") Global $debug = 0 ;0=off, 1=on , 2=deeper, - use debug > 1 to see arrays in Funcs $version = "v1g" ;v1g - we have an Autoit "Error allocating memory" somewhere - printing out WorkingSetSize and PeakWorkingSetSize from ProcessGetStats to try and find it __scrolling_text_box_init("--- Read files ---", 1050, 450) ;__scrolling_text_box_init($title, $width, $height) ;set up box - to display text use: __scrolltext($text) WinMove("--- Read files ---", "", 2000, 300) ;move so can see it - on single screen use 10, 30 on dual screen use 2000, 300 __scrolltext("Starting: " & @CRLF) ;illustrate error using current script directory by creating unique directotry and create file in it and put some text into it ----------- $dir = @ScriptDir ;for iterative testing see if test directory already exists - i.e. only need to build this once $dir = @ScriptDir & "\testdir_xcrgua" ;highly unlikely areadly exists unless this program was already run $str = "" ;null it For $j = 1 to 100 ;put 100 lines in each file $str = $str & $j & @CRLF Next If DirGetSize($dir) = -1 Then DirCreate($dir) ;create directory ;then create and fill it For $i = 1 to 50000 ;brute force (and I know it's slow, however straightforward and only 1 time FileWrite($dir & "\" & $i & ".txt", $str) If $i/1000 = Int($i/1000) Then __scrolltext("Writing test file " & $i & "/50000" & @CRLF) Next EndIf MsgBox(262144, "DEBUG", $dir & " <-- should have 50000 files each with 100 numbered lines 1- 100.") MsgBox(262144, "DEBUG", "Paused.") __scrolltext("Reading files in dir = " & $dir & @CRLF) ;__ShowMemoryUsage("Location: Before file count.") ;v1g $fc = __GetFileCount($dir) ;returns file count in $dir ;__ShowMemoryUsage("Location: After file count.") ;v1g __scrolltext("Number of files in dir = " & $fc & @CRLF) MsgBox(262144, "DEBUG", "Paused.") ;in this we get memory allocation erroroccurs between 25K and 50K on my machine __ReadFiles($dir) MsgBox(262144, "DEBUG", "Paused out of loop.") Exit ;----------------------------------- Functions ----------------------------------- Func __ShowMemoryUsage($title) $aMemory = ProcessGetStats() ; Retrieve memory details about the current process. ; If $aMemory is an array then display the following details about the process. If IsArray($aMemory) Then __scrolltext($title & " " & "WorkingSetSize: " & $aMemory[0] & " PeakWorkingSetSize: " & $aMemory[1] & @CRLF) Else __scrolltext("An error occurred in ProcessGetStats() in Func __ShowMemoryUsage($title).") EndIf EndFunc ;__ShowMemoryUsage($title) Func _ReduceMemory($i_PID = -1) ;from https://www.autoitscript.com/forum/topic/134831-is-there-a-way-to-free-up-memory-being-used/ If $i_PID <> -1 Then Local $ai_Handle = DllCall("kernel32.dll", 'int', 'OpenProcess', 'int', 0x1F0FFF, 'int', False, 'int', $i_PID) Local $ai_Return = DllCall("psapi.dll", 'int', 'EmptyWorkingSet', 'long', $ai_Handle[0]) DllCall('kernel32.dll', 'int', 'CloseHandle', 'int', $ai_Handle[0]) Else Local $ai_Return = DllCall("psapi.dll", 'int', 'EmptyWorkingSet', 'long', -1) EndIf Return $ai_Return[0] EndFunc ;==>_ReduceMemory Func __GetFileCount($dir) ;returns number of files in $dir - brute force but only about 50K files/directory ;MsgBox(0, "DEBUG", "$dir = '" & $dir & "'") #AutoIt3Wrapper_Run_Debug=off $fcount = 0 ;init count $search = FileFindFirstFile($dir & "\*.*") If $search = -1 Then ;no files found Return($fcount) ;MsgBox(0, "Error", "No files/directories matched the search pattern") ;Exit EndIf ;okay check number of files While 1 $file = FileFindNextFile($search) If @error Then ExitLoop ;exit loop when there are no more files Else $fcount = $fcount + 1 EndIf WEnd FileClose($search) ;be polite Return($fcount) #AutoIt3Wrapper_Run_Debug=on EndFunc Func __ReadFiles($dir) ;just reading to show memory alloc error Local $x Local $skipline #AutoIt3Wrapper_Run_Debug=off $tfc = __GetFileCount($dir) ;get total file count so we can show progress #AutoIt3Wrapper_Run_Debug=on $cfc = 0 ;init currect file count $search = FileFindFirstFile($dir & "\*.*") ;get search handle If $search = -1 Then ;no files found __scrolltext("Working on file: " & $cfc & "/" & $tfc & @CRLF) Return ;MsgBox(0, "Error", "No files/directories matched the search pattern") ;Exit EndIf ;okay go through the files one by one While 1 ;_ReduceMemory() ;this makes little difference - surprising $file = FileFindNextFile($search) If @error = 1 Then ExitLoop ;exit loop when there are no more to do If @extended = 1 Then $adir = 1 ;we have a directory so note it Else $adir = 0 ;a file EndIf ;MsgBox(4096, "File:", $directory&"\"&$file) $cfc = $cfc + 1 __scrolltext("Working on file: " & $cfc & "/" & $tfc & " " & $file & @CRLF) ;show the filename __ShowMemoryUsage("Location: In FileFindNextFile While 1 loop.") ;v1g ;clear out arrays so we have no artifacts from procesing the prior loop ;from here it looks like resetting it is better https://www.autoitscript.com/forum/topic/110933-solved-how-to-delete-whole-array/ $testarray = 0 $newtextarray = 0 Dim $textarray[1] ;1 element $textarray[0] = 0 ;initial count Dim $newtextarray[1] ;1 element $newtextarray[0] = 0 ;initial count ;bring file into memory for faster processing If $adir = 0 Then ;process file $x = _FileReadToArray($dir & "\" & $file, $textarray) ;bring file into memory for faster processing [0] has $textarray count If $x <> 1 Then MsgBox($MB_TOPMOST + $MB_ICONERROR, "ERROR", "Unable to read file into array. Error = " & $x & " @error = " & @error & " @extended = " & @extended) Exit EndIf If $debug > 0 Then _ArrayDisplay($textarray, "INPUT $textarray") ReDim $newtextarray[$textarray[0] + 1] ;create output array ($newtextarray) of the same size as input array ($textarray) and later ReDim the output array to the correct size $newtextarray[0] = 0 ;set the count of actual entries as $newtextarray is empty but has same size as $textarray If $debug > 0 Then _ArrayDisplay($newtextarray, "Starting $newtextarray") ;now the approach is to write out only lines we want then to file For $i = 1 to $textarray[0] ;process all elements (rows, lines) in input array ;If $debug > 0 Then __scrolltext("$textarray[" & $i & "] = '" & $textarray[$i] & "'" & @CRLF) ;show the line $skipline = 0 ;init value to not skip line ;----------- start stripping out stuff ----------- ;this rountine is not the cause of the memory leak so removed ;------------- If $skipline = 0 Then ;write it out $newtextarray[0] = $newtextarray[0] + 1 ;increase count and point to index where we're going to store it in $newtextarray $newtextarray[$newtextarray[0]] = $textarray[$i] Else ;skip the line EndIf Next $fn = $dir & "\processed-1\" & StringLeft($file, StringLen($file) - 4) & "-1.txt" __scrolltext("Processed file written to: " &$fn & @CRLF) ;show the line ;RECALL written out like an array so 1st entry which corresponds to index [0] has count of rows = lines in the file Else ;its a directory - skip it __scrolltext("NOT processed directory (i.e. skipped) : " & $dir & "\" & $file & @CRLF) ;show the line EndIf WEnd EndFunc ;__CleanFiles($dir) Func __scrolling_text_box_init($title, $width, $height) ;from http://www.autoitscript.com/forum/topic/110948-add-text-to-edit-box-and-scroll-it-down/page__p__971158__hl___guictrledit_scroll__fromsearch__1#entry971158 $hGUI = GUICreate($title, $width, $height) $hEdit = GUICtrlCreateEdit("", 10, 10, $width-20, $height-20, BitOr($GUI_SS_DEFAULT_EDIT, $ES_READONLY)) ;$limit = 9223372036854775807 ;2^63 $limit = 1000000000 ;works $x = GUICtrlSetLimit($hEdit, $limit) ;~ If $x = 0 Then ;~ MsgBox(0, "ERROR", "Limit of " & $limit & " is too large.") ;~ Else ;~ MsgBox(0, "Okay", "Limit of " & $limit & " is okay.") ;~ EndIf ;$hButton = GUICtrlCreateButton("Add", 10, 250, 80, 30) GUISetState() EndFunc Func __scrolltext($text) #AutoIt3Wrapper_Run_Debug=off ;prefix everything with date and time e.g. 2014-02-01 HH:MM:SS $dt = @YEAR & "-" & @MON & "-" & @MDAY & " " & @HOUR & ":" & @MIN & ":" & @SEC & " " $text = $dt & $text GUICtrlSetData($hEdit, $text, 1) #AutoIt3Wrapper_Run_Debug=on EndFunc Func EndProgram() $x = MsgBox($MB_TOPMOST + $MB_YESNO + $MB_ICONWARNING, "Paused", "Do you want to continue?") If $x = $IDNO Then Exit ;exit program Else ;just a pause - so continue EndIf EndFunc  
      04 - Clean files - v1g - test for memory leak v1c.au3
    • lrstndm
      Read out excel to array
      By lrstndm
      Hi All,
      How is it possible to read out a Excel file without opening the excel file itself in excel?
      With the current posts on the forum it's for me not possible to fix my issue.
      I was looking at the Excel.au3 include file but this did not help me.
      Could someone help me please?
      Regards,
      lrstndm