Skip to content

Commit

Permalink
From Lua 5.2: Add lua_tonumberx() and lua_tointegerx().
Browse files Browse the repository at this point in the history
Contributed by François Perrad.
  • Loading branch information
Mike Pall committed Apr 7, 2017
1 parent 2b8de8c commit de26f76
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
47 changes: 46 additions & 1 deletion src/lj_api.c
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,22 @@ LUA_API lua_Number lua_tonumber(lua_State *L, int idx)
return 0;
}

LUA_API lua_Number lua_tonumberx(lua_State *L, int idx, int *ok)
{
cTValue *o = index2adr(L, idx);
TValue tmp;
if (LJ_LIKELY(tvisnumber(o))) {
if (ok) *ok = 1;
return numberVnum(o);
} else if (tvisstr(o) && lj_strscan_num(strV(o), &tmp)) {
if (ok) *ok = 1;
return numV(&tmp);
} else {
if (ok) *ok = 0;
return 0;
}
}

LUALIB_API lua_Number luaL_checknumber(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
Expand Down Expand Up @@ -379,9 +395,38 @@ LUA_API lua_Integer lua_tointeger(lua_State *L, int idx)
if (!(tvisstr(o) && lj_strscan_number(strV(o), &tmp)))
return 0;
if (tvisint(&tmp))
return (lua_Integer)intV(&tmp);
return intV(&tmp);
n = numV(&tmp);
}
#if LJ_64
return (lua_Integer)n;
#else
return lj_num2int(n);
#endif
}

LUA_API lua_Integer lua_tointegerx(lua_State *L, int idx, int *ok)
{
cTValue *o = index2adr(L, idx);
TValue tmp;
lua_Number n;
if (LJ_LIKELY(tvisint(o))) {
if (ok) *ok = 1;
return intV(o);
} else if (LJ_LIKELY(tvisnum(o))) {
n = numV(o);
} else {
if (!(tvisstr(o) && lj_strscan_number(strV(o), &tmp))) {
if (ok) *ok = 0;
return 0;
}
if (tvisint(&tmp)) {
if (ok) *ok = 1;
return intV(&tmp);
}
n = numV(&tmp);
}
if (ok) *ok = 1;
#if LJ_64
return (lua_Integer)n;
#else
Expand Down
2 changes: 2 additions & 0 deletions src/lua.h
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,8 @@ LUA_API int lua_loadx (lua_State *L, lua_Reader reader, void *dt,
const char *chunkname, const char *mode);
LUA_API const lua_Number *lua_version (lua_State *L);
LUA_API void lua_copy (lua_State *L, int fromidx, int toidx);
LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *isnum);
LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *isnum);

/* From Lua 5.3. */
LUA_API int lua_isyieldable (lua_State *L);
Expand Down

0 comments on commit de26f76

Please sign in to comment.