[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: lua_number2integer
- From: Asko Kauppi <askok@...>
- Date: Thu, 25 Sep 2008 20:47:12 +0300
'lua_tointeger()' could easily be changed so that it does not allow
non-integer numbers as input.
The LNUM patch actually does this, unless LUA_COMPAT_TOINTEGER is
defined.
LUA_API lua_Integer lua_tointeger (lua_State *L, int idx) {
TValue n;
/* Lua 5.1 documented behaviour is to return nonzero for non-
integer:
* "If the number is not an integer, it is truncated in some non-
specified way."
*/
#ifdef LUA_COMPAT_TOINTEGER
...
#else
/* New suggestion */
const TValue *o = index2adr(L, idx);
if (tonumber(o, &n)) {
lua_Integer i;
if (ttisint(o)) return ivalue(o);
if (tt_integer_valued(o,&i)) return i;
}
#endif
return 0;
}
Also, a 'lua_isinteger()' would be needed to tell, if a value can be
carried unchanged in 'lua_Integer'.
LUA_API int lua_isinteger (lua_State *L, int idx) {
TValue tmp;
lua_Integer dum;
const TValue *o = index2adr(L, idx);
#ifdef LUA_TINT
return tonumber(o,&tmp) && (ttisint(o) || tt_integer_valued(o,&dum));
#else
return tonumber(o,&tmp) && tt_integer_valued(o,&dum);
#endif
}
-asko
Mike Pall kirjoitti 25.9.2008 kello 15:56:
Cuero Bugot wrote:
Here is the code which revealed the unconsistency of the number to
integer
process:
string.char(112+remaining/256, remaining%256)
where remaining was taken from 0 to 4095.
This code was done assuming that the string.char function was
"correctly
truncating" the value as C would do it in such a case.
Passing non-integral numbers to library functions expecting
integral numbers is "undefined". There is no "correct rounding
mode" in this case -- Lua is not C.
Rewrite your example as:
local r = remaining % 256
string.char(112 + (remaining-r)/256, r)
Or better use the struct library:
struct.pack(">H", 0x7000+remaining)
Get it from: http://www.inf.puc-rio.br/~roberto/struct/
--Mike