Number Parsing in Lua
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:
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.