Suggestion: Enum to string

Started by
2 comments, last by Wipe 5 years, 2 months ago

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.

Advertisement

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();
}

 

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

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 :)

Games are meant to be created, not played...

This topic is closed to new replies.

Advertisement