Jump to content

_ArrayAddColumns


BrewManNH
 Share

Recommended Posts

I was inspired to create this little function by the discussion that was going on in thread. What this function does is it allows you to add any number of columns to a 1D or 2D array up to the max number of columns. I have tested this up to a max of 251 columns in total.

I have added some error checking to it that checks to see if wasn't passed an array, your columns to add are less than 1 (can't add zero columns or use negative numbers), and checks if the array has too many dimensions. It preserves the contents of the passed array without using ReDim, although I'm not sure of the speed impact that would have on something like this.

_ArrayAddColumns

; #FUNCTION# ====================================================================================================================
; Name...........: _ArrayAddColumns
; Description ...: Adds a specified number of columns to an array.
; Syntax.........: _ArrayAddColumns(ByRef $aArrayIn, $NumColCount)
; Parameters ....: $aArrayIn - Array to modify
;                  $NumColCount  - Number of columns to add (default = 1)
; Return values .: Success - New array with columns added
;                  Failure - -1, sets @error
;                  |1 - $aArrayIn is not an array
;                  |2 - $NumColCount is an invalid number
;                  |3 - Array has too many dimensions (2D array max)
; Author ........: Bob Marotte aka BrewManNH
; Remarks .......: This will add any number of columns to a 1D or 2D array of any size and preserves
;                  the contents of the array being modified
; Related .......: _ArrayConcatenate, _ArrayDelete, _ArrayInsert, _ArrayPop, _ArrayPush
; Link ..........:
; Example .......: Yes
; ===============================================================================================================================
Func _ArrayAddColumns(ByRef $aArrayIn, $NumColCount = 1)
    If Not IsArray($aArrayIn) Then
        SetError(1)
        Return -1
    EndIf
    If $NumColCount < 1 Then
        SetError(2)
        Return -1
    EndIf
    Local $iDimensions = UBound($aArrayIn, 0)
    If $iDimensions > 2 Then
        SetError(3)
        Return -1
    EndIf
    Local $NewArrayOut[UBound($aArrayIn)][$iDimensions + $NumColCount + 1]
    For $I = 0 To UBound($aArrayIn) - 1
        If $iDimensions > 1 Then
            For $X = 0 To $iDimensions
                $NewArrayOut[$I][$X] = $aArrayIn[$I][$X]
            Next
        Else
        $NewArrayOut[$I][0] = $aArrayIn[$I]
        EndIf
    Next
    Return $NewArrayOut
EndFunc   ;==>_ArrayAddColumns

Demo

#include <Array.au3>
Global $Array[10][3], $Array1
For $I = 0 To 9
    $Array[$I][0] = "Row " & $I
    $Array[$I][1] = "Column 1"
    $Array[$I][2] = "Column 2"
Next
_ArrayDisplay($Array)
$Array1 = _ArrayAddColumns($Array, 5) ; Adds 5 columns to $Array and returns the result to $Array1
_ArrayDisplay($Array, "Line Number " & @ScriptLineNumber & " - $Array")
_ArrayDisplay($Array1, "Add 5 columns to $Array and return them it to $Array1")
$Array = _ArrayAddColumns($Array, 10) ; Adds 10 columns to $Array
_ArrayDisplay($Array, "After adding 10 Columns to - $Array")
$Array1 = ""
$Array = _ArrayAddColumns($Array1, 1) ; $Array1 isn't an array will cause error code to be returned
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $Array = ' & $Array & @crlf & '>Error code: ' & @error & @crlf) ;### Debug Console

