Adventure Game Studio

AGS Support => Advanced Technical Forum => Topic started by: eri0o on Sat 13/02/2021 23:14:31

Title: Modify String that is passed as parameter, is it possible?
Post by: eri0o on Sat 13/02/2021 23:14:31
I want to do something like:

Code (ags) Select
function modifyString (String s)
{
  // some way to modify the string
  s = s.Append("world");
}


And then run it like
Code (ags) Select
String str = "hello ";
  modifyString(str);
  Display(str);


Unfortunately the above gives me "hello " instead of "hello world". Is there a way in AGS to modify a String in place? The problem I have is my function has to return additional information - an integer with some status information. Unfortunately, I can't return a pointer to struct that contains the String since this would be pointer of pointer... So if I could modify the string in place it would be perfect.

So far my only solution is to return the String and have the function receive a pointer to a struct that has the int so it can modify the integer in place instead...
Title: Re: Modify String that is passed as parameter, is it possible?
Post by: Crimson Wizard on Sat 13/02/2021 23:47:03
AGS Strings are immutable, and this is why all of the modifying functions return new String.

you use them like
Code (ags) Select
s = s.Append("more");

If you write your own functions then the use method should be similar.
Code (ags) Select
String modifyString (String s)
{
  // some way to modify the string
  return s.Append("world");
}

Code (ags) Select

  String str = "hello ";
  str = modifyString(str);
  Display(str);
Title: Re: Modify String that is passed as parameter, is it possible?
Post by: eri0o on Sun 14/02/2021 00:18:09
Ah, ok, thanks! Then it's settled!  :)

I ended up going with the route

Code (ags) Select
managed struct Result
{
  int value; 
};


String modifyString (String s, Result* res)
{
  // some way to modify the string
  res.value = 5;
  return s.Append("world");
}


And run like
Code (ags) Select
String str = "hello ";
  Result* res = new Result;
  str = modifyString(str, res);
  Display(str);


Got the job done, so it's alright! (it has more lines but that is the spirit, it works, I am happy!)