forked from TypeScriptToLua/TypeScriptToLua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParseInt.ts
More file actions
41 lines (35 loc) · 1.29 KB
/
ParseInt.ts
File metadata and controls
41 lines (35 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const __TS__parseInt_base_pattern = "0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTvVwWxXyYzZ";
function __TS__ParseInt(this: void, numberString: string, base?: number): number {
// Check which base to use if none specified
if (base === undefined) {
base = 10;
const [hexMatch] = string.match(numberString, "^%s*-?0[xX]");
if (hexMatch) {
base = 16;
numberString = string.match(hexMatch, "-")[0]
? "-" + numberString.substr(hexMatch.length)
: numberString.substr(hexMatch.length);
}
}
// Check if base is in bounds
if (base < 2 || base > 36) {
return NaN;
}
// Calculate string match pattern to use
const allowedDigits =
base <= 10
? __TS__parseInt_base_pattern.substring(0, base)
: __TS__parseInt_base_pattern.substr(0, 10 + 2 * (base - 10));
const pattern = `^%s*(-?[${allowedDigits}]*)`;
// Try to parse with Lua tonumber
const number = tonumber(string.match(numberString, pattern)[0], base);
if (number === undefined) {
return NaN;
}
// Lua uses a different floor convention for negative numbers than JS
if (number >= 0) {
return math.floor(number);
} else {
return math.ceil(number);
}
}