Can I add two arrays together?

Monkey Forums/Monkey Programming/Can I add two arrays together?

Oddball(Posted 2014) [#1]
In BlitzMax I could add two string arrays like so
Local eName:String[]=["Enchanted","Mighty","Magical","Wondrous","Of power","Of glory","Ancient","Of wonder","Lucky","Heroic","Of amazement","Of renown","Rogue's","Exalted deeds","Ceremonial","Incredible","Ultimate","Marvelous","Mysterious"]
eName:+["Of doom","Of harming","Of wounding","Of lament","Bloodletter","Deathbringer","Of might","Of vengeance","Of wrath","Of pain"]


In monkey this gives me an illegal expression error. Code below.
Local eName:String[]=["Enchanted","Mighty","Magical","Wondrous","Of power","Of glory","Ancient","Of wonder","Lucky","Heroic","Of amazement","Of renown","Rogue's","Exalted deeds","Ceremonial","Incredible","Ultimate","Marvelous","Mysterious"]
eName+=["Of doom","Of harming","Of wounding","Of lament","Bloodletter","Deathbringer","Of might","Of vengeance","Of wrath","Of pain"]


What's the solution?


Gerry Quinn(Posted 2014) [#2]
The solution is that you can't add two arrays together.

So do something like:

Local a:String = [ .... ]
Local b:String = [ .... ]
Local total:String = New String[ a.Length() + b.Length() ]
' Copy a and b into total.

Don't imagine that this makes things less efficient, BlitzMax is almost certainly doing the same thing, only automatically.

Or you could write template code to add arrays, Okay, here it is ;-)



Usage:


(I put all methods like this into a class called Generic so I effectively have a syntax for generic functions, which Monkey doesn't support directly.)


Jesse(Posted 2014) [#3]
Not a Method, a Function!


Oddball(Posted 2014) [#4]
Damn. I was hoping I wouldn't have to copy over array fields individually. I'm porting some code and there are A LOT of these. Was hoping for a quick cut/paste/search/replace solution. Never mind, I guess I better roll my sleeves up and earn my money.


Gerry Quinn(Posted 2014) [#5]
You're right, that should of course be a function not a method. But aside from that, the generic code will work, e.g. you can import the code to any module that needs it, then convert the second statement in your example to:

eName = Generic< String >.ConcatenateArrays( eName, [ "Of Doom", "Of Harming", "etc." ] )

...without too much in the way of cutting and pasting, and no need to retype the string elements.

[Of course, if it's always going to be string arrays, you can write a non-generic function just for those.]