Jump to content

Recommended Posts

I'm trying to pass a nested array to a function, such that the function alters the inner array.

I was surprised to find that this minimal reproducible example, despite its use of ByRef, seems to pass a copy of the inner array to the function:

#include <Array.au3>

; a boring old array
Local $aInnerArray[5] = [1, 2, 3, 4, 5]

; a one-element array containing a reference to the other array
Local $aOuterArray[1] = [$aInnerArray]

; intention: take a nested array and alter its inner array
; reality: the inner array seems to be getting copied
Func ChangeIt(ByRef $aOuter)
    Local $aInner = $aOuter[0]
    $aInner[2] = 0
EndFunc

; Expected: [1, 2, 3, 4, 5]
; Actual: [1, 2, 3, 4, 5] ✔
_ArrayDisplay($aInnerArray, 'Before')

; $aOuterArray passed by-ref, should receive reference to $aInnerArray
; Therefore should change $aInnerArray to [1, 2, 0, 4, 5]
ChangeIt($aOuterArray)

; Expected: [1, 2, 0, 4, 5]
; Actual: [1, 2, 3, 4, 5] ✘
_ArrayDisplay($aInnerArray, 'After')

I suspect that either:

  1. the copy is taking place in the first line of the function (I couldn't find a way to access the inner array without first assigning it to a variable though); or
  2. ByRef doesn't propagate into inner levels of the data structure being passed, which seems less likely to me.

Could someone please point me in the right direction to get this working as intended?

Update: the answer

; WRONG:
; a one-element array containing a reference to the other array
Local $aOuterArray[1] = [$aInnerArray]

The assumption I made about this code is wrong—it actually copies $aInnerArray into $aOuterArray, so there are now two unrelated $aInnerArray instances.  It is not possible to store arrays in other arrays by reference.

If it is necessary to refer to a mutable array in multiple places, consider holding it in a global variable.  Where a collection of mutable arrays needs to be accessed in multiple places (as in my case), consider storing them in a global array and referring to each sub-array by index (also known as the Registry pattern).

Edited by LxP
add answer in response to replies
Link to post
Share on other sites

I dont know if i got you right but

You havent even declared $aOuter ... and you don't wanna change or return it so why you need Byref?

 

if you just change

Func ChangeIt(ByRef $aOuter)
    Local $aInner = $aOuter[0]
    $aInner[2] = 0
EndFunc

with

Func ChangeIt(ByRef $aOuter)
    Local $aInner = $aOuter[0]
    $aInnerArray[2] = 0
EndFunc

it works like you expected... because You just change $aInnerArray[2].

But this would always happen even when you just write 

$aInnerArray[2] = 0

so what do you exactly want to do?

 

 

btw yes you can have 1 array which include multiple arrays 

Edited by Aelc

why do i get garbage when i buy garbage bags? <_<

Link to post
Share on other sites

If you want to change the inner array you can use ByRef to the inner array, example:

#include <Array.au3>

; a boring old array
Local $aInnerArray[5] = [1, 2, 3, 4, 5]

; a one-element array containing a reference to the other array
Local $aOuterArray[1] = [$aInnerArray]

; intention: take a nested array and alter its inner array
; reality: the inner array seems to be getting copied
Func ChangeIt(ByRef $aInner)
    $aInner[2] = 0
EndFunc

; Expected: [1, 2, 3, 4, 5]
; Actual: [1, 2, 3, 4, 5] ✔
_ArrayDisplay($aInnerArray)

; $aOuterArray passed by-ref, should receive reference to $aInnerArray
; Therefore should change $aInnerArray to [1, 2, 0, 4, 5]
ChangeIt($aOuterArray[0])

; Expected: [1, 2, 0, 4, 5]
; Actual: [1, 2, 3, 4, 5] ✘
_ArrayInnerDisplay($aOuterArray[0])

Func _ArrayInnerDisplay(ByRef $aInner)
    _ArrayDisplay($aInner)
EndFunc

 

Link to post
Share on other sites

Looks like an AutoIt bug to me. However, this works:

#include <Array.au3>

; a boring old array
Local $aInnerArray[5] = [1, 2, 3, 4, 5]

; outer array receives a COPY of $aInnerArray
Local $aOuterArray[1] = [$aInnerArray]
_ArrayDisplay($aOuterArray[0],"before")

ChangeIt($aOuterArray,0)
_ArrayDisplay($aOuterArray[0],"after")
_ArrayDisplay($aInnerArray,"$aInnerArray after (UNCHANGED)")

; intention: take a nested array and alter its inner array
Func ChangeIt(ByRef $aOuter, $index)
    _ChangeIt($aOuterArray[$index])
EndFunc

Func _ChangeIt(ByRef $aInner)
    $aInner[2] = 0
EndFunc

Also, your test is wrong, as $ainnerArray is itself never changed (a copy is stored in $aOuterArray). You should display $aAouterArray[0] afterwards.

Link to post
Share on other sites

The reason it doesn't change the original inner array is because you never actually modified it. You modify a copy of it, then do absolutely nothing with that modified array expecting it to magically know that the copy of the array is supposed to modify the original array without being told to. Here's how it SHOULD have been written. Also, there's no bug here, it's working exactly as expected.

#include <Array.au3>

; a boring old array
Local $aInnerArray[5] = [1, 2, 3, 4, 5]

; a one-element array containing a reference to the other array
Local $aOuterArray[1] = [$aInnerArray]

; intention: take a nested array and alter its inner array
; reality: the inner array seems to be getting copied
Func ChangeIt(ByRef $aOuter)
    Local $aInner = $aOuter[0]
    $aInner[2] = 0
    $aOuter[0] = $aInner ; <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Add this line to modify $aOuter
EndFunc

; Expected: [1, 2, 3, 4, 5]
; Actual: [1, 2, 3, 4, 5] ✔
_ArrayDisplay($aInnerArray)

; $aOuterArray passed by-ref, should receive reference to $aInnerArray
; Therefore should change $aInnerArray to [1, 2, 0, 4, 5]
ChangeIt($aOuterArray)

; Expected: [1, 2, 0, 4, 5]
; Actual: [1, 2, 3, 4, 5] ✘
_ArrayDisplay($aOuterArray[0]) ; <<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Change this line because you're showing the ORIGINAL array, and not the contents of the $aOuterArray nested 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 post
Share on other sites

Thanks to everyone for your replies so far.

Why isn't $aOuter declared?

This is intended—$aOuter is a parameter name, for referencing any desired other variable at runtime.

Why use ByRef if not altering the top-level data structure being passed in?

Because I want to change the contents of the inner array, and if I don't pass the top-level, outer array by reference using ByRef, then my changes to the inner array will definitely not persist after the function returns.

Why not have a ByRef parameter for the inner array directly?

Because this is not viable outside my minimal reproducible example given above.

The example given above is the minimal code needed to demonstrate my issue.  In my actual code I wouldn't have access to a variable name for the inner array.

Why am I expecting the outer array's copy of the inner array to ever be modified?

These replies hit the nail on the head (emphasis is mine):

  • “Also, your test is wrong, as $ainnerArray is itself never changed (a copy is stored in $aOuterArray).”
  • “The reason it doesn't change the original inner array is because you never actually modified it. You modify a copy of it, then do absolutely nothing with that modified array expecting it to magically know that the copy of the array is supposed to modify the original array without being told to.”

As a formally qualified software engineer I know better than to expect magic synchronisation of two distinct data structures in memory.  What I didn't know was that two distinct data structures existed.  Here's the source of my misunderstanding:

Local $aOuterArray[1] = [$aInnerArray]

In other languages, $aOuterArray would get a reference to $aInnerArray.  In AutoIt, $aOuterArray gets a copy of $aInnerArray.  In other words, I didn't know I had made two $aInnerArrays at this point.  With this knowledge I can move forwards.

My new question

Is there a way to store an inner array inside an outer array by reference, such that:

  • two different outer arrays can reference the same inner array; and
  • changes to the inner array are visible within both outer arrays?

If not, I'll resort to global arrays and store indexes instead.

Link to post
Share on other sites

AutoIt doesn't have a reference operator.

Yet, in limited cases (fixed sizes and datatypes) one might use structs to achieve something like that, (awful code emoji).

Local $tInner = DllStructCreate("int[5]")
For $i = 1 To 5
    DllStructSetData($tInner, 1, $i, $i)
Next

Local $tOuterA = DllStructCreate("wchar[12];ptr")
Local $tOuterB = DllStructCreate("wchar[12];ptr")

; init both structs with distinct strings but same inner array
DllStructSetData($tOuterA, 1, "String A")
DllStructSetData($tOuterA, 2, DllStructGetPtr($tInner))
Local $tInnerA = DllStructCreate("int[5]", DllStructGetData($tOuterA, 2))

DllStructSetData($tOuterB, 1, "String B")
DllStructSetData($tOuterB, 2, DllStructGetPtr($tInner))
Local $tInnerB = DllStructCreate("int[5]", DllStructGetData($tOuterB, 2))

$cw("Before:")
vd($tOuterA)
vd($tInnerA)
vd($tOuterB)
vd($tInnerB)

ChangeMe($tOuterB)

$tInnerA = DllStructCreate("int[5]", DllStructGetData($tOuterA, 2))
$tInnerB = DllStructCreate("int[5]", DllStructGetData($tOuterB, 2))
$cw("After:")
vd($tOuterA)
vd($tInnerA)
vd($tOuterB)
vd($tInnerB)

Func ChangeMe(ByRef $t)
    DllStructSetData($t, 1, "B chain!")
    ; local copy to work with
    Local $tt = DllStructCreate("int[5]", DllStructGetData($t, 2))
    DllStructSetData($tt, 1, 0, 3)
    ; same necessary write back step as with arrays!
    DllStructSetData($t, 2, DllStructGetPtr($tt))
EndFunc

$cw() is a consolewrite, vd() is a variable dump. Output is as follows:

Before:
Struct             (32) @:000001C4C9191FC0 (structure alignment is unknown)
      wchar[12]   'String A'
      ptr         0x000001C4C91CB170

Struct             (20) @:000001C4C91CB170 (structure alignment is unknown)
      int[5]
                  1
                  2
                  3
                  4
                  5

Struct             (32) @:000001C4C9191FF0 (structure alignment is unknown)
      wchar[12]   'String B'
      ptr         0x000001C4C91CB170

Struct             (20) @:000001C4C91CB170 (structure alignment is unknown)
      int[5]
                  1
                  2
                  3
                  4
                  5

After:
Struct             (32) @:000001C4C9191FC0 (structure alignment is unknown)
      wchar[12]   'String A'
      ptr         0x000001C4C91CB170

Struct             (20) @:000001C4C91CB170 (structure alignment is unknown)
      int[5]
                  1
                  2
                  0
                  4
                  5

Struct             (32) @:000001C4C9191FF0 (structure alignment is unknown)
      wchar[12]   'B chain!'
      ptr         0x000001C4C91CB170

Struct             (20) @:000001C4C91CB170 (structure alignment is unknown)
      int[5]
                  1
                  2
                  0
                  4
                  5

Note that we indeed changed item #3 of inner array inside struct $tOuterB but value got changed in $tOuterA as well since the pointers are the same.

Also note that I highly recommend against use of nested arrays as well as such above struct constructs!

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 post
Share on other sites
2 hours ago, jchd said:

AutoIt doesn't have a reference operator.

Thanks for confirming.  I greatly appreciate the time you have put into your code example using structs.

I think in my case, the best alternative will be to adopt the Registry pattern, store my arrays in another global array, and pass around a global array index as a reference for each sub-array.

2 hours ago, jchd said:

Also note that I highly recommend against use of nested arrays as well as such above struct constructs!

I'm guessing that this is mostly due to performance?

I suppose my proposed array-of-arrays could be a 2D array instead since each sub-array is guaranteed to be of a certain length.  Is that a significant improvement in your view?

Link to post
Share on other sites

If the array content is numerical only (or can be encoded as such), I would suggest looking into using matrices instead; they're natively 2D, limited in size only by your virtual memory, and can be accessed/manipulated orders of magnitude faster than AutoIt arrays (incl. file I/O).

Link to post
Share on other sites

My arrays contain varying content in this case—numbers, strings, handles, other arrays (I'm technically trying to emulate object instances).  Nonetheless, I'll keep your tip in mind for another time.  Thank you.

Link to post
Share on other sites

Then if the structure looks more like a tree, you can probably use a scripting.dictionary (search for that).

Else, a native 2D array with the maximum number of column could work too.

Edited by jchd

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 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
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By TheAlienDoctor
      Hi, I was looking into creating a script that would detect if a file exists, then move it (and in some cases rename it, depending on the file) as well as write to a log file.
      The issue is, there is a lot of files that need to be moved, sometimes some files will exist and others won't depending on the use-case. However if a file does exist, it will always be going into the same directory with the same name.
      Currently I have an array nested inside of the array, with each array inside that array having both the old and new directory, and then a For loop to actually run through and do the file transferring. The issue I am having is how to call the Array inside of the array, because how do I specify  which the old directory is and which the new is?
      Global $FileTransfer[2000] = [Global $Dir1[2] = ["original dir 1", "new dir 1"], Global $Dir2[2] = ["original dir 2", "new dir 2"]] For $FileTransfer = [0] To [1] Step +1 If FileExists({original dir}) Then FileMove({original dir}, new dir, 1) FileOpen("log.latest.txt", 1) FileWrite("log.latest.txt", "{original dir} found, moved it to new dir." & @CRLF) FileClose("log.latest.txt") Else FileOpen("log_latest.txt", 1) FileWrite("log_latest.txt", "{original dir} not found, ignoreing it." & @CRLF) FileClose("log_latest.txt") EndIf Next I have put what I want the old and new directory to be for each array in {}, so hopefully its easier to tell which part is working and whats not.

      I am still reasonably new to AutoIT, any help is appreciated. Thankyou
    • By arunkw
      I have a spreadsheet - daily routine which has two columns: activity and time as shown here
      | Activity             | Time     | |----------------------|----------| | Sleep               |  6:00 am | | Toilet              |  6:15 am | | Get ready for gym  |  6:30 am | | Exercise            |  7:50 am | | ... more things      |  9:00 pm | | ... still more       | 10:45 pm | | Sleep               |  6:00 am |   I wanted to find out, say in C1 which activity is current for me using now() I.e., if it’s 6:45am on my watch, it should show me Exercise  in C1 Thanks to Adam D. PE, this formula works like magic to get the result =VLOOKUP(MOD(NOW(),1),{B2:B,A2:A},2,1)   Now, I want to reproduce same result in autoit, how to do that? To have easy solution say, I copy-paste spreadsheet data in array directly in code, right? Use for loop and run the above vlookup function and show the answer using tooltip. How to achieve this? please help.  
    • By goku200
      I have an Autoit script that lists files from a folder into an array list. Is there a way to separate the filenames by an underscore and include the id, version, name and date into separate columns in Excel.
      Example of filename:
      12345_v1.0_TEST Name [12345]_01.01.2022.html
      12345 would be in one column
      v1.0 would be in another column
      TEST Name [12345] would be in another column
      01.01.2022 would be in another column
      .html would be in another column
      Note: filenames always change each day.
      Here is my code that lists the files into column C and then writes the column Headers into Column D, E, F, G. Just need some help with separating them into columns by the _ delimiter
       
    • By mLipok
      Usually when I collect data from DataBase I need to give EndUser a possibility to select rows which should be taken in the processing loop.
      I was searching on the forum and I'm not able to find any UDF or even example of how to select data from array.
      I have my own solutions but I think they are not worth posting on the forum as it is very old code and I am looking for a better solution.

      Could anybody point me to some examples/solutions ?

      Thank you in advance.
      @mLipok
    • By EmilyLove
      I have a string containing the full path of an executable and an array of executables without their paths. I am trying to compare the string to the list in the array and if a match is found, remove it from the array. The entry get removed from the array successfully, and after checking its return result, uses it to update the ubound if it succeeded, but it doesn't want to update to the new value. Any ideas what I am doing wrong? It acts like it is read-only.
      #include <Array.au3> #include <File.au3> Local $sApp_Exe = "F:\App\Nextcloud\nextcloud.exe" Local $aWaitForEXEX = [3, "Nextcloud.exe", "nextcloudcmd.exe", "QtWebEngineProcess.exe"] For $h = 1 To $aWaitForEXEX[0] If StringInStr($sApp_Exe, $aWaitForEXEX[$h]) <> 0 Then $iRet = _ArrayDelete($aWaitForEXEX, $h) If $iRet <> -1 Then $aWaitForEXEX[0] = $iRet ;this line doesn't work. $aWaitForEXEX[0] doesn't update and shortly gives Error: Array variable has incorrect number of subscripts or subscript dimension range exceeded.: _ArrayDisplay($aWaitForEXEX) EndIf Next  
×
×
  • Create New...