From bb1851ce98e80ef9fadd9d02510c3e8f0a6569f6 Mon Sep 17 00:00:00 2001 From: Roberto Ierusalimschy Date: Thu, 25 Apr 2013 16:50:02 -0300 Subject: [PATCH] 'for' loop uses integers when possible --- lvm.c | 49 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/lvm.c b/lvm.c index 212583f6..e129438d 100644 --- a/lvm.c +++ b/lvm.c @@ -1,5 +1,5 @@ /* -** $Id: lvm.c,v 2.160 2013/04/25 16:07:52 roberto Exp roberto $ +** $Id: lvm.c,v 2.161 2013/04/25 19:12:41 roberto Exp roberto $ ** Lua virtual machine ** See Copyright Notice in lua.h */ @@ -805,27 +805,44 @@ void luaV_execute (lua_State *L) { } ) vmcase(OP_FORLOOP, - lua_Number step = nvalue(ra+2); - lua_Number idx = luai_numadd(L, nvalue(ra), step); /* increment index */ - lua_Number limit = nvalue(ra+1); - if (luai_numlt(L, 0, step) ? luai_numle(L, idx, limit) - : luai_numle(L, limit, idx)) { - ci->u.l.savedpc += GETARG_sBx(i); /* jump back */ - setnvalue(ra, idx); /* update internal index... */ - setnvalue(ra+3, idx); /* ...and external index */ + if (ttisinteger(ra)) { /* integer count? */ + lua_Integer step = ivalue(ra + 2); + lua_Integer idx = ivalue(ra) + step; /* increment index */ + lua_Integer limit = ivalue(ra + 1); + if ((0 < step) ? (idx <= limit) : (limit <= idx)) { + ci->u.l.savedpc += GETARG_sBx(i); /* jump back */ + setivalue(ra, idx); /* update internal index... */ + setivalue(ra + 3, idx); /* ...and external index */ + } + } + else { /* floating count */ + lua_Number step = fltvalue(ra + 2); + lua_Number idx = luai_numadd(L, fltvalue(ra), step); /* inc. index */ + lua_Number limit = fltvalue(ra + 1); + if (luai_numlt(L, 0, step) ? luai_numle(L, idx, limit) + : luai_numle(L, limit, idx)) { + ci->u.l.savedpc += GETARG_sBx(i); /* jump back */ + setnvalue(ra, idx); /* update internal index... */ + setnvalue(ra + 3, idx); /* ...and external index */ + } } ) vmcase(OP_FORPREP, const TValue *init = ra; const TValue *plimit = ra+1; const TValue *pstep = ra+2; - if (!tonumber(init, ra)) - luaG_runerror(L, LUA_QL("for") " initial value must be a number"); - else if (!tonumber(plimit, ra+1)) - luaG_runerror(L, LUA_QL("for") " limit must be a number"); - else if (!tonumber(pstep, ra+2)) - luaG_runerror(L, LUA_QL("for") " step must be a number"); - setnvalue(ra, luai_numsub(L, nvalue(ra), nvalue(pstep))); + if (ttisinteger(ra) && ttisinteger(ra + 1) && ttisinteger(ra + 2)) { + setivalue(ra, ivalue(ra) - ivalue(pstep)); + } + else { /* try with floats */ + if (!tonumber(init, ra)) + luaG_runerror(L, LUA_QL("for") " initial value must be a number"); + else if (!tonumber(plimit, ra+1)) + luaG_runerror(L, LUA_QL("for") " limit must be a number"); + else if (!tonumber(pstep, ra+2)) + luaG_runerror(L, LUA_QL("for") " step must be a number"); + setnvalue(ra, luai_numsub(L, fltvalue(ra), fltvalue(pstep))); + } ci->u.l.savedpc += GETARG_sBx(i); ) vmcasenb(OP_TFORCALL,