转换为字符串

基本类型 / 布尔类型

local sun_is_star = true
local str_sun = tostring(sun_is_star)
-- str_sun = true

-- A string now, not a boolean
local sun_type = type(str_sun)
-- sun_type = string

local earth_is_star = false
local str_earth = tostring(earth_is_star)
-- str_earth = false

-- %s calls tostring by itself
local sentence = string.format("Is a star: %s",
                               earth_is_star)
-- sentence = Is a star: false

print("str_sun = " .. str_sun)
print("sun_type = " .. sun_type)
print("str_earth = " .. str_earth)
print("sentence = " .. sentence)

-- Trap: .. does not convert a boolean
local ok, err = pcall(function()
  return "Is a star: " .. earth_is_star
end)
-- ok = false
-- err = main.lua:25: attempt to concatenate a
-- boolean value (upvalue 'earth_is_star')
print("ok = " .. tostring(ok))
print("err = " .. err)