; #FUNCTION# ====================================================================================================================
; Name...........: _ArrayAddColumns
; Description ...: Adds a specified number of columns to an array.
; Syntax.........: _ArrayAddColumns(ByRef $aArrayIn, $NumColCount)
; Parameters ....: $aArrayIn - Array to modify
;                  $NumColCount  - Number of columns to add (default = 1)
; Return values .: Success - New array with columns added
;                  Failure - -1, sets @error
;                  |1 - $aArrayIn is not an array
;                  |2 - $NumColCount is an invalid number
;                  |3 - Array has too many dimensions (2D array max)
; Author ........: Bob Marotte aka BrewManNH
; Remarks .......: This will add any number of columns to a 1D or 2D array of any size and preserves
;                  the contents of the array being modified
; Related .......: _ArrayConcatenate, _ArrayDelete, _ArrayInsert, _ArrayPop, _ArrayPush
; Link ..........:
; Example .......: Yes
; ===============================================================================================================================
Func _ArrayAddColumns(ByRef $aArrayIn, $NumColCount = 1)
    If Not IsArray($aArrayIn) Then
        SetError(1)
        Return -1
    EndIf
    If $NumColCount < 1 Then
        SetError(2)
        Return -1
    EndIf
    Local $iDimensions = UBound($aArrayIn, 0)
    If $iDimensions > 2 Then
        SetError(3)
        Return -1
    EndIf
    Local $NewArrayOut[UBound($aArrayIn)][$iDimensions + $NumColCount + 1]
    For $I = 0 To UBound($aArrayIn) - 1
        If $iDimensions > 1 Then
            For $X = 0 To $iDimensions
                $NewArrayOut[$I][$X] = $aArrayIn[$I][$X]
            Next
        Else
        $NewArrayOut[$I][0] = $aArrayIn[$I]
        EndIf
    Next
    Return $NewArrayOut
EndFunc   ;==>_ArrayAddColumns

Edit: Typo in the #include line as I was using a modified Array.au3 file.

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

  • Developers

You do know that Redim does preserve the Array content that "fits" so something like this will also work to all 10 columns:

ReDim $Array[UBound($Array,1)][UBound($Array,2)+10]

Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

Nice code! Another point is lines like this >>

SetError(1)
Return -1

can be reduced to a single Return using >>

SetError(1, 0, -1) ; SetError(Error Occurred, @Extended Value, Return Value)
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

Nice code! Another point is lines like this >>

SetError(1)
Return -1

can be reduced to a single Return using >>

SetError(1, 0, -1) ; SetError(Error Occurred, @Extended Value, Return Value)

Forgot about the extended options of SetError, I had it like that to try different options on the return value and neglected looking at the other settings for that command.

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

You do know that Redim does preserve the Array content that "fits" so something like this will also work to all 10 columns:

ReDim $Array[UBound($Array,1)][UBound($Array,2)+10]

I do know about ReDim and the contents of the array. With this code you can also make a copy of the original array to a new one and not affect the original array in case you needed to do this. It probably doesn't have a whole lot of uses, but I figured it can't hurt to have it out there. :)

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

I did it both ways and it didn't affect the outcome using it with or without ByRef when I experimented with it, so I left it as is. I probably could have removed the ByRef, but when I put it in there it was because the remarks section for Functions says it should be passed that way so I did it that way. I never actually modify the $ArrayIn in any way, so it doesn't change the original array inside the function.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

I just tested Jos' code in a simple test, and ReDim didn't preserve the contents of the array when I tested it. Here's the code I tested, maybe I did something wrong with it.

#include <Array.au3>
Global $Array[10]
For $i = 0 To 9
    $Array[$I] = Chr($I + 65)
Next
_ArrayDisplay($Array)
ReDim $Array[UBound($Array,1)][UBound($Array,2)+10] ;<<<<<<<<<<<<<<<< this line was copied from Jos' post above
_ArrayDisplay($Array)

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

  • Moderators

BrewManNH,

maybe I did something wrong

Yes, ReDim will only save the contents if the number of dimensions (i.e the number of [ ]) remains the same. If you alter that it acts like Global or Local (or Dim although you should not use that). If you merely change the value of a dimension it keeps the old elements.

