util.mathcompat: Module to ease reuse of math.type()

Mostly to ensure it is available during tests, as util.startup is not
invoked there
This commit is contained in:
Kim Alvefur 2022-10-20 16:50:12 +02:00
parent e64c5e30c2
commit e2cff34641
7 changed files with 41 additions and 10 deletions

View file

@ -19,6 +19,8 @@
-- TODO s/number/integer/ once we have appropriate math.type() compat
--
if not math.type then require "util.mathcompat" end
local st = require "util.stanza";
local json = require"util.json"
local pointer = require"util.jsonpointer";

View file

@ -8,6 +8,8 @@
-- https://json-schema.org/draft/2020-12/json-schema-validation.html
--
if not math.type then require "util.mathcompat" end
local json = require"util.json"
local null = json.null;

View file

@ -0,0 +1,15 @@
if not math.type then
local enum number_subtype
"float" "integer"
end
local function math_type(t:any) : number_subtype
if t is number then
if t % 1 == 0 and t ~= t+1 and t ~= t-1 then
return "integer"
else
return "float"
end
end
end
_G.math.type = math_type
end

View file

@ -1,5 +1,9 @@
-- This file is generated from teal-src/util/datamapper.lua
if not math.type then
require("util.mathcompat")
end
local st = require("util.stanza");
local pointer = require("util.jsonpointer");

13
util/mathcompat.lua Normal file
View file

@ -0,0 +1,13 @@
if not math.type then
local function math_type(t)
if type(t) == "number" then
if t % 1 == 0 and t ~= t + 1 and t ~= t - 1 then
return "integer"
else
return "float"
end
end
end
_G.math.type = math_type
end

View file

@ -21,6 +21,10 @@ local to_hex = require "util.hex".to;
local pcall = pcall;
local envload = require"util.envload".envload;
if not math.type then
require "util.mathcompat"
end
local pos_inf, neg_inf = math.huge, -math.huge;
local m_type = math.type;

View file

@ -280,16 +280,7 @@ function startup.init_global_state()
-- COMPAT Lua < 5.3
if not math.type then
-- luacheck: ignore 122/math
function math.type(n)
if type(n) == "number" then
if n % 1 == 0 and (n + 1 ~= n and n - 1 ~= n) then
return "integer"
else
return "float"
end
end
end
require "util.mathcompat"
end
end