Jump to content
Sign in to follow this  
xola

Creating an Array

Recommended Posts

xola

Hello,

I'm pretty new to AutoIt, but not new to programming at all. I usually was programming with C-like syntax, so sometimes AutoIt is confusing me.

But now i need you help. I'm trying to build up an array:

$sourceFilesArray = [[$filename, $filepath, $lastInsertedItem]]

This line is in a Func.

This code results in a "syntax error". While in the gorgeous AutoIt Help there is an article where this is no problem (Help page for _ArrayDisplay, at the very bottom):

Local $avArray[2][5] = [["JPM", "Holger", "Jon", "Larry", "Jeremy"],["Valik", "Cyberslug", "Nutster", "JdeB", "Tylo"]]
_ArrayDisplay($avArray, "$avArray as a 2D array")

When I add "Local" to my piece of code, there come even more errors.

What am I doing wrong? Just want to make an array...

Greets

xola

PS: When I want to add more dimensions ("lines") to the array, does something like "$array += " work?

Share this post


Link to post
Share on other sites
JLogan3o13

Hi, xola, welcome to the forum. Try something like this...

#include <array.au3>
$filename = "Bob"
$filepath = "C:"
$lastInsertedItem = "Boo"
Local $sourceFilesArray[3] = [$filename, $filepath, $lastInsertedItem]
_ArrayDisplay($sourceFilesArray)

√-1 2^3 ∑ π, and it was delicious!

Share this post


Link to post
Share on other sites
Blue_Drache

Your syntax for the first line is written wrong.

Dim $sourceFilesArray[$filename, $filepath, $lastInsertedItem]

creates your array.

Or you could use Local instead of Dim, since it's in a function.


Lofting the cyberwinds on teknoleather wings, I am...The Blue Drache

Share this post


Link to post
Share on other sites
Melba23

xola,

Welcome to the AutoIt forum. :bye:

You need to declare the array, so you should have either Global or Local before the name. What "more errors" do you get when you used Local? Could you post all your code so we could see what is going on? :oops:

You cannot change the number of "dimensions" - this refers to the number of [ ] pairs - but you can change the number of elements within a dimension - "lines" as you put it - by using ReDim. :doh:

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
JLogan3o13

Three answers within 20 seconds of each other. what OTHER forum would you find that kind of help on?? :oops:


√-1 2^3 ∑ π, and it was delicious!

Share this post


Link to post
Share on other sites
BrewManNH

You have to define the dimensions of the array before you can add things into it

Local $sourceFilesArray[3] = [[$filename, $filepath, $lastInsertedItem]] ; Use Global instead of Local if this isn't inside a Function

To add rows to an array, you can either use _ArrayAdd, or ReDim to redimension the array.

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

Share this post


Link to post
Share on other sites
BrewManNH

Or you could use Local instead of Dim, since it's in a function.

Don't use Dim for anything, regardless of where in a script it is. Dim is deprecated in its use these day, define it explicitly as either Global or Local and avoid Dim completely.

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

Share this post


Link to post
Share on other sites
guinness

Your syntax for the first line is written wrong.

Dim $sourceFilesArray[$filename, $filepath, $lastInsertedItem]

creates your array.

Or you could use Local instead of Dim, since it's in a function.

This is incorrect as well.

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

Share this post


Link to post
Share on other sites
xola

Thank you for your help so far. I'm impressed about the number of replies in this short time.

I now saw that I've not realised, that the number in the brackets means "number of columns".

So, I dont want to Redim my array every time the Func is triggered. _ArrayAdd seems to do this by its own.

But it seems difficult to give _ArrayAdd more than one column:

Local $triple[3] = [$filename, $filepath, $lastInsertedItem]
   _ArrayAdd($sourceFilesArray, $triple)
   _ArrayDisplay($sourceFilesArray, @error)

_ArrayDisplay tells me, that there is one column with no content.

Unfortunately, something like this does not work:

_ArrayAdd($sourceFilesArray, [$filename, $filepath, $lastInsertedItem])
   _ArrayDisplay($sourceFilesArray, @error)

And i noticed, that there are two "lines" in the Array, even if I just added one.

I initialised the Array like this at the very top of my script with

Global $sourceFilesArray[1]

Just for your information, so my purpose is clearer to you:

I make a small gui for a specific group of people, to convert videos from their cam to a format their dvd-player accepts. These people work in a kinder garden. It's their job to study the children and to tell the parents about their learning processes. Now they want to film the children to show the parents. Unfortunately the video format from the cam is not supported by the dvd-player.

Since they all are not very good in computer and video stuff, i make it easier for them by creating this little program.

As they told me, they want to convert 1 to 5 videos at once.

So the convertion is done via ffmpeg - easy stuff. Already figured out the command line and tried it on the dvd-player. No problem here.

