Fix arithmetic coercion - refactored and enhanced (#1576)

The Lua 5.4 compatible `tonumber` implementation completely reworked

- custom char-by-char parser (no regexes)
- proper Lua space handling
- support for heximal integers and floats
- support for scientific float notation
- extended tests
- updated website docs

Signed-off-by: Matouš Jan Fialka <mjf@mjf.cz>
This commit is contained in:
Matouš Jan Fialka
2025-10-01 11:30:58 +02:00
committed by GitHub
parent 26d9d5bdf0
commit 80f31da16b
7 changed files with 656 additions and 48 deletions
+2 -18
View File
@@ -21,6 +21,7 @@ import { mathApi } from "./stdlib/math.ts";
import { parse } from "./parse.ts";
import { evalStatement } from "./eval.ts";
import { encodingApi } from "./stdlib/encoding.ts";
import { luaToNumber } from "./tonumber.ts";
const printFunction = new LuaBuiltinFunction(async (_sf, ...args) => {
console.log(
@@ -112,24 +113,7 @@ const tostringFunction = new LuaBuiltinFunction((_sf, value: any) => {
const tonumberFunction = new LuaBuiltinFunction(
(_sf, value: LuaValue, base?: number) => {
if (typeof value === "string" && value.trim() === "") {
return null;
}
if (base !== undefined) {
if (base < 2 || base > 36) {
return null;
}
const n = parseInt(String(value), base);
if (isNaN(n)) {
return null;
}
return n;
}
const n = Number(value);
if (isNaN(n)) {
return null;
}
return n;
return luaToNumber(value, base);
},
);