Array Push Function
Posted: Fri Jun 13, 2014 12:53 am
I created this simple array push function but have ran into some issues. The function works fine as long as long as the array name that you pass it as the first argument already exists, the variable type equals array, and the value is not null. I would like to be able to call this function in cases where if the array doesn't already exist, to create it, and add the second parameter to it. The problem with this is since the array doesn't exist, therefore it's value equals nil and it is basically like you never added the first parameter to the function which produces wacky results.
Here is the function
The only thing I can currently think of is to test if the array exists before I initially call the function and if not, create a variable as a string, then convert it to an array but that's a lot of extra steps.
Here is the function
ros code
# Usage: [$arrayPush <array name> <value>] # Input an array name and a value to push to the end of the array :global arrayPush do={ :if ($1="") do={ :error "You did not specify an array name argument."; } :if ($2="") do={ :error "You did not specify a value to add to the array."; } :local string; :if ([:typeof $1]="array") do={ :foreach item in=$1 do={ :set string ($string . "," . $item); } :set string ($string . "," . $2); :set string [:toarray $string]; :return $string; } else={ :error "Argument 1 variable type was not an array."; } }Here is an example of what I mean
ros code
:global myVar; :set myVar [:toarray $myVar]; :set myVar [$arrayPush $myVar "some value"];Since $myVar is nil, the toarray function essentially does nothing and the next line has undesired results. I'm not sure exactly how to explain this but hopefully you get the picture. Any ideas on a way to work around this?
The only thing I can currently think of is to test if the array exists before I initially call the function and if not, create a variable as a string, then convert it to an array but that's a lot of extra steps.