So i've got a GUI with a button with a FileOpenDialog to choose input videos. Every video ist loaded in a GUICtrlListView ($listSourceFiles) and additionally in an array ($sourceFilesArray).

Maybe now what I do is clearer to you.

Edited by xola

Share this post


Link to post
Share on other sites
Melba23

xola,

I am beginning to get an idea of what you are doing - and what you are trying will not work. Do your arrays look like this:

$sourceFilesArray:

Name1      Path1     Last_Item1
Name2      Path2     Last_Item2
Name3      Path3     Last_Item3
Name4      Path4     Last_Item4

$triple:

Newname    Newpath   NewLast_Item]

and you want:

Name1      Path1     Last_Item1
Name2      Path2     Last_Item2
Name3      Path3     Last_Item3
Name4      Path4     Last_Item4
Name5      Path5     Last_Item5

Did I guess correctly? :oops:

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
xola

No, youre not entirely right.

I want to have every video stored in my array like this:

- filename

- filepath

- ID of corresponding GUICtrlListViewItem

$triple should just represent the line to insert into my array. This variable was just created for getting the columns in my array. But this does not work so far.

Am i assuming right, that _ArrayAdd just works with one-dimensional arrays?

Share this post


Link to post
Share on other sites
Melba23

xola,

You are correct - and you need a 2D array to store your data. :bye:

So you could declare your original array like this - I have set a count in the [0][0] element:

Global $sourceFilesArray[1][3] = [[0]]

Then you can add "lines" to it like this:

;Increase the count
$sourceFilesArray[0][0] += 1
$iCount = $sourceFilesArray[0][0]
; Now increase the size of the array
ReDim $sourceFilesArray[$iCount + 1][3]
; Now add the new data
$sourceFilesArray[$iCount][0] = $filename
$sourceFilesArray[$iCount][1] = $filepath
$sourceFilesArray[$iCount][2] = $lastInsertedItem

Is that clear? :oops:

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
BrewManNH

This is a modified version of _ArrayAdd that works with 2D arrays, it will insert a string into the array and the sub-elements are divided by the delimiter character (default character is "|") so if you had a string $string = "1|2|3" it will add that to a 2D array that has 3 "columns", if the string doesn't match the dimensions of the array it will cause an error.

; #FUNCTION# ====================================================================================================================
; Name...........: _ArrayAdd
; Description ...: Adds a specified value at the end of an existing array. Also will add a delimited string to a 2D array.
; Syntax.........: _ArrayAdd(ByRef $avArray, $vValue)
; Parameters ....: $avArray - Array to modify
;                  $vValue  - Value to add
; Return values .: Success - Index of last added item
;                  Failure - -1, sets @error
;                  |1 - $avArray is not an array
;                  |2 - $avArray is not a 1 or 2 dimensional array
;                  |3 - $vValue has too many subitems
; Author ........: Jos van der Zande <jdeb at autoitscript dot com>
; Modified.......: Ultima - code cleanup, BrewManNH - 2D array support
; Remarks .......:
; Related .......: _ArrayConcatenate, _ArrayDelete, _ArrayInsert, _ArrayPop, _ArrayPush
; Link ..........:
; Example .......: Yes
; ===============================================================================================================================
Func _ArrayAdd(ByRef $avArray, $vValue, $sSeparator = "|")
    Local $iUBound
    Local $iSubMax
    If Not IsArray($avArray) Then Return SetError(1, 0, -1)
    If UBound($avArray, 0) > 2 Then Return SetError(2, 0, -1)
    Local $avValue = StringSplit($vValue, $sSeparator)
    If Not @error Then
        $iSubMax = $avValue[0]
        If $iSubMax <> UBound($avArray, 2) Then Return SetError(3, 0, 0)
    EndIf
    If UBound($avArray, 0) = 1 Then
        $iUBound = UBound($avArray)
        ReDim $avArray[$iUBound + 1]
        $avArray[$iUBound] = $vValue
        Return $iUBound
    Else
        $iUBound = UBound($avArray)
        ReDim $avArray[$iUBound + 1][$iSubMax]
        For $i = 0 To $iSubMax - 1
            $avArray[$iUBound][$i] = $avValue[$i + 1]
        Next
        Return $iUBound
    EndIf
EndFunc   ;==>_ArrayAdd

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

Share this post


Link to post
Share on other sites
xola

Hey Guys,

thank you so much for your support. I'm nearly done with my little program.

Only one thing left to ask.

_ArrayDelete has the bad side effect, that it deletes the whole Array instead of deleting the last array element. I want to have my "empty" array left. How can that be done?

Greets

xola

Share this post


Link to post
Share on other sites
Blue_Drache

Recreate the array after it's been destroyed.

and if it's in a function, declared with "Local" ... it'll be destroyed anyway and inaccessible once the function returns.


Lofting the cyberwinds on teknoleather wings, I am...The Blue Drache

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  

×