So you have to trick AutoIt by declaring the array with 2 dimensions, but with the second set to 1 - like this: :)

#include <Array.au3>
Global $Array[10][1]
For $i = 0 To 9
    $Array[$I][0] = Chr($I + 65)
Next
_ArrayDisplay($Array)
ReDim $Array[UBound($Array,1)][UBound($Array,2)+10]
_ArrayDisplay($Array)

That works for me. :)

M23

Edit: Typnig!

Edited by Melba23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

So, I was right, the code posted by Jos wouldn't replace the function that I posted? Just wanted to be sure that I hadn't missed something in regards to ReDim and a 1D to 2D array.

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

  • Moderators

BrewManNH,

You are correct, ReDim will not allow you to create a 2D array from a 1D array and keep the contents of the original 1D array.

My example used a 2D array with only 1 value in the second dimension - legal but sneaky. :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Try this example. The correct number of columns as requested are added to a 1d (one dimensional) array - which the OP's function does not.

#include <Array.au3>

Local $Array2[6] = [1, 2, 3, 4, 5, 6]
Local $Array[10][3], $Array1

For $i = 0 To 9
    $Array[$i][0] = "Row " & $i
    $Array[$i][1] = "Column 1"
    $Array[$i][2] = "Column 2"
Next

_ArrayDisplay($Array, "2D Array Before")
$Array1 = _ArrayAddColumns($Array, 5) ; Adds 5 columns to $Array and returns the result to $Array1
_ArrayDisplay($Array1, "Add 5 columns to 2D Array")


_ArrayDisplay($Array2, "1D Array Before")
$Array1 = _ArrayAddColumns($Array2, 5) ; Adds 5 columns to $Array and returns the result to $Array1
_ArrayDisplay($Array1, "Add 5 columns to 1D Array")


Func _ArrayAddColumns(ByRef $aArr, $iNumColToAdd = 1)
    If IsArray($aArr) = 0 Then Return SetError(1, 0, -1) ; Filter out non-array
    If $iNumColToAdd < 1 Then Return SetError(2, 0, -1) ; $iNumColToAdd must be greater than zero to add a column.
    If UBound($aArr, 0) > 2 Then Return SetError(3, 0, -1) ; Only allows a 1d or 2d array pass this line.

    If UBound($aArr, 0) = 1 Then ; ====== For 1d array ========
        Local $aRet[UBound($aArr)][$iNumColToAdd + 1] ; Create new 2d array.
        For $r = 0 To UBound($aArr) - 1
            $aRet[$r][0] = $aArr[$r]
        Next
    Else ; ======= For 2d array ============
        Local $aRet = $aArr ; So that ByRef $aArr is not altered outside of function.
        ReDim $aRet[UBound($aRet)][UBound($aRet, 2) + $iNumColToAdd] ; ReDim 2d array only.
    EndIf

    Return $aRet
EndFunc   ;==>_ArrayAddColumns
Link to comment
Share on other sites

Try this modification to the original code, it avoides using ReDim and corrects the problem Malkey pointed out. I have to do more testing next time. :)

Func _ArrayAddColumns(ByRef $aArrayIn, $NumColCount = 1)
    If Not IsArray($aArrayIn) Then
        Return SetError(1, 0, -1)
    EndIf
    If $NumColCount < 1 Then
        Return SetError(2, 0, -1)
    EndIf
    Local $iDimensions = UBound($aArrayIn, 0)
    If $iDimensions > 2 Then
        Return SetError(3, 0, -1)
    EndIf
    If $iDimensions >1 Then
        Local $NewArrayOut[UBound($aArrayIn)][$iDimensions + $NumColCount + 1]
    Else
        Local $NewArrayOut[UBound($aArrayIn)][$iDimensions + $NumColCount]
        _ArrayDisplay($NewArrayOut)
    EndIf
    For $I = 0 To UBound($aArrayIn) - 1
        If $iDimensions > 1 Then
            For $X = 0 To $iDimensions
                $NewArrayOut[$I][$X] = $aArrayIn[$I][$X]
            Next
        Else
        $NewArrayOut[$I][0] = $aArrayIn[$I]
        EndIf
    Next
    Return $NewArrayOut
