Game Development Community

Returning an array from a function

by Bryce "Cogburn" Weiner · in Torque Game Engine · 07/16/2004 (1:33 pm) · 8 replies

I was going to share this anyway.... So you can keep it if you tell me what's wrong. ;)

// Split a string (%parse) by another string (%delim) and return it as an array.
function splitString(%parse, %delim)
{
	if (%delim !$= ""){
		%posDelim = strpos(%parse, %delim);
		if (%posDelim == 0)
			return -1;
		%len = strlen(%parse);
		%temp[0] = getSubStr (%parse, 0, %posDelim - 1);
		%parse = getSubStr (%parse, %posDelim + 1, %len - %posDelim);
		%posDelim = strpos (%parse, %delim);
		%x = 1;
		while (%posDelim > 0) {
			%len = strlen(%parse);
			%temp[%x] = getSubStr (%parse, 0, %posDelim);
			%parse = getSubStr (%parse, %posDelim + 1, %len - %posDelim);
			%posDelim = strpos (%parse, %delim);
			%x++;
		}
		%temp[%x] = %parse;
		return %temp;
	} else {
		return -1;
	}
}

Works ok if I do some echo()'s in the code to print results at various stages. The problem is that when I do something like....

%test = splitString("0:1:2:3:4:5",":");

... %test is always empty.

Have I been staring at this too long to see the problem or can functions not return arrays?

#1
07/16/2004 (2:47 pm)
You can't return an array, unfortunately.
#2
07/16/2004 (3:21 pm)
Doh!

Thank you. Cut and paste it is then. :)
#3
07/16/2004 (3:52 pm)
I don't know if this is of any help to you, but you can use strings in an "array like way" using SetWord and GetWord if you use space as a delimiter:

// Init the "array"
%mystring = "1 2 3 4 5";
echo(%mystring);

// Get the first element 
%firstElement = GetWord(%mystring,0);
echo(%firstElement); // %firstElement is 1

// Set the last element in the array to -1
%mystring = SetWord(%mystring,4,-1);
echo(%mystring); // %mystring is now 1 2 3 4 -1

of course this will bork if there are spaces in the elements.
#4
07/16/2004 (5:31 pm)
There are spaces to be accounted for, but that's still good to know. Thanks Russell.
#5
07/16/2004 (5:40 pm)
Yeah Array's are global if I'm not mistaken.
#6
07/17/2004 (11:47 am)
You can also use tabbed fields for passing lists among text funcitons. (look in consoleFunctions.cc for getField() and it's brothers). In fact for one setup I did I used sets of space delimited lists grouped into tabbed lists.

But there is a really nice resource for a script array object that you may very well find usefull...

www.garagegames.com/index.php?sec=mg&mod=resource&page=view&qid=4711
#7
07/17/2004 (2:32 pm)
@Martin: Thanks. That's a great resource. Hope it makes its way into HEAD. Beats the heck out of using GetWord/SetWord.
#8
07/17/2004 (6:04 pm)
NP. It's a great resource and probably should be in the HEAD. The only thing it lacks is network propigation, so you could swap arrays with clients. Of course I doubt that would be all that hard to implement.