Jump to content

Arrays 101: All you need to know about them!


TheDcoder
 Share

Recommended Posts

On 10/17/2015 at 9:31 AM, TheDcoder said:

Best practice of using "Enum"

I adopted this technique for most of my GUI scripts.  Extremely useful organizationally (for me).  It's nice to see someone wrote up a tut/illustration on it.

Link to comment
Share on other sites

I think AutoIt lacks a dynamic array. Am i right ? 

Spoiler

My Contributions

Glance GUI Library - A gui library based on Windows api functions. Written in Nim programming language.

UDF Link Viewer   --- A tool to visit the links of some most important UDFs 

 Includer_2  ----- A tool to type the #include statement automatically 

 Digits To Date  ----- date from 3 integer values

PrintList ----- prints arrays into console for testing.

 Alert  ------ An alternative for MsgBox 

 MousePosition ------- A simple tooltip display of mouse position

GRM Helper -------- A littile tool to help writing code with GUIRegisterMsg function

Access_UDF  -------- An UDF for working with access database files. (.*accdb only)

 

Link to comment
Share on other sites

@kcvinu If you are looking for resizablility, you can resize them using ReDim but it is not very efficient... I am not very experienced with other languages so I cannot comment here.

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

@TheDcoder ,

I have never used ReDim in any of my scripts.  I like the table in Lua. AutoIt needs one like it. 

Spoiler

My Contributions

Glance GUI Library - A gui library based on Windows api functions. Written in Nim programming language.

UDF Link Viewer   --- A tool to visit the links of some most important UDFs 

 Includer_2  ----- A tool to type the #include statement automatically 

 Digits To Date  ----- date from 3 integer values

PrintList ----- prints arrays into console for testing.

 Alert  ------ An alternative for MsgBox 

 MousePosition ------- A simple tooltip display of mouse position

GRM Helper -------- A littile tool to help writing code with GUIRegisterMsg function

Access_UDF  -------- An UDF for working with access database files. (.*accdb only)

 

Link to comment
Share on other sites

  • 9 months later...
Quote

Best practice of using "Enum"

Thaks for the great info!

I always did this in ugly way like this:

; We will create an array which will contain details of the OS

Global Const $ARCH = 0, $TYPE = 1, $LANG = 2, $VERSION = 3, $BUILD = 4, $SERVICE_PACK = 5

Global $aOS[6] = [@OSArch, @OSType, @OSLang, @OSVersion, @OSBuild, @OSServicePack]

ConsoleWrite($LANG &' (L: '&@ScriptLineNumber&')'&@CRLF)
; Now, if you want to access anything related to the OS, you would do this:

ConsoleWrite(@CRLF)
ConsoleWrite('+>' & "Architecture: " & $aOS[$ARCH] & @CRLF)
ConsoleWrite('+>' & "Type: " & $aOS[$TYPE] & @CRLF)
ConsoleWrite('+>' & "Langauge: " & $aOS[$LANG] & @CRLF)
ConsoleWrite('+>' & "Version: " & $aOS[$VERSION] & @CRLF)
ConsoleWrite('+>' & "Build: " & $aOS[$BUILD] & @CRLF)
ConsoleWrite('+>' & "Service Pack: " & $aOS[$SERVICE_PACK] & @CRLF)
ConsoleWrite(@CRLF)

; Isn't it cool? XD

 

I'm going to adopt it a whole lot! 

Edited by Guest
Link to comment
Share on other sites

My pleasure @gil900 :).

To everyone: I am aware that there are some (serious) mistakes in the multi-dimensional array explanation, I am planning to publish this article as an ASCII Document with an open source licence at GitHub... I will try to correct all of the mistakes in that document. Not enough motivation for me to do it at the moment, if enough people are interested, I may get motivated :D

- TD

Edited by TheDcoder
Added link

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

Why ReDim is slower then _ArrayAdd ? This thread has a lot to offer. This is very helpful. Keep up the good work

Edited by Guest
Link to comment
Share on other sites

31 minutes ago, gil900 said:

Why ReDim is slower then _ArrayAdd ?

As far as I can see, _ArrayAdd uses ReDim to resize arrays so it theoretically impossible that ReDim is slower than _ArrayAdd. If possible, can you provide me with a proof of concept code where I can see this behaviour?

31 minutes ago, gil900 said:

