从字符串转换

基本类型 / 数字 / 整型

-- 对全是数字的文本,tonumber 给出整数
local number = tonumber("42")
-- number = 42

-- 两侧的空格会被忽略
local padded = tonumber(" 42 ")
-- padded = 42

-- 不是数字:nil,不是 0,也不是错误
local not_number = tonumber("42 apples")
-- not_number = nil

-- 带小数点会得到浮点数,math.tointeger 可将其转回整数
local text_float = tonumber("3.0")
-- text_float = 3.0
local whole = math.tointeger(text_float)
-- whole = 3

-- 真正的小数没有整数形式
local fraction = math.tointeger(3.5)
-- fraction = nil

print("number = " .. number)
print("padded = " .. padded)
print("not_number = " .. tostring(not_number))
print("text_float = " .. text_float)
print("whole = " .. whole)
print("fraction = " .. tostring(fraction))

-- tonumber 返回的 nil 会让下一次求和出错
local ok, err = pcall(function()
  return not_number + 1
end)
-- ok = false
-- err = main.lua:32: attempt to perform
-- arithmetic on a nil value
-- (upvalue 'not_number')
print("ok = " .. tostring(ok))
print("err = " .. err)