字符串拼接

基本类型 / 字符串

local s1 = "three"
local s2 = "two"

-- .. 连接字符串;没有 +=,要把结果赋回去
local s3 = s1 .. ", " .. s2
s3 = s3 .. ", one"
local s_go = s3 .. ", go!"
-- s_go = three, two, one, go!

-- string.format 用一个模板生成
local formatted =
  string.format("%s, %s, one, go!", s1, s2)
-- formatted = three, two, one, go!

print("s_go = " .. s_go)
print("formatted = " .. formatted)

-- 只有字符串和数字能连接
local missing
local ok, err = pcall(function()
  return "value: " .. missing
end)
-- ok = false
-- err = main.lua:21: attempt to concatenate a nil
-- value (upvalue 'missing')
print("ok = " .. tostring(ok))
print("err = " .. err)