This thread has a lot to offer. This is very helpful. Keep up the good work

Thanks for the kind words :D

Edited by TheDcoder
Appended the post

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

Just now, TheDcoder said:

As far as I can see, _ArrayAdd uses ReDim to resize arrays so it theoretically impossible that ReDim is slower than _ArrayAdd. If possible, can you provide me with a proof of concept code where I can see this behaviour?

It's like I thought.
I have not encountered such a case. I just probably misunderstood one of the comments here (not one of your comments)

Link to comment
Share on other sites

Storing the array size (0Based size ) in aArray[0][0] is faster then UBound($aArray)-1

I tested it. UBound($aArray)-1 is slower but here is the point - it is slower because of the "-1" after it. otherwise it is a bit faster.

Edited by Guest
Link to comment
Share on other sites

On 4/19/2017 at 2:35 PM, gil900 said:

Storing the array size (0Based size ) in aArray[0][0] is faster then UBound($aArray)-1

Do you have any code that proves this? How much slower is it?

If we're talking about microseconds, then the whole thing is moot because AutoIt isn't all that fast to begin with, so a milli/micro/nano second gain is a pointless exercise. The speed gain of UBound over storing the size in the first element comes in when you change what's in the array later in the script, with UBound, you never have to update the size in the first element, which takes a minuscule amount of time, but still more than none. 

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

  • 2 weeks later...

Found something very nice while I played with the syntax

#include <Array.au3>

Local $aArry[] = ['a','b','c']


_ArrayDisplay($aArry,'Array size: '&UBound($aArry)-1)

The size of the array is automatic.


I don't know if it is documented 

This is an excellent feature.

 

BrewManNH

I am talking about 2 microseconds..

 

; AUTOIT SPEED TESTER
; What is faster in autoIT3?
; ????????????????????????????????????????????????????????????????????????????
; What I know for sure as of version 3.2.4.9:
;
; 1. For/next loops are champions. Try not to use While/Wend or Do/Until
; 2. If $Val is faster than If $Val = 1 or $Val = TRUE.
; 3. If $Val = 1 is faster than $Val = TRUE
; 4. If Not $Val is faster than If $Val = 0 or $Val = FALSE.
; 5. If $Val = 0 is faster than If $Val = FALSE
; 6. < and > are faster than =, >= or >= (Wow!)
; 7. $i += 1 is faster than $i = $i + 1
; 8. If doing a lot of verifications on a single variable:
;    Switch is fastest, Select is second (but slow) and If is slowest.
; 9. If $Val is a string, If Not $Val is faster than If $Val = ""
;    If $Val is faster than If $Val <> ""
; 10. When doing binary operations, If $Val -128 > 0 is twice as fast
;     as If BitAnd($Val, 128).
;
; IMPORTANT: To get precise timings, TURN OFF ALL RUNNING PROGRAMS!
; To get compiled speeds ... compile and run :) (that was easy)
; Also note different CPU/Chipset/GPUs can affect results.
; It's been brought to my attention by chris95219 that GetTickCount() cannot be properly timed
; Also if you modify $i and $j (both loop counters) you will obviously get incorrect results!
; Other functions that can't be tested ... Exit (!) and Return (for obvious reasons)
; ????????????????????????????????????????????????????????????????????????????

Global $Chrono[801] ; Chronometer values
Global $Mess = "Timer values"&@CR ; String to contain MsgBox content.

; Declare all necessary variables for your test code here
$Val1 = 99
Global $aArray[100][2]
$aArray[0][0] = 99


