Add range-checking Lua stack -> C value converters

Signed-off-by: Uli Schlachter <psychon@znc.in>
This commit is contained in:
Uli Schlachter 2016-04-17 13:37:15 +02:00
parent 2cf4ea5cd4
commit 163c15979e
1 changed files with 39 additions and 0 deletions

39
luaa.h
View File

@ -75,6 +75,18 @@ luaA_typerror(lua_State *L, int narg, const char *tname)
return luaL_argerror(L, narg, msg); return luaL_argerror(L, narg, msg);
} }
static inline int
luaA_rangerror(lua_State *L, int narg, double min, double max)
{
const char *msg = lua_pushfstring(L, "value in [%f, %f] expected, got %f",
min, max, (double) lua_tonumber(L, narg));
#if LUA_VERSION_NUM >= 502
luaL_traceback(L, L, NULL, 2);
lua_concat(L, 2);
#endif
return luaL_argerror(L, narg, msg);
}
static inline void static inline void
luaA_getuservalue(lua_State *L, int idx) luaA_getuservalue(lua_State *L, int idx)
{ {
@ -166,6 +178,33 @@ luaA_getopt_integer(lua_State *L, int idx, const char *name, lua_Integer def)
return def; return def;
} }
static inline int
luaA_checkinteger_range(lua_State *L, int n, int min, int max)
{
int result = luaA_checkinteger(L, n);
if (result < min || result > max)
luaA_rangerror(L, n, min, max);
return result;
}
static inline lua_Integer
luaA_optinteger_range(lua_State *L, int narg, lua_Integer def, int min, int max)
{
if (lua_isnoneornil(L, narg))
return def;
return luaA_checkinteger_range(L, narg, min, max);
}
static inline int
luaA_getopt_integer_range(lua_State *L, int idx, const char *name, lua_Integer def, int min, int max)
{
lua_getfield(L, idx, name);
if (lua_isnil(L, -1) || lua_isnumber(L, -1))
def = luaA_optinteger_range(L, -1, def, min, max);
lua_pop(L, 1);
return def;
}
/** Push a area type to a table on stack. /** Push a area type to a table on stack.
* \param L The Lua VM state. * \param L The Lua VM state.
* \param geometry The area geometry to push. * \param geometry The area geometry to push.