orbs

Better way to handle many parameters for a function?

12 posts in this topic

'?do=embed' frameborder='0' data-embedContent>>

In the link above i made a function with 3 mandatory parameters, 5 optional, and maybe 2 more will be added. That's prone to confusion when the calling script needs to set only one or two of the optional parameters, leaving the rest at "Default". How would you handle this?

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

I've always liked a keyword=value type parm structure.  You could pass the whole thing as a string and parse it yourself within the function.  Some of the UDFs pass a string using the alternation char or semi-colon to seperate values.  If you do NOT want to follow AutoIT syntax conventions then it is up to you to "roll your own".

edit: You can also have a func with all parms being optional.  It will still be up to you to validate whatever is passed.

Edited by kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

Another approach is using an object orientated-like structure, whereby a user creates/returns an object (internal array) from a create method and then passed to relevant methods e.g.

#cs
    The following can be expanded by using PreExpand (see my signature). It's only because magic values cause confusion, I mean what does 0 mean?
#ce

; An enumeration, so I don't have to remember what 0, 1, 2 or 3 means in the internal array. It's also easy to expand as I can move around the enum variable without affecting the array. 
; Whereas if I used hard coded numbers i.e. 1 or 0, then if I wanted to swap the location of 0 with 2 and 2 with 0, then I would have to do a really difficult "search 'n' replace". #smartarrayuse.
Global Enum $CUSTOMUDF_FILEPATH, $CUSTOMUDF_STARTTIME, $CUSTOMUDF_GUIDID, $CUSTOMUDF_MAX
Global Const $CUSTOMUDF_GUID = 'C88F0862-EEDD-4205-9191-97B3F762DB41'

Example()

