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 authored and lukego committed Aug 13, 2017
1 parent 9fabcf9 commit ffd2610
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/lj_api.c
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,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 @@ -360,8 +376,35 @@ LUA_API lua_Integer lua_tointeger(lua_State *L, int idx)
} else {
if (!(tvisstr(o) && lj_strscan_number(strV(o), &tmp)))
return 0;
if (tvisint(&tmp))
return intV(&tmp);
n = numV(&tmp);
}
return (lua_Integer)n;
}

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;
return (lua_Integer)n;
}

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 ffd2610

Please sign in to comment.