Add lualib support for Math.trunc (#1564) · TypeScriptToLua/TypeScriptToLua@5ba1fac · GitHub
Skip to content

Commit 5ba1fac

Browse files
authored
Add lualib support for Math.trunc (#1564)
Also includes a small fix that makes `Math.sign` ECMA compliant Closes #1550
1 parent d6f1bb0 commit 5ba1fac

5 files changed

Lines changed: 39 additions & 5 deletions

File tree

‎src/LuaLib.ts‎

Lines changed: 1 addition & 0 deletions

‎src/lualib/MathSign.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
1+
// https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.sign
2+
3+
import { __TS__NumberIsNaN } from "./NumberIsNaN";
4+
15
export function __TS__MathSign(this: void, val: number) {
2-
if (val > 0) {
3-
return 1;
4-
} else if (val < 0) {
6+
if (__TS__NumberIsNaN(val) || val === 0) {
7+
return val;
8+
}
9+
10+
if (val < 0) {
511
return -1;
612
}
713

8-
return 0;
14+
return 1;
915
}

‎src/lualib/MathTrunc.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.trunc
2+
3+
import { __TS__NumberIsFinite } from "./NumberIsFinite";
4+
export function __TS__MathTrunc(this: void, val: number) {
5+
if (!__TS__NumberIsFinite(val) || val === 0) {
6+
return val;
7+
}
8+
9+
return val > 0 ? math.floor(val) : math.ceil(val);
10+
}

‎src/transformation/builtins/math.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,10 @@ export function transformMathCall(
100100
return transformLuaLibFunction(context, LuaLibFeature.MathSign, node, ...params);
101101
}
102102

103+
case "trunc": {
104+
return transformLuaLibFunction(context, LuaLibFeature.MathTrunc, node, ...params);
105+
}
106+
103107
case "abs":
104108
case "acos":
105109
case "asin":

‎test/unit/builtins/math.spec.ts‎

Lines changed: 14 additions & 1 deletion

0 commit comments

Comments
 (0)