Register Lua enum types as strings, not numbers.

- Even though these strings are in the context of the table, we still prefix them
   with the enum name ("UnlockRequirement_ArcadePoints", not "ArcadePoints").  The typical
   use is as a simple string (obj:Call("Type")), not as an index into the table, and
   this makes the type clear and easy to search for in that case.
 - no "NUM_UnlockRequirement"; use #UnlockRequirement.
 - no UnlockRequirement_Invalid; use nil
 - Enum<X>::Check always returns a valid X; no additional error checking is
   needed and Lua code can no longer introduce invalid enum values into C
 - This does not support enum types with holes; neither does FOREACH.
 - This is typesafe.  If you give "GAME_CONTROLLER_1" to a function expecting an
   UnlockRequirement, we can detect the error and show a meaningful error message.
 - Lua strings are always merged, and comparisons are as cheap as integers, so
   this isn't slow (and may be faster).
 - Can iterate: for i,j in ipairs(UnlockEntry) do func(j) end
   (This is a bit clumsy; probably want a foreach() iterator that doesn't return i)
 - ThemeMetric<UnlockRequirement> just works.
This commit is contained in:
Glenn Maynard
2006-09-26 01:41:40 +00:00
parent 923f0f7346
commit 3d79319c04
2 changed files with 96 additions and 0 deletions
+30
View File
@@ -1,5 +1,35 @@
#include "global.h"
#include "EnumHelper.h"
#include "LuaManager.h"
#include "RageUtil.h"
int CheckEnum( lua_State *L, LuaReference &table, int iPos, int iInvalid, const char *szType )
{
if( lua_isnil(L, iPos) )
return iInvalid;
iPos = LuaHelpers::AbsIndex( L, iPos );
table.PushSelf( L );
lua_pushvalue( L, iPos );
lua_gettable( L, -2 );
// If the result is nil, then a string was passed that is not a member of this enum. Throw
// an error. To specify the invalid value, pass nil. That way, typos will throw an error,
// and not silently result in nil, or an out-of-bounds value.
if( unlikely(lua_isnil(L, -1)) )
{
// XXX: show string if a string, otherwise the type
lua_pushvalue( L, iPos );
RString sGot;
LuaHelpers::Pop( L, sGot );
LuaHelpers::Push( ssprintf("Expected %s; got \"%s\"", szType, sGot.c_str() ), L );
lua_error( L );
}
int iRet = lua_tointeger( L, -1 );
lua_pop( L, 2 );
return iRet;
}
/*
* (c) 2004 Chris Danford