Suggestion: Enum to string

Recommended Posts

I end up needing this a lot for debugging; to be able to cast the name of an enum value to a string. Right now, I always make a function like "string GetCategoryName(SomeCategory cat)" and return the name from a switch statement. Of course that gets harder to do if you have a lot of enum values.

I'm sure it can be done externally by creating some generic function or something, but it would be quite nice to have it integrated into the language somehow.

Additionally, I think it would be cool to have the ability to have some kind of toString() function, however this might be a bit too high level though, so is probably better to implement at the application level via some base object class.

Edited by Miss

Share on other sites

In what situation do you want this? The debugger add-on has a ToString that translates the values of the enum types into the matching symbol (when it exists).

If you want to have it as a function that can be called from the script, you can easily implement a function with the same logic and register it with the engine. You can use the variable type for the argument so it can fit any type.

string CDebugger::ToString(void *value, asUINT typeId, int expandMembers, asIScriptEngine *engine)
{
...

else if( (typeId & asTYPEID_MASK_OBJECT) == 0 )
{
// The type is an enum
s << *(asUINT*)value;

// Check if the value matches one of the defined enums
if( engine )
{
asITypeInfo *t = engine->GetTypeInfoById(typeId);
for( int n = t->GetEnumValueCount(); n-- > 0; )
{
int enumVal;
const char *enumName = t->GetEnumValueByIndex(n, &enumVal);
if( enumVal == *(int*)value )
{
s << ", " << enumName;
break;
}
}
}
}

...

return s.str();
}

Share on other sites

Had same problem few years back, so i ended with this. It's pretty old (~2013), but could be a good starting point

There's also great reflection addon by @cvet for more complex stuff; most likely easier to work with than bunch of global functions in first link :)

Create an account

Register a new account

• What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 9
• 11
• 9
• 23
• 18
• Forum Statistics

• Total Topics
634432
• Total Posts
3017388
×