Jump to content
  • Advertisement
Miss

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 this post


Link to post
Share on other sites
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();
}

 

Share this post


Link to post
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 :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!