From 163c15979e1737cab5b391cd0fbfb81de2d6b459 Mon Sep 17 00:00:00 2001 From: Uli Schlachter Date: Sun, 17 Apr 2016 13:37:15 +0200 Subject: [PATCH] Add range-checking Lua stack -> C value converters Signed-off-by: Uli Schlachter --- luaa.h | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/luaa.h b/luaa.h index 42404eeb..c27b5d21 100644 --- a/luaa.h +++ b/luaa.h @@ -75,6 +75,18 @@ luaA_typerror(lua_State *L, int narg, const char *tname) 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 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; } +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. * \param L The Lua VM state. * \param geometry The area geometry to push.