lua: tonumber(s, base) for bases 2-36 +3 tests; math.lua past assert #21
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Has been cancelled

This commit is contained in:
2026-04-24 23:44:08 +00:00
parent 2a4a4531b9
commit 0491f061c4
5 changed files with 104 additions and 52 deletions

View File

@@ -1538,12 +1538,50 @@
(else (lua-to-display v)))))
(else (lua-to-display v)))))
(define
lua-parse-int-base
(fn (s base)
(let ((trimmed (trim s)) (neg false) (i 0) (n 0) (valid false))
(begin
(when (and (> (len trimmed) 0) (= (char-at trimmed 0) "-"))
(begin (set! neg true) (set! i 1)))
(when (and (> (len trimmed) i) (= (char-at trimmed i) "+"))
(set! i (+ i 1)))
(define
pi-loop
(fn ()
(when (< i (len trimmed))
(let ((c (char-at trimmed i)))
(let ((d (cond
((and (>= c "0") (<= c "9")) (- (char-code c) (char-code "0")))
((and (>= c "a") (<= c "z")) (+ 10 (- (char-code c) (char-code "a"))))
((and (>= c "A") (<= c "Z")) (+ 10 (- (char-code c) (char-code "A"))))
(else -1))))
(cond
((or (< d 0) (>= d base)) (set! i (len trimmed)))
(else
(begin
(set! n (+ (* n base) d))
(set! valid true)
(set! i (+ i 1))
(pi-loop)))))))))
(pi-loop)
(cond
((not valid) nil)
((< i (len trimmed)) nil)
(neg (- 0 n))
(else n))))))
(define
lua-tonumber
(fn (&rest args)
(let ((v (first args))
(base (if (> (len args) 1) (nth args 1) nil)))
(cond
((not (= base nil))
(cond
((= (type-of v) "string") (lua-parse-int-base v base))
(else nil)))
((= (type-of v) "number") v)
((= (type-of v) "string") (lua-to-number v))
(else nil)))))