Merge pull request #62 from djpohly/enum-compatibility

Backwards-compatible type-safe enum behavior
This commit is contained in:
Colby Klein
2014-02-23 23:24:42 -08:00
3 changed files with 36 additions and 1 deletions
+18
View File
@@ -22,6 +22,24 @@ int CheckEnum( lua_State *L, LuaReference &table, int iPos, int iInvalid, const
lua_pushvalue( L, iPos );
lua_gettable( L, -2 );
// If not found, check case-insensitively for legacy compatibility
if( lua_isnil(L, -1) && lua_isstring(L, iPos) ) {
RString sLower;
// Get rid of nil value on stack
lua_pop( L, 1 );
// Get the string and lowercase it
lua_pushvalue( L, iPos );
LuaHelpers::Pop( L, sLower );
sLower.MakeLower();
// Try again to read the value
table.PushSelf( L );
LuaHelpers::Push( L, sLower );
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.
+8
View File
@@ -135,6 +135,14 @@ static void Lua##X(lua_State* L) \
lua_pushstring( L, (#X "_")+s ); \
lua_pushnumber( L, i ); /* 0-based */ \
lua_rawset( L, -3 ); \
/* Compatibility with old, case-insensitive values */ \
s.MakeLower(); \
lua_pushstring( L, s ); \
lua_pushnumber( L, i ); /* 0-based */ \
lua_rawset( L, -3 ); \
/* Compatibility with old, raw values */ \
lua_pushnumber( L, i ); \
lua_rawseti( L, -2, i ); \
} \
EnumTraits<X>::StringToEnum.SetFromStack( L ); \
EnumTraits<X>::StringToEnum.PushSelf( L ); \
+10 -1
View File
@@ -2223,8 +2223,17 @@ public:
static int ApplyGameCommand( T* p, lua_State *L )
{
PlayerNumber pn = PLAYER_INVALID;
if( lua_gettop(L) >= 2 && !lua_isnil(L,2) )
if( lua_gettop(L) >= 2 && !lua_isnil(L,2) ) {
// Legacy behavior: if an old-style numerical argument
// is given, decrement it before trying to parse
if( lua_isnumber(L,2) ) {
int arg = (int) lua_tonumber( L, 2 );
arg--;
LuaHelpers::Push( L, arg );
lua_replace( L, -2 );
}
pn = Enum::Check<PlayerNumber>(L, 2);
}
p->ApplyGameCommand(SArg(1),pn);
return 0;
}