1
0
mirror of https://github.com/lua/lua.git synced 2025-01-14 05:43:00 +08:00

better check when converting from float to int, to avoid overflow

(on some machines it may result in run-time error)
This commit is contained in:
Roberto Ierusalimschy 1997-01-31 12:27:11 -02:00
parent d9ecc13545
commit 1143bf9286
2 changed files with 19 additions and 15 deletions

View File

@ -1,6 +1,6 @@
%{ %{
char *rcs_luastx = "$Id: lua.stx,v 3.41 1996/11/08 12:49:35 roberto Exp roberto $"; char *rcs_luastx = "$Id: lua.stx,v 3.42 1997/01/15 16:11:37 roberto Exp roberto $";
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
@ -163,9 +163,9 @@ static void add_varbuffer (Long var)
static void code_number (float f) static void code_number (float f)
{ {
Word i = (Word)f; Word i;
if (f == (float)i) /* f has an (short) integer value */ if (f >= 0 && f <= (float)MAX_WORD && (float)(i=(Word)f) == f) {
{ /* f has an (short) integer value */
if (i <= 2) code_byte(PUSH0 + i); if (i <= 2) code_byte(PUSH0 + i);
else if (i <= 255) else if (i <= 255)
{ {

View File

@ -3,7 +3,7 @@
** TecCGraf - PUC-Rio ** TecCGraf - PUC-Rio
*/ */
char *rcs_opcode="$Id: opcode.c,v 3.77 1996/11/18 13:48:44 roberto Exp roberto $"; char *rcs_opcode="$Id: opcode.c,v 3.78 1996/11/22 13:08:28 roberto Exp roberto $";
#include <setjmp.h> #include <setjmp.h>
#include <stdio.h> #include <stdio.h>
@ -157,16 +157,20 @@ static int lua_tonumber (Object *obj)
*/ */
static int lua_tostring (Object *obj) static int lua_tostring (Object *obj)
{ {
char s[256]; if (tag(obj) != LUA_T_NUMBER)
if (tag(obj) != LUA_T_NUMBER) return 1;
return 1; else {
if ((int) nvalue(obj) == nvalue(obj)) char s[60];
sprintf (s, "%d", (int) nvalue(obj)); real f = nvalue(obj);
else int i;
sprintf (s, "%g", nvalue(obj)); if ((real)(-MAX_INT) <= f && f <= (real)MAX_INT && (real)(i=(int)f) == f)
tsvalue(obj) = lua_createstring(s); sprintf (s, "%d", i);
tag(obj) = LUA_T_STRING; else
return 0; sprintf (s, "%g", nvalue(obj));
tsvalue(obj) = lua_createstring(s);
tag(obj) = LUA_T_STRING;
return 0;
}
} }