Converting to a number

Basic types / Strings

-- To integer: the text has no dot
local str_number = "42"
local number = tonumber(str_number)
-- number = 42
local number_type = math.type(number)
-- number_type = integer

-- To float
local str_pi = "3.14"
local pi_float = tonumber(str_pi)
-- pi_float = 3.14
local pi_type = math.type(pi_float)
-- pi_type = float

-- The decimal comma is not understood.
-- Parentheses keep one value of gsub, otherwise
-- the count becomes the 2nd argument (a base)
local str_half = "0,5"
local half = tonumber((str_half:gsub(",", ".")))
-- half = 0.5

-- Spaces around the number are allowed
local padded = tonumber("  42  ")
-- padded = 42

-- Wrong text: nil, not 0 and not an error
local wrong = tonumber(str_half)
-- wrong = nil

print("number = " .. number)
print("number_type = " .. number_type)
print("pi_float = " .. pi_float)
print("pi_type = " .. pi_type)
print("half = " .. half)
print("padded = " .. padded)
print("wrong = " .. tostring(wrong))