Jump to content

Recommended Posts

Posted (edited)

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
Posted (edited)

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? <_<

Posted

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

 

Posted

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.

Posted

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

Posted

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.

Posted

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)

Posted
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?

Posted

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

Posted

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.

Posted (edited)

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)

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
×
×
  • Create New...