• Subject: Re: Fast integer arithmetic
• From: ramsdell@... (John D. Ramsdell)
• Date: 20 Feb 2008 10:35:39 -0500

```Enrico Colombini <erix@erix.it> writes:

> I just put this at the end of luaconf.h.

To make progress on supporting integer operations, you must change
src/lvm.c so that it correctly handles integer divide by zero.  I've
enclosed a patch that addresses this issue.  It also provides integer
exponentiation.

John

diff -ur olua-5.1.3/src/lvm.c lua-5.1.3/src/lvm.c
--- olua-5.1.3/src/lvm.c	2007-12-28 10:32:23.000000000 -0500
+++ lua-5.1.3/src/lvm.c	2008-02-20 10:27:15.000000000 -0500
@@ -27,6 +27,37 @@
#include "lvm.h"

+#if defined LUA_NUMBER_INTEGRAL
+#define luai_znumdiv(a,b)	\
+  ((b)==0?			\
+   (luaG_runerror(L,"divide by zero"),0): \
+   luai_numdiv(a,b))
+#define luai_znummod(a,b)	\
+  ((b)==0?			\
+   (luaG_runerror(L,"modulo by zero"),0): \
+   luai_nummod(a,b))
+
+LUA_NUMBER luai_ipow(LUA_NUMBER a, LUA_NUMBER b) {
+  if (b < 0)
+    return 0;
+  else if (b == 0)
+    return 1;
+  else {
+    LUA_NUMBER c = 1;
+    for (;;) {
+      if (b & 1)
+	c *= a;
+      b = b >> 1;
+      if (b == 0)
+	return c;
+      a *= a;
+    }
+  }
+}
+#else
+#define luai_znumdiv(a,b)	(luai_numdiv(a,b))
+#define luai_znummod(a,b)	(luai_nummod(a,b))
+#endif

/* limit for table tag-method chains (to avoid loops) */
#define MAXTAGLOOP	100
@@ -321,8 +352,8 @@
case TM_SUB: setnvalue(ra, luai_numsub(nb, nc)); break;
case TM_MUL: setnvalue(ra, luai_nummul(nb, nc)); break;
-      case TM_DIV: setnvalue(ra, luai_numdiv(nb, nc)); break;
-      case TM_MOD: setnvalue(ra, luai_nummod(nb, nc)); break;
+      case TM_DIV: setnvalue(ra, luai_znumdiv(nb, nc)); break;
+      case TM_MOD: setnvalue(ra, luai_znummod(nb, nc)); break;
case TM_POW: setnvalue(ra, luai_numpow(nb, nc)); break;
case TM_UNM: setnvalue(ra, luai_numunm(nb)); break;
default: lua_assert(0); break;
@@ -480,11 +511,11 @@
continue;
}
case OP_DIV: {
-        arith_op(luai_numdiv, TM_DIV);
+        arith_op(luai_znumdiv, TM_DIV);
continue;
}
case OP_MOD: {
-        arith_op(luai_nummod, TM_MOD);
+        arith_op(luai_znummod, TM_MOD);
continue;
}
case OP_POW: {
Only in lua-5.1.3/src: lvm.c~

```