"legal" way to convert a float to an integer in C

This commit is contained in:
Roberto Ierusalimschy
2013-05-27 09:43:37 -03:00
parent 8c883cb4e8
commit d630daca1a
3 changed files with 30 additions and 10 deletions

20
lvm.c
View File

@@ -1,5 +1,5 @@
/*
** $Id: lvm.c,v 2.169 2013/05/06 17:17:09 roberto Exp roberto $
** $Id: lvm.c,v 2.170 2013/05/26 14:47:51 roberto Exp roberto $
** Lua virtual machine
** See Copyright Notice in lua.h
*/
@@ -58,17 +58,25 @@ int luaV_tostring (lua_State *L, StkId obj) {
}
/*
** Check whether a float number is within the range of a lua_Integer.
** (The comparisons are tricky because of rounding, which can or
** not occur depending on the relative sizes of floats and integers.)
** This function is called only when 'n' has an integer value.
*/
int luaV_numtointeger (lua_Number n, lua_Integer *p) {
lua_Integer k;
lua_number2integer(k, n);
if (luai_numeq(cast_num(k), n)) { /* 'k' is int? */
*p = k;
if (cast_num(MIN_INTEGER) <= n && n < (MAX_INTEGER + cast_num(1))) {
*p = cast_integer(n);
lua_assert(cast_num(*p) == n);
return 1;
}
return 0;
return 0; /* number is outside integer limits */
}
/*
** try to convert a non-integer value to an integer
*/
int luaV_tointeger_ (const TValue *obj, lua_Integer *p) {
lua_Number n;
lua_assert(!ttisinteger(obj));