Number Parsing in Lua
-- Lua doesn't have a built-in package for number parsing like Go's strconv.
-- We'll use Lua's tonumber() function for basic parsing and implement
-- custom functions for more complex cases.
-- Function to parse float
local function parseFloat(str)
return tonumber(str)
end
-- Function to parse int (base 10 by default)
local function parseInt(str, base)
return tonumber(str, base or 10)
end
-- Function to parse unsigned int (base 10 by default)
local function parseUint(str, base)
local num = tonumber(str, base or 10)
return num and math.abs(num) or nil
end
-- Main function
local function main()
-- Parse float
local f = parseFloat("1.234")
print(f)
-- Parse int
local i = parseInt("123")
print(i)
-- Parse hexadecimal
local d = parseInt("0x1c8", 16)
print(d)
-- Parse unsigned int
local u = parseUint("789")
print(u)
-- Basic base-10 int parsing
local k = parseInt("135")
print(k)
-- Parsing functions return nil on bad input
local bad = parseInt("wat")
print(bad)
end
main()
This Lua code demonstrates number parsing, similar to the original example. Here’s a breakdown of the changes and explanations:
Lua doesn’t have a built-in package for number parsing like Go’s
strconv
. Instead, we use Lua’stonumber()
function and implement custom functions for more specific parsing.We define
parseFloat()
,parseInt()
, andparseUint()
functions to mimic the behavior of Go’s parsing functions.The
parseFloat()
function simply uses Lua’stonumber()
, which can handle floating-point numbers.The
parseInt()
function usestonumber()
with an optional base parameter. If no base is provided, it defaults to base 10.The
parseUint()
function is similar toparseInt()
, but it usesmath.abs()
to ensure the result is non-negative.In the
main()
function, we demonstrate the usage of these parsing functions, similar to the original example.Lua doesn’t have explicit error handling like Go. Instead, the parsing functions return
nil
for invalid input.
To run this Lua script:
$ lua number-parsing.lua
1.234
123
456
789
135
nil
Note that Lua’s number parsing is more lenient than Go’s. For example, Lua will successfully parse “1.234” as both a float and an integer (truncating the decimal part), while Go’s ParseInt
would return an error for this input.
Next, we’ll look at another common parsing task: URLs.