diff --git a/compat/luajit.lua b/compat/luajit.lua index 72cb133..2a6bfc9 100644 --- a/compat/luajit.lua +++ b/compat/luajit.lua @@ -476,10 +476,14 @@ end -- ---------------------------------------------------------------------------------------------------- math do + -- math.min / math.max are LuaJIT fast functions (branch-free minsd / maxsd in a trace); the two data-dependent + -- branches of `if x < lo ... elseif x > hi` spawned side traces in hot loops (codecs/Dct, colour conversion) and + -- ran ~3.5x slower. NaN stays NaN, as in Luau (maxsd would return lo). + local mmin, mmax = math.min, math.max math.clamp = math.clamp or function(x, lo, hi) if lo > hi then error("max must be greater than or equal to min", 2) end - if x < lo then return lo elseif x > hi then return hi end - return x + if x ~= x then return x end + return mmin(mmax(x, lo), hi) end math.sign = math.sign or function(x) if x > 0 then return 1 elseif x < 0 then return -1 end