lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> Borrowing Tim's crystal ball, I foresee that this indirect change in
> the behavior of lua_tointeger (caused by the change in lua_tointegerx)
> will take lots of people by surprise and silently break code out
> there. The Lua authors will be rightfully justified in blaming the
> module authors for relying on explicitly non-specified conversions,
> but since the conversions are more strict now in the Lua side too
> (generating obvious errors as pointed by Liam's original email), then
> perhaps the definition of lua_integer could be updated into something
> like the (untested) code below?
> 
> lua_Integer lua_tointeger (lua_State *L, int index) {
>   int isnum;
>   lua_Integer num = lua_tointegerx(L, index, &isnum);
>   if (!isnum) {
>     lua_pushliteral(L, "number has no integer representation");
>     lua_error(L);
>   }
>   return num;
> }
> 
> This would probably save a lot of headache, and people who know what
> they're doing and care for the last drop of performance in the Lua/C
> API can always use lua_tointegerx(L, index, NULL) explicitly.

Of course, lua_tointeger can fail for other reasons different
from "number has no integer representation" (e.g., tables also do not
have integer representations).

Anybody that calls lua_tointeger without knowing for sure that the
value is a number is already having a lot of headaches. On the other
hand, some programs use the fact that lua_tointeger returns zero
for non-number objects to avoid some checks. For instance, Lua 5.1
has the following:

LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
  lua_Integer d = lua_tointeger(L, narg);
  if (d == 0 && !lua_isnumber(L, narg))  /* avoid extra test when d is not 0 */
    tag_error(L, narg, LUA_TNUMBER);
  return d;
}

Your porposal would break that kind of code.

Probably a better solution (that, like most of this discussion,
has little to do with the new integer subtype), would be
to deprecate lua_tointeger. Programmers could still write
lua_tointegerx(L,index,NULL), but then it is very clear that they are
ignoring an error condition...

-- Roberto