From d76b9ffb3e6ed2d54367d7242134d3432ebb181e Mon Sep 17 00:00:00 2001 From: Francois Perrad Date: Wed, 18 Dec 2019 10:17:56 +0100 Subject: [PATCH] library math integer --- Makefile | 2 +- src/compat53/math.lua | 57 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 src/compat53/math.lua diff --git a/Makefile b/Makefile index 00c7d46e8c..4c3058db44 100644 --- a/Makefile +++ b/Makefile @@ -90,7 +90,7 @@ FILES_JITLIB= bc.lua bcsave.lua dump.lua p.lua v.lua zone.lua \ dis_x86.lua dis_x64.lua dis_arm.lua dis_arm64.lua \ dis_arm64be.lua dis_ppc.lua dis_mips.lua dis_mipsel.lua \ dis_mips64.lua dis_mips64el.lua vmdef.lua -FILES_COMPAT53= utf8.lua +FILES_COMPAT53= math.lua utf8.lua FILES_COMPAT54= utf8.lua ifeq (,$(findstring Windows,$(OS))) diff --git a/src/compat53/math.lua b/src/compat53/math.lua new file mode 100644 index 0000000000..7e34fb8373 --- /dev/null +++ b/src/compat53/math.lua @@ -0,0 +1,57 @@ +---------------------------------------------------------------------------- +-- math integer library. +-- +-- Copyright (C) 2019 Francois Perrad +-- +-- This library is licensed under the terms of the MIT/X11 license, +-- like LuaJIT itself. +---------------------------------------------------------------------------- + +local error, type = error, type +local math = math + +math.maxinteger = 9007199254740992 -- 2^53 +math.mininteger = -9007199254740992 + +function math.tointeger (n) + if type(n) == 'number' and n <= 9007199254740992 and n >= -9007199254740992 and n % 1 == 0 then + return n + end + return nil +end + +function math.type (n) + if type(n) == 'number' then + if n <= 9007199254740992 and n >= -9007199254740992 and n % 1 == 0 then + return 'integer' + else + return 'float' + end + else + return nil + end +end + +function math.ult (m, n) + local t = type(m) + if t ~= 'number' then + error("bad argument #1 to 'ult' (number expected, got " .. t .. ")", 2) + end + if m > 9007199254740992 or m < -9007199254740992 or m % 1 ~= 0 then + error("bad argument #1 to 'ult' (number has no integer representation)", 2) + end + t = type(n) + if t ~= 'number' then + error("bad argument #2 to 'ult' (number expected, got " .. t .. ")", 2) + end + if n > 9007199254740992 or n < -9007199254740992 or n % 1 ~= 0 then + error("bad argument #2 to 'ult' (number has no integer representation)", 2) + end + if m >= 0 and n < 0 then + return true + elseif m < 0 and n >= 0 then + return false + else + return m < n + end +end