; Actual timing loops
; ============================================================================
For $i = 1 To 800 ; 20 iterations of set
    $go = TimerInit() ; Start your engines!

    For $j = 1 To 9999 ; 9999 iterations of commands here
                       ; For complex test code, reduce value
                       ; although I suggest to test small bits instead.

        ; Insert your test code here
        ; Remove all commands to get a base reading (when you substract the base
        ; value from the values you get when you add a command, you will get the
        ; true time it took to process your command.
        ; IMPORTANT: Then ConsoleWrite("") serves as a dummy opreation to satisfy
        ;            the IF condition.


        ;(UBound($aArray)-1)  ; <------------------------------------------------------------------ TEST1: Uncomment only this


        ;($aArray[0][0])        ; <------------------------------------------------------------------ TEST2: Uncomment only this


    Next ; $j

    $Chrono[$i] = TimerDiff($go) ; Ok, how long did it take?
;~  $Mess &= "Pass "&$i&" = "&$Chrono[$i]&"ms"&@CR ; Jolt it down for the report

Next ; $i
; ============================================================================

_Report() ; ... err report it!







Exit

; ==== FUNCTIONS =============================================================
Func _Report()
    $Mess &= @CR ; Add an empty line
    $Mess &= "Min: "&_Minn()&"ms"&@CR ; Find minimum value and add it
    $Mess &= "Max: "&_Maxx()&"ms"&@CR ; Find maximum value and add it
    $Mess &= "Ave: "&_Ave()&"ms"&@CR ; Calculate median value and add it!
    MsgBox(48,"Results",$Mess) ; Show it to the user --> see how @CR works?
EndFunc

Func _Maxx() ; Find maximum value and return it
    Local $i, $Max ; Set local variables
    For $i = 1 To Ubound($Chrono) -1 ; Read all values in $Chrono, from 1 to end
        If $Chrono[$i] > $Max Then $Max = $Chrono[$i] ; If the current value is larger than the current max, it is the new max.
    Next
    Return $Max ; Send back the value
EndFunc

Func _Minn() ; Find minimum value and add it
    Local $i, $Min = $Chrono[1] ; Set local variables. Notice $Min which equals the first value in $Chrono
    For $i = 1 To Ubound($Chrono) -1 ; Read all values in $Chrono, from 1 to end
        If $Chrono[$i] < $Min Then $Min = $Chrono[$i] ; If the current value is lower than the current min, it is the new min.
    Next
    Return $Min ; Send back the value
EndFunc

Func _Ave() ; Find average value and return it
    Local $i, $Ave ; Set local variables
    For $i = 1 To Ubound($Chrono) -1 ; Read all values in $Chrono, from 1 to end
        $Ave += $Chrono[$i] ; Add up all the values
    Next
    Return $Ave / $i ; Send back the value, dividing total by # of numbers added together --> average
EndFunc

 

To test only the "UBound($aArray)-1", Uncomment only line 54. To test $aArray[0][0] Uncomment only line 57

Edited by Guest
Link to comment
Share on other sites

2 hours ago, gil900 said:

I am talking about 2 microseconds..

So, like I said before, a pointless exercise. Especially in a scripting program like AutoIt, where it's an interpreted language, microseconds can be gained or lost without ANY noticeable run differences.

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 think it depends on context: with an array that keeps changing size, inside or outside a loop (or a frequently called function), circumstances may suggest the best approach. Needlessly calling Ubound() for an array that never changes size is wasted cycles. Also, time critical responses sometimes require extreme measures. Both ways have their advantages and disadvantages. With Ubound(), you can just go to sleep and not worry about it.

Edited by czardas
Link to comment
Share on other sites

6 hours ago, gil900 said:

Local $aArry[] = ['a','b','c']

Note that you don't need the empty square brackets:

Local $aArry = ['a','b','c']

works as well. There is one more incentive to omit []: it's the syntax for declaring a Map in the beta (and most probably future releases).

#AutoIt3Wrapper_Version=B                        ;(B/P) Use Beta or Production for AutoIt3 and Aut2Eex. Default is P

Local $a[0]                 ; an empty array
ConsoleWrite(VarGetType($a) & @LF)

Local $aa = []              ; an empty array (preferrable syntax)
ConsoleWrite(VarGetType($aa) & @LF)

Local $b[] = [1, 2, 3]      ; an initialized array
ConsoleWrite(VarGetType($b) & @LF)

Local $bb = [1, 2, 3]       ; an initialized array (preferrable syntax)
ConsoleWrite(VarGetType($bb) & @LF)

Local $c[]                  ; a Map under beta (or syntax error under release)
ConsoleWrite(VarGetType($c) & @LF)

The similarity between declarations of $b and $c may lead to confusion when Maps become solid. Also by the time the beta has been out and since it doesn't show regressions I'd consider it release-class.

One more point: the size of an array is UBound($aArray), while UBound($aArray) - 1 which is the index of the last element.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

9 minutes ago, jchd said:

One more point: the size of an array is UBound($aArray), while UBound($aArray) - 1 which is the index of the last element.

Good point, I failed to notice that in @gil900's code

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

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

×
×
  • Create New...