EndFunc   ;==>_ArrayAddColumns
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

it avoides using ReDim

Why?

--- ---

@general

func(Byref $array, ...) ;; no need to ByRef it, if I remember correct. (not tested it though)

or

func(Byref Const $array, ...) ;; no need to comment on the fact that $array is NOT going to be changed inside the function.

;; + complementary error message in case you accidentally try to do so anyway.

"Straight_and_Crooked_Thinking" : A "classic guide to ferreting out untruths, half-truths, and other distortions of facts in political and social discussions."
"The Secrets of Quantum Physics" : New and excellent 2 part documentary on Quantum Physics by Jim Al-Khalili. (Dec 2014)

"Believing what you know ain't so" ...

Knock Knock ...
 

Link to comment
Share on other sites

Why?

Trying to avoid any speed issues with using ReDim. I don't know if avoiding it will help or hurt the UDF but it works without it, so why bother using it? If it's shown that using Redim would actually be faster than this, I can always change it. But, ReDim won't preserve the contents of an array if you change the dimensions of it, unless you use a programming trick to do so, my function doesn't require you to do that.

--- ---

@general

func(Byref $array, ...) ;; no need to ByRef it, if I remember correct. (not tested it though)

or

func(Byref Const $array, ...) ;; no need to comment on the fact that $array is NOT going to be changed inside the function.

;; + complementary error message in case you accidentally try to do so anyway.

I went that way because the Help file says to pass arrays that way

ByRef is typically preferred when a function expects large amounts of data, such as a large array, where copying all the data would impose a significant performance penalty.

Seeing as how I can't anticipate the size of an array someone might pass to this function, I did it this way to follow the help file suggestion and avoid any performance penalties.

The reason I commented on the fact that the original array isn't touched by this function, unless you use the incoming array as the array that receives the changed array, is because it is important to note that using this incorrectly won't affect the original array if you send it something that might cause an error. Which might cause trouble shooting issues later in someone's script.

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

Trying to avoid any speed issues with using ReDim.

There are no speed issues with ReDim.

Redim will alway be faster (way faster on big array's!) than creating a new array and manually copying the data from one array to the other. (same array dimension count on both array's of course.)

But, ReDim won't preserve the contents of an array if you change the dimensions of it, unless you use a programming trick to do so, my function doesn't require you to do that.

Erm ... See Malkey's code. He did it without needing to use that trick. (nor is the caller required to use that trick when calling his function.)

(think "trick" is overstating it a bit. -> ref: Dim Array[X][1])

I went that way because the Help file says to pass arrays that way

Arrays should be passed to user-defined functions using the ByRef keyword to avoid the overhead of copying all the data in the array.

Yep. So it is ... (Not bad advice, but it might be a bit general or outdated to. ...) Edited by iEvKI3gv9Wrkd41u

"Straight_and_Crooked_Thinking" : A "classic guide to ferreting out untruths, half-truths, and other distortions of facts in political and social discussions."
"The Secrets of Quantum Physics" : New and excellent 2 part documentary on Quantum Physics by Jim Al-Khalili. (Dec 2014)

"Believing what you know ain't so" ...

Knock Knock ...
 

Link to comment
Share on other sites

True, ReDim would be faster than an interpreted script, should have realized that in the beginning, but I'm still learning as I go. Either way though it's still plenty fast using either method, even on a 1000 row array, although in my timing tests, using ReDim is far and away faster.

Having an easy way to add column(s) to an array might be a good thing to add to the Array.au3 UDF, as I've seen a few posts asking how to do it. Or if not, at least now there's a thread showing various ways to do it. :)

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

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