(01-15-2013, 05:14 PM)Adrianis Wrote: In your example, both A and B will modify the original variable when they return - in my mind, there should only be 1 point where the modified value should be returned if possible.
Since A would be passed the reference, it then passes the reference to the original to B, when B returns it will modify the original, and when A returns it will also modify the original...
No, since
string is a
reference type (not the & kind of references, something else - didn't cover that yet in the guide, will do together with classes). AngelScript has two kinds of types -
value types (like
bool,
int and
float), which store their value directly, and
reference types , which are more like pointers, except you don't have to deference them or worry about memory deallocation. This type system is different than those of C and C++, but is very similar to that of C# (which I understand pretty well). So, when strings are passed by reference like that, all of those parameters are, internally, essentially pointers to the same thing. So, in my example, when the string is changed in B(), the original is affected
instantly (as soon as that line executes, before the func ends) - nothing else happens when each of the function returns.
This is the reason why (I suspect, though I could be wrong) callbacks accept
sting &in and not
string& - if it was the other way around, you'd potentially be able to affect some internal strings keys of the game, as the engine passes in names of various entities, or timer IDs, etc. Since &in references are basically the same as passing by value (except if the param is const), this can't happen.
(01-15-2013, 05:14 PM)Adrianis Wrote: I was wary at first about using 'GetGlobalVarString()' as an argument, as I'm not sure exactly what it returns, but I tested it (extensively, and hopefully thoroughly) and it does work as intended. If you happen to know of a problem with doing this I would love to know it
The wiki says it returns a
string& (string by reference), but that's a bit tricky to figure out since you are not allowed to have non-parameter
string& variables. When you assign the result to a
string, a copy is made (you can tell by passing it by reference to a function that changes it, and then call GetGlobalVarString() to see if it was affected).
But, you can assign it to a
string@ variable, which is AngelScript's equivalent to those "smart" pointers I mentioned before (works only on reference types). A
string@ variable is used as a normal
string, but it points to the original memory.
You were right to be wary though; I did some tests, and in some cases, unclear to me at this point (in my case it was when I set the string to be a small sequence of 1-3 chars), strange things happen (nothing get's printed out, etc.). Not sure why.
But both this is pretty much equivalent and should work without problems:
string@ s = GetGlobalVarString("globalstringname");
int inNextPos = GetSetNextSpawnSequential(s);