[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: 5.3.0-work3 and lossless integer conversion
- From: Josh Haberman <jhaberman@...>
- Date: Mon, 23 Jun 2014 01:20:23 -0700
I was just looking at 5.3.0-work3 and its integer APIs (excited for these).
My use case is a messaging (protobuf/JSON/etc) library. Because this
is a serialization system, I want to be very strict that you get out
exactly what you put in. I don't want to do any implicit conversion or
rounding whatsoever. (See this thread for more:
http://lua-users.org/lists/lua-l/2014-01/msg00137.html)
When I looked at the 5.3.0-work3 integer APIs they seem to make it
difficult to enforce this strictness:
- lua_tointeger() performs implicit conversion from string and rounding.
- lua_tonumber() performs implicit conversion from string.
- while I could test lua_isinteger() first, this would fail for floats
that have an integral value.
While part of me is ok with making users explicitly convert to integer
first, it would be an unnecessary (in my view) incompatibility between
Lua 5.3 and other versions of Lua. Pre-5.3 you wouldn't be able to
coerce to integer, but >=5.3 would require it. I'd prefer to just
allow floats as long as their value is integral.
To implement my desired check with the 5.3.0-work3 API, it appears I
would have to write:
lua_Integer checkint64(lua_State *L, int narg) {
if (lua_isinteger(L, narg)) {
return lua_tointeger(L, narg);
}
// Prevent implicit conversion from string.
luaL_checktype(L, narg, LUA_NUMBER);
lua_Number n = lua_tonumber(L, narg);
lua_Integer i = (lua_Integer)n;
if (i != n) {
// lua_Number -> lua_Integer truncated or rounded.
luaL_error(L, "non-integral value");
}
return i;
}
Maybe this isn't so bad. I guess I just wanted to write this out in
case seeing the use case gave you useful input for the design of the
feature/api. It could be that my use case is unusual in wanting to be
so strictly lossless.
Thanks,
Josh