0

This code

07: ReDim newArray(0)
08: ReDim oldArray(0)

'populating newArray

40: wscript.echo "redimming oldArray to length of " & UBound(newArray)
41: ReDim oldArray(UBound(newArray))
42: wscript.echo UBound(oldArray)
43: oldArray = newArray

results in the following output:

redimming oldArray to length of 19
19
D:\Scripts\test.vbs(43, 2) Microsoft VBScript runtime error: Type mismatch

How can I make a copy of "newArray()"? (Created via this question)

Community
  • 1
  • 1

1 Answers1

-1

In VBScript, array assignment copies the right hand side value:

>> Dim a : a = Array(1,2,3)
>> Dim b : b = a
>> b(0) = 17
>> WScript.Echo Join(a), Join(b)
>>
1 2 3 17 2 3

(as opposed to other languages where array assignment often means to make an alias of/a reference to the r-value).

So: don't create an array for the l-value, just Dim the name (to allow Option Explicit).

Attempt II:

If you want a copy of a dynamic array, just assign it to a clean/new variable.

BTW: ReDim newArray(0) - creates an array containing one (empty) element; reflect on the difference between size/Num of Elms vs. UBound/Last Index.

Attempt III:

ReDim a(n) ' create array for/with n+1 elements
... fill a ...
Dim b ' plain variant variable
b = a ' copy a (in)to b
Ekkehard.Horner
  • 38,498
  • 2
  • 45
  • 96
  • So you're saying if I remove line 08, I should just be able to say "oldArray = newArray"? –  Jun 16 '14 at 21:05