Func Example()
    Local $hCustomUDF = CustomUDF_Create(@ScriptFullPath) ; Create an object.
    CustomUDF_Print($hCustomUDF) ; Print the object details.

    Sleep(250) ; Wait to see the updated time difference in the next line.

    CustomUDF_UpdateTime($hCustomUDF) ; Update the time of the object.
    CustomUDF_Print($hCustomUDF) ; Print the object details.

    CustomUDF_Close($hCustomUDF) ; Destroy the object.

    $hCustomUDF = 0 ; Destroy the object reference.
    CustomUDF_Print($hCustomUDF) ; Print the object details (notice that we see an error as __CustomUDF_IsAPI() returned false.
EndFunc   ;==>Example

Func CustomUDF_Create($sFilePath) ; Create an object (which is just an internal array that we hide from the user.
    Local $aAPI[$CUSTOMUDF_MAX]
    $aAPI[$CUSTOMUDF_FILEPATH] = $sFilePath
    $aAPI[$CUSTOMUDF_STARTTIME] = @HOUR & @MIN & @MSEC
    $aAPI[$CUSTOMUDF_GUIDID] = $CUSTOMUDF_GUID ; The GUID is to check that a user doesn't pass an array with 4 elements (by mistake). It's additional verification.
    Return $aAPI
EndFunc   ;==>CustomUDF_Create

Func CustomUDF_UpdateTime(ByRef $aAPI) ; Update the time of the object.
    Local $bReturn = __CustomUDF_IsAPI($aAPI)
    If $bReturn Then
        $aAPI[$CUSTOMUDF_STARTTIME] = @HOUR & @MIN & @MSEC
    EndIf
    Return $bReturn
EndFunc   ;==>CustomUDF_UpdateTime

Func CustomUDF_Print(ByRef $aAPI) ; Print the object contents.
    Local $bReturn = __CustomUDF_IsAPI($aAPI)
    If $bReturn Then
        ConsoleWrite('File: ' & $aAPI[$CUSTOMUDF_FILEPATH] & ', was started at ' & $aAPI[$CUSTOMUDF_STARTTIME] & @CRLF)
    Else
        ConsoleWrite('Error: Invalid object' & @CRLF)
    EndIf
    Return $bReturn
EndFunc   ;==>CustomUDF_Print

Func CustomUDF_Close(ByRef $aAPI) ; Destroy the object contents.
    If __CustomUDF_IsAPI($aAPI) Then
        For $i = 0 To $CUSTOMUDF_MAX - 1
            $aAPI[$i] = Null
        Next
    EndIf
    Return True
EndFunc   ;==>CustomUDF_Close

Func __CustomUDF_IsAPI(ByRef $aAPI)
    Return UBound($aAPI) = $CUSTOMUDF_MAX And $aAPI[$CUSTOMUDF_GUIDID] = $CUSTOMUDF_GUID ; The GUID is to check that a user didn't pass an array with 4 elements (by mistake). It's additional verification.
EndFunc   ;==>__CustomUDF_IsAPI

You can see this quite a bit in my coding style, especially in password valid (see signature).

Edited by guinness

_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 for this concept. i implemented [some type of] it in the topic linked at the first post. i also threw in some possibilities to:_Create() a default parameters array, _Update() it with some non-default parameters, and _Duplicate() it - as well as calling the main function with some specific parameters even without creating a parameters array. tried to keep all options on the table, for the calling script to choose from - so it can be either a set of calls to build the parameters array, or just a one-liner.

the method suggested by kylomas does not fit well with the specific purpose at hand, as the parameters involve mainly string conditions. when an entire group of string conditions requires string manipulation, things get ugly. the first beast to raise its head out of that swamp was deciding on a delimiter, and then the need to allow the calling script to decide on it when the obvious happens and the default delimiter is invalid. i did not tread further down that path.

anyway thanks for all the help!

Share this post


Link to post
Share on other sites

Okay.


_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

orbs,

FYI, something like this is what I had in mind.  This is proof of concept only.  There still remains the problem of the seperator char residing in the "value" portion of the parm but I suspect that this could be worked out.

#include <array.au3>

_arraydisplay(_1('start date = 01/01/2001','user name = Joe', 'acton= Delete'))

func _1($prm1='', $prm2='', $prm3='', $prm4='', $prm5='', $prm6='', $prm7='', $prm8='', $prm9='', $prm10='')

    local $aParms[10][2]

    for $1 = 0 to 9
        if stringinstr(eval('prm' & $1),'=') then
            $aParms[$1][0] = stringregexpreplace(eval('prm' & $1),'(.+)=.+','$1')
            $aParms[$1][1] = stringregexpreplace(eval('prm' & $1),'.+=(.+)','$1')
        endif
    Next

    return $aParms

endfunc

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

An array with a single data type is a close as you will get.


_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

#9 ·  Posted (edited)

There's always boolean flags: one 32-bit integer is equivalent to 32 True or False parameters. You can also use globals (or static values sometimes): which can be accessed from outside the function.

One boolean flag associated with a local array of instructions? :think:

Edited by czardas

Share this post


Link to post
Share on other sites

Yeah bit flags are great.


_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

Variadic. What's up that?

Variable argument? maybe these are what you looking while AutoIt3 still don't support it!

.

; variadic trick

$a = array('damn!', 45, ptr(80), array(3, 2))
$b = array('yeah...')
array_push($a, 'k', 1, 6.7)
array_push($a, $b)
array_push($a, 5, 6, 7, 'you!')

print_r($a)

; php.array.au3 by me (prazetto) that also posted in another thread

#include-once

; array ( mixed $arg0, mixed $arg1, mixed $arg2 .. mixed $argN ) : array
; array_push ( $array, mixed $arg0, mixed $arg1, mixed $arg2 .. mixed $argN ) : Number
; array_pop ( $array ) : Number
; array_delete ( $array, $element )                       this func support 2D Array
; array_search ( mixed $needle , array $haystack , opt bool $strict = 0) : Number
; ~ array_search ( array $haystack , mixed $needle , opt bool $strict = 0) : Number
; array_exist : alias of in_array()
; array_rand ( array $input , opt int $num_req = 1  ) : mixed
; array_reverse ( array $array , opt bool $preserve_keys = false ): array
; array_sum ( array $array ) : number
; array_shift ( array &$array ) : mixed
; array_unshift ( array &$array , mixed $var [, mixed $... ] ) : int
; array_unique ( array $array [, int $sort_flags = SORT_STRING ] ) : array
; in_array ( mixed $needle , array $haystack , opt bool $strict = 0 ) :  bool


Func array($a=0,$b=0,$c=0,$d=0,$e=0,$f=0,$g=0,$h=0,$i=0,$j=0,$k=0,$l=0,$m=0,$n=0,$o=0,$p=0,$q=0,$r=0,$s=0,$t=0,$u=0,$v=0,$w=0,$x=0,$y=0,$z=0)
    Local $chr = 97, $agc = @NumParams
    Local $arr[$agc]
    For $lop = 1 To $agc
        $arr[$lop - 1] = Eval(Chr($chr))
        $chr += 1
    Next
    Return $arr
EndFunc

Func array_push(ByRef $arr, $var, $a=0,$b=0,$c=0,$d=0,$e=0,$f=0,$g=0,$h=0,$i=0,$j=0,$k=0,$l=0,$m=0,$n=0,$o=0,$p=0,$q=0,$r=0,$s=0,$t=0,$u=0,$v=0,$w=0,$x=0,$y=0,$z=0)
   Local $chr = 97, $agc = @NumParams - 1
   If Not IsArray($arr) Then
      Local $avb[$agc]
      $arr = $avb
      $arr[0] = $var
      For $lop = 1 To $agc -1
         $arr[$lop] = Eval(Chr($chr))
         $chr += 1
         Next
      Return $agc
      Else
      Local $ubn = UBound($arr)
      ReDim $arr[$ubn + $agc]
      $arr[$ubn] = $var
      For $lop = 1 To $agc -1
         $arr[$ubn + $lop] = Eval(Chr($chr))
         $chr += 1
         Next
      Return $ubn + $agc
      EndIf
EndFunc

Func array_pop(ByRef $arr)
   Local $ret, $ubn = UBound($arr) - 1
   If Not IsArray($arr) Then Return SetError(1, 0, 0)
   $ret = $arr[$ubn]
   ; array in array destroy
   If IsArray($arr[$ubn]) Then $arr[$ubn] = 0
   If $ubn = 0 Then
      Local $und
      $arr = $und
      Return SetError(0, 1, $ret)
      EndIf
   ReDim $arr[$ubn]
   Return $ret
EndFunc

Func array_delete(ByRef $arr, $elm)
   If Not IsArray($arr) Then Return SetError(1, 0, 0)
   Local $ubn = UBound($arr, 1) - 1

   ; Bounds check
   If $elm < 0 Then $elm = 0
   If $elm > $ubn Then $elm = $ubn

   ; Move items after $elm up by 1
   Switch UBound($arr, 0)
      Case 1
         ; array in array destroy
         If IsArray($arr[$elm]) Then $arr[$elm] = 0
         For $i = $elm To $ubn - 1
            $arr[$i] = $arr[$i + 1]
            Next
         ; return undefined variable default
         If $ubn = 0 Then
            Local $und
            $arr = $und
            Return 0
            EndIf
         ReDim $arr[$ubn]
      Case 2
         Local $max = UBound($arr, 2) - 1
         ; array in 2D array destroy
         For $j = 0 To $max
            If IsArray($arr[$elm][$j]) Then $arr[$elm][$j] = 0
            Next
         For $i = $elm To $ubn - 1
            For $j = 0 To $max
               $arr[$i][$j] = $arr[$i + 1][$j]
               Next
            Next
         ; return undefined variable default
         If $ubn = 0 Then
            Local $und
            $arr = $und
            Return 0
            EndIf
         ReDim $arr[$ubn][$max + 1]
      Case Else
         Return SetError(1, 1, 0)
   EndSwitch
   Return $ubn
EndFunc

Func in_array($ndl, ByRef $arr, $stc = 0)
   If array_search($ndl, $arr, $stc) = -1 Then
      Return 0
      Else
      Return 1
      EndIf
EndFunc

Func array_exist($ndl, ByRef $arr, $stc = 0)
   If array_search($ndl, $arr, $stc) = -1 Then
      Return 0
      Else
      Return 1
      EndIf
EndFunc

;Func array_search(ByRef Const $ndl, ByRef Const $arr, $stc = 0)
Func array_search($ndl, $arr, $stc = 0)
   Local $agc = UBound($arr)
   ; overload to allow param type swapping with keep access variable as ByRef
   If IsArray($ndl) Then Return array_search($arr, $ndl, $stc)
   If $agc = 0 Then Return -1
   $agc -= 1
   Switch VarGetType($ndl)
      Case 'String'
         For $lop = 0 To $agc
            If IsString($arr[$lop]) Then
               If StringCompare($arr[$lop], $ndl, $stc) == 0 Then Return $lop
               EndIf
            Next
      Case 'Bool'
            If $stc Then
               For $lop = 0 To $agc
                  If IsBool($arr[$lop]) Then
                     If $arr[$lop] = $ndl Then Return $lop
                     EndIf
                  Next
               Else
               For $lop = 0 To $agc
                  Switch VarGetType($arr[$lop])
                     Case 'Int32', 'Int64', 'ptr'
                        If $ndl = True Then
                           If $arr[$lop] <> 0 Then Return $lop
                           Else
                           If $arr[$lop] = 0 Then Return $lop
                           EndIf
                     Case Else
                        If $arr[$lop] = $ndl Then Return $lop
                     EndSwitch
                  Next
               EndIf
      Case 'Int32'
            If $stc Then
               For $lop = 0 To $agc
                  If VarGetType($arr[$lop]) = 'Int32' Then
                     If $arr[$lop] = $ndl Then Return $lop
                     EndIf
                  Next
               Else
               For $lop = 0 To $agc
                     If $arr[$lop] = $ndl Then Return $lop
                  Next
               EndIf
      Case 'Int64'
            If $stc Then
               For $lop = 0 To $agc
                  If VarGetType($arr[$lop]) = 'Int64' Then
                     If $arr[$lop] = $ndl Then Return $lop
                     EndIf
                  Next
               Else
               For $lop = 0 To $agc
                  If $arr[$lop] = $ndl Then Return $lop
                  Next
               EndIf
      Case 'Ptr' ; HWnd also trapped here
            If $stc Then
               For $lop = 0 To $agc
                  If IsPtr($arr[$lop]) Then
                     If $arr[$lop] = $ndl Then Return $lop
                     EndIf
                  Next
               Else
               For $lop = 0 To $agc
                  If $arr[$lop] = $ndl Then Return $lop
                  Next
               EndIf
      EndSwitch
   Return -1
EndFunc

Func array_search_instring(ByRef Const $ndl, ByRef Const $arr, $stc = 0)
   Local $agc = UBound($arr)
   ; overload to allow param type swapping with keep access variable as ByRef
   If IsArray($ndl) Then Return array_search_instring($arr, $ndl, $stc)
   If $agc = 0 Then Return -1
   $agc -= 1
   Switch VarGetType($ndl)
      Case 'String'
         For $lop = 0 To $agc
            If IsString($arr[$lop]) Then
               If StringInStr($arr[$lop], $ndl, $stc) <> 0 Then Return $lop
               EndIf
            Next
      Case 'Bool'
            If $stc Then
               For $lop = 0 To $agc
                  If IsBool($arr[$lop]) Then
                     If $arr[$lop] = $ndl Then Return $lop
                     EndIf
                  Next
               Else
               For $lop = 0 To $agc
                  Switch VarGetType($arr[$lop])
                     Case 'Int32', 'Int64', 'ptr'
                        If $ndl = True Then
                           If $arr[$lop] <> 0 Then Return $lop
                           Else
                           If $arr[$lop] = 0 Then Return $lop
                           EndIf
                     Case Else
                        If $arr[$lop] = $ndl Then Return $lop
                     EndSwitch
                  Next
               EndIf
      Case 'Int32'
            If $stc Then
               For $lop = 0 To $agc
                  If VarGetType($arr[$lop]) = 'Int32' Then
                     If $arr[$lop] = $ndl Then Return $lop
                     EndIf
                  Next
               Else
               For $lop = 0 To $agc
                     If $arr[$lop] = $ndl Then Return $lop
                  Next
               EndIf
      Case 'Int64'
            If $stc Then
               For $lop = 0 To $agc
                  If VarGetType($arr[$lop]) = 'Int64' Then
                     If $arr[$lop] = $ndl Then Return $lop
                     EndIf
                  Next
               Else
               For $lop = 0 To $agc
                  If $arr[$lop] = $ndl Then Return $lop
                  Next
               EndIf
      Case 'Ptr' ; HWnd also trapped here
            If $stc Then
               For $lop = 0 To $agc
                  If IsPtr($arr[$lop]) Then
                     If $arr[$lop] = $ndl Then Return $lop
                     EndIf
                  Next
               Else
               For $lop = 0 To $agc
                  If $arr[$lop] = $ndl Then Return $lop
                  Next
               EndIf
      EndSwitch
   Return -1
EndFunc

Func array_search_or($ndl, $arr, $nd2, $stc = 0)
   Local $agc = UBound($arr)
   ; overload to allow param type swapping with keep access variable as ByRef
   If IsArray($ndl) Then Return array_search_or($arr, $ndl, $nd2, $stc)
   If $agc = 0 Then Return -1
   $agc -= 1
   Switch VarGetType($ndl)
      Case 'String'
         For $lop = 0 To $agc
            If IsString($arr[$lop]) Then
               If (StringCompare($arr[$lop], $ndl, $stc) == 0) Or _
                  (StringCompare($arr[$lop], $nd2, $stc) == 0) Then Return $lop
               EndIf
            Next
      Case 'Bool'
            If $stc Then
               For $lop = 0 To $agc
                  If IsBool($arr[$lop]) Then
                     If $arr[$lop] = $ndl Then Return $lop
                     EndIf
                  Next
               Else
               For $lop = 0 To $agc
                  Switch VarGetType($arr[$lop])
                     Case 'Int32', 'Int64', 'ptr'
                        If $ndl = True Then
                           If $arr[$lop] <> 0 Then Return $lop
                           Else
                           If $arr[$lop] = 0 Then Return $lop
                           EndIf
                     Case Else
                        If $arr[$lop] = $ndl Then Return $lop
                     EndSwitch
                  Next
               EndIf
      Case 'Int32'
            If $stc Then
               For $lop = 0 To $agc
                  If VarGetType($arr[$lop]) = 'Int32' Then
                     If $arr[$lop] = $ndl Then Return $lop
                     EndIf
                  Next
               Else
               For $lop = 0 To $agc
                     If $arr[$lop] = $ndl Then Return $lop
                  Next
               EndIf
      Case 'Int64'
            If $stc Then
               For $lop = 0 To $agc
                  If VarGetType($arr[$lop]) = 'Int64' Then
                     If $arr[$lop] = $ndl Then Return $lop
                     EndIf
                  Next
               Else
               For $lop = 0 To $agc
                  If $arr[$lop] = $ndl Then Return $lop
                  Next
               EndIf
      Case 'Ptr' ; HWnd also trapped here
            If $stc Then
               For $lop = 0 To $agc
                  If IsPtr($arr[$lop]) Then
                     If $arr[$lop] = $ndl Then Return $lop
                     EndIf
                  Next
               Else
               For $lop = 0 To $agc
                  If $arr[$lop] = $ndl Then Return $lop
                  Next
               EndIf
      EndSwitch
   Return -1
EndFunc


; @err 1  @ext 1 = param 1 not array or array zero
;              2 = param 2 not an number
;              3 = param 2 are invalid and is negative number
;              4 = param 2 requested exceed max value of array param 1
Func array_rand(ByRef $arr, $req = 1)
   Local $und, $rnd, $ubn = UBound($arr)
   If $ubn = 0 Then Return SetError(1, 1, $und)
   $ubn -= 1
   Switch $req
      Case 0
         Return $und
      Case 1
         $rnd = Random(0, $ubn, 1)
         Return $arr[$rnd]
      Case Else
         If Not IsNumber($req) Then Return SetError(1, 2, $und)
         If $req < 0 Then Return SetError(1, 3, $und)
         If $req > $ubn Then Return SetError(1, 4, $und)
         Local $avb[$req]
         $req -= 1
         For $lop = 0 To $req
            $avb[$lop] = $arr[Random(0, $ubn, 1)]
            Next
         Return $avb
      EndSwitch
   Return $und
EndFunc

Func array_reverse(ByRef $arr)
   Local $und, $ubn = UBound($arr)
   If $ubn = 0 Then Return SetError(1, 0, $und)
   Local $avb[$ubn], $cnt
   $ubn -= 1
   $cnt = $ubn
   For $lop = 0 To $ubn
      $avb[$cnt] = $arr[$lop]
      $cnt -= 1
      Next
   Return $avb
EndFunc

Func array_sum(ByRef $arr)
   Local $ret, $ubn = UBound($arr)
   If $ubn = 0 Then Return SetError(1, 0, 0)
   $ubn -= 1
   If IsNumber($arr[0]) Or IsPtr($arr[0]) Then
      For $lop = 0 To $ubn
         $ret += $arr[$lop]
         Next
      EndIf
   If IsString($arr[0]) Then
      For $lop = 0 To $ubn
         $ret &= $arr[$lop]
         Next
      EndIf
   Return $ret
EndFunc

Func array_shift(ByRef $arr)
   Local $ret, $ubn = UBound($arr)
   If $ubn = 0 Then Return SetError(1, 0, $ret)
   $ret = $arr[0]
   array_delete($arr, 0)
   Return $ret
EndFunc

Func array_unshift(ByRef $arr, $var, $a=0,$b=0,$c=0,$d=0,$e=0,$f=0,$g=0,$h=0,$i=0,$j=0,$k=0,$l=0,$m=0,$n=0,$o=0,$p=0,$q=0,$r=0,$s=0,$t=0,$u=0,$v=0,$w=0,$x=0,$y=0,$z=0)
   Local $chr = 97, $agc = @NumParams - 1
   If Not IsArray($arr) Then
      Local $avb[$agc]
      $arr = $avb
      $arr[0] = $var
      For $lop = 1 To $agc -1
         $arr[$lop] = Eval(Chr($chr))
         $chr += 1
         Next
      Return $agc
      Else
      Local $ubn, $add, $cnt
      $ubn = UBound($arr)
      $add = $ubn + $agc
      ReDim $arr[$add]

      For $lop = $add - 1 To 0 Step -1
         $cnt = $lop - $agc
         $arr[$lop] = $arr[$cnt]
         ; array in array destroy
         If IsArray($arr[$cnt]) Then $arr[$cnt] = 0
         If ($lop) = $agc Then ExitLoop
         Next

      $arr[0] = $var

      $agc -= 1
      For $lop = 1 To $agc
         $arr[$lop] = Eval(Chr($chr))
         $chr += 1
         Next

      Return $add
      EndIf
EndFunc

Func array_unique(ByRef $arr, $sfg = 0)
   Local $ret, $ubn = UBound($arr)
   If $ubn = 0 Then Return SetError(1, 0, $ret)
   array_push($ret, $arr[0])
   For $lop = 1 To $ubn-1
      If array_search($ret, $arr[$lop], 1) = -1 Then array_push($ret, $arr[$lop])
      Next
   Return $ret
EndFunc

Func array_valid(ByRef $arr, $i = 0)
   Switch @NumParams
      Case 1
         Return IsArray($arr)
      Case 2
         Return IsArray($arr[$i])
      EndSwitch
EndFunc

Func array_count(ByRef $arr, $i = 0)
   Switch @NumParams
      Case 1
         Return UBound($arr)
      Case 2
         If UBound($arr) < $i + 1 Then Return 0
         Return UBound($arr[$i])
      EndSwitch
EndFunc

Func array_value(ByRef $arr, $i, $j = 0, $k = 0)
   Switch @NumParams
      Case 2
         If Not IsArray($arr) Or UBound($arr) = 0 Then Return SetError(1, 0, 0)
         If $i >= UBound($arr) Then Return SetError(1, 0, 0)
         Return $arr[$i]
      Case 3
         Return array_value($arr[$i], $j)
      Case 4
         Return array_value($arr[$i], $j, $k)
      EndSwitch
EndFunc

;Func array_change(ByRef $arr, ByRef $_, $i, $j = 0, $k = 0)
Func array_change(ByRef $arr, $_, $i, $j = 0, $k = 0)
   Switch @NumParams-1
      Case 2
         If Not IsArray($arr) Or UBound($arr) = 0 Then Return SetError(1, 0, 0)
         If $i >= UBound($arr) Then Return SetError(1, 0, 0)
         $arr[$i] = $_
      Case 3
         array_change($arr[$i], $_, $j)
      Case 4
         array_change($arr[$i], $_, $j, $k)
      EndSwitch
EndFunc



Func array_count2(ByRef $arr, $i, $j = 0, $k = 0)
   Switch @NumParams
      Case 2
         If Not IsArray($arr) Or UBound($arr) = 0 Then Return SetError(1, 0, 0)
         If $i >= UBound($arr) Then Return SetError(1, 0, 0)
         Return UBound($arr)
      Case 3
         Return array_count2($arr[$i], $j)
      Case 4
         Return array_count2($arr[$i], $j, $k)
      EndSwitch
EndFunc



Func array_value2(ByRef $arr, $i, $j)
   Return array_value($arr[$i], $j)
EndFunc

Func array_search2(ByRef $arr, $i, ByRef $needle)
   Return array_search($arr[$i], $needle)
EndFunc

Func array_push2(ByRef $arr, $i, $var)
   If Not IsArray($arr) Then
      Local $va_arr[] = []
      $arr = $va_arr
      EndIf
   If not IsArray($arr) Then ;newlinecode
      Local $va_arr[] = []
      $arr = $va_arr
      EndIf
   If UBound($arr) < $i + 1 Then ReDim $arr[$i + 1]
   Return array_push($arr[$i], $var)
EndFunc


Func print_r($arr, $padspace='', $recursive=-1)
   Local $space, $n

   $space &= $padspace

   $n = UBound($arr)

   If IsArray($arr) Then
      If $recursive <> -1 Then
         ConsoleWrite($space & '[' & $recursive & ']  ' & 'Array [' & $n & ']' & @CR)
         Else
         ConsoleWrite($space & 'Array [' & $n & ']' & @CR)
         EndIf

      $space &= '   '
      EndIf

  $n -= 1
   For $loop = 0 To $n

      Switch VarGetType($arr[$loop])
         Case 'Array'
            print_r($arr[$loop], $space, $loop)
         Case 'Object'
            ConsoleWrite($space & '[' & $loop & ']  ' & '[object]' & @CR)
         Case 'String'
            If StringInStr($arr[$loop], @CR) Or StringInStr($arr[$loop], @LF) Then
               Local $str = $arr[$loop]
               $str = StringReplace($str, @CRLF, @CR)
               $str = StringReplace($str, @LF, @CR)
               $str = StringReplace($str, @CR, @CR & $space & '     ')
               ConsoleWrite($space & '[' & $loop & ']  ' & $str & @CR)
               Else
               ConsoleWrite($space & '[' & $loop & ']  ' & $arr[$loop] & @CR)
               EndIf
         Case 'Int32', 'Int64'
               ConsoleWrite($space & '[' & $loop & ']  ' & $arr[$loop] & @CR)
         Case 'ptr'
               ConsoleWrite($space & '[' & $loop & ']  ' & $arr[$loop] & @CR)
         Case 'Bool'
               ConsoleWrite($space & '[' & $loop & ']  ' & $arr[$loop] & @CR)
         Case 'Double'
               ConsoleWrite($space & '[' & $loop & ']  ' & $arr[$loop] & @CR)
         Case 'Keyword'
            Switch IsKeyword($arr[$loop])
               Case 1 ; Default
               ConsoleWrite($space & '[' & $loop & ']  ' & 'Default : [keyword]' & @CR)
               Case 2 ; Null
               ConsoleWrite($space & '[' & $loop & ']  ' & 'Null : [keyword]' & @CR)
               EndSwitch
         Case 'UserFunction', 'Function'
               ConsoleWrite($space & '[' & $loop & ']  ' & StringLower(FuncName($arr[$loop])) & ' --> {function}' & @CR)
         Case Else
            ConsoleWrite($space & '[' & $loop & ']  ' & $arr[$loop] & @CR)
         EndSwitch
      Next
EndFunc

Func array_setimax_value()

EndFunc


Func high(ByRef $arr)
   Local $ret
   $ret = UBound($arr)
   If $ret > 0 Then
      Return $ret -1
      Else
      Return -1
      EndIf
EndFunc

Func array_value_high(ByRef $arr, $stage=0)
   Local $nil, $r, $n = UBound($arr)
   If Not IsArray($arr) Or $n = 0 then Return SetError(1, 0, $nil)
   $n -= 1
   $r = $n + $stage
   If $r < 0 then Return SetError(1, 1, $nil)
   If $n < $r then Return SetError(1, 2, $nil)
   Return $arr[$r]
EndFunc

Func array_value_high_add(ByRef $arr, $val, $stage=0)
   Local $nil, $r, $n = UBound($arr)
   If Not IsArray($arr) Or $n = 0 then Return SetError(1, 0, 0)
   $n -= 1
   $r = $n + $stage
   If $r < 0 then Return SetError(1, 1, 0)
   If $n < $r then Return SetError(1, 2, 0)
   $arr[$r] += $val
EndFunc

.

Output:

.

Array [12]
   [0]  damn!
   [1]  45
   [2]  0x00000050
   [3]  Array [2]
      [0]  3
      [1]  2
   [4]  k
   [5]  1
   [6]  6.7
   [7]  Array [1]
      [0]  yeah...
   [8]  5
   [9]  6
   [10]  7
   [11]  you!

# Button. Progressbar - Graphical AutoIt3 Control (UDF) # GTK on AutoIt3 - GTK+ Framework | Widgets

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