Skip to main content

Module numeric

Module numeric 

Source
Expand description

Lua numeral conversion core (stone candidate: pure functions, no runtime types). Two consumers: the lexer (literal tokens, shape pre-validated by scanning) and the VM/stdlib (str2num — luaO_str2num semantics with whitespace and sign). Versioning is expressed as capability flags so this module stays dialect-agnostic.

Enums§

Num
Result of parsing a Lua numeric literal — either an integer or a float (Lua 5.1 collapses everything to float at this layer).

Functions§

dec_literal
Decimal numeral (no sign, no surrounding space). int_ok = false forces float results (Lua 5.1: numbers are doubles). neg is whether a leading ‘-’ was stripped by the caller: it widens the integer range by one unit (PUC l_str2int’s + neg) so that the magnitude 2^63 parses as an integer — letting tonumber("-9223372036854775808") recover minint. The caller still applies the actual negation.
hex_digit
Decode a single ASCII hex digit (0-9, a-f, A-F) into its numeric value, or return None for a non-hex byte.
hex_literal
Hex numeral after the 0x prefix (no sign, no surrounding space).
num_to_string
Lua number → text. Integers print as integers. Floats print with shortest round-trip digits (the 5.5 “read back correctly” rule) in C %g-style presentation: scientific form when the decimal exponent falls outside [-4, 14), two-digit signed exponent, and .0 appended to integral-looking decimals (PUC lua_number2str). Exact boundary alignment against PUC 5.5 output is rechecked by the P04 gate (strings/math suites).
num_to_string_for
Variant for ≤5.2: those dialects only had lua_Number (a double), so PUC’s %.14g formatter trims any trailing .0 (an integer-valued float renders as plain 2, not 2.0). 5.3+ introduced the integer subtype and the renderer started appending .0 to distinguish floats — pm.lua’s pattern transformations build "%" .. (s+1) and need "%2" on 5.1/5.2.
str2num
luaO_str2num: optional surrounding whitespace and sign, decimal or hex. Used by VM string→number coercion and tonumber.
write_i64_dec
Write i64 decimal into a stack buffer; returns the slice of valid bytes inside buf. 20 chars covers i64::MIN..=i64::MAX (the longest is “-9223372036854775808” at 20 bytes). Hot in tostring(int) on numeric-heavy workloads (string_concat builds 5000 of these): skips the String allocation that i.to_string() does.