I have this function:
function AddImpulse(Vector2D impulse)
{
`log("ADD IMPULSE: " $ impulse);
}
The trouble is that I get the error "Right type is incompatible with '$'. It seems that, although the built-in vector class will automatically coerce to a string, the Vector2D class is just a built-in struct without any operator overloading or automatic conversion.
I wrote an operator overload that help the situation, but unless I put the declaration of the overload in the object class (which I'm lead to believe shouldn't be done) I have to declare it in every class that may use it:
static final operator(40) string $ (string A, Vector2D B)
{
return A $ string(B.x) $ ", " $ string(B.y);
}
Is there a way this can be done generically so that I don't need to do this every time:
`log("ADD IMPULSE: " $ impulse.x $ "," $ impulse.Y);
Although that is not bad in the case of a Vector2D, this will become cumbersome with larger structures or classes.
Your options for generic programming in UnrealScript are limited, unfortunately. One option may be to put your operator overload in an include file and include it in each class that needs it using the `include
macro.
If that doesn't work, another option may be to use a macro to invoke a static function in a special class for handling struct to string conversions.
First create a Globals.uci file in your code package's root folder. Globals.uci is a special file which is automatically included by the compiler in all UncrealScript files in the package it is associated with. If your package is called MyPackage, Globals.uci would go in Development/Src/MyPackage/Globals.uci. It should be next to the Classes folder for your package.
Put your macro in Globals.uci:
`define toString(type,name) class'MyStructConversions'.static.`{type}ToString(`{name},"`{name}")
Put your conversion function in MyStructConversions.uc:
class MyStructConversions;
static function string Vector2DToString (const out Vector2D A, string varname)
{
return varname $ ": (" $ A.X $ ", " $ A.Y $ ")";
}
Now when you call `toString(Vector2D, impulse)
from anywhere in your package the macro will be replaced at compile time with an invocation to your Vector2DToString function. You can then support more struct types by adding the appropriate definitions to MyStructConversions.uc, and the toString macro will work seamlessly with them.
The documentation on the UnrealScript preprocessor has more information on `include
and other macros. Check out Globals.uci in Development/Src/Core for some useful examples as well.