替换字符

基本类型 / 字符串

local text = "1-3-2"

-- gsub 构建新字符串,原文本保持不变
local replaced = text:gsub("3", "x")
-- replaced = 1-x-2
-- text = 1-3-2

-- 通过字符数组交换两个字符
local chars = {}
for char in text:gmatch(".") do
  chars[#chars + 1] = char
end
chars[3], chars[5] = chars[5], chars[3]
local swapped = table.concat(chars)
-- swapped = 1-2-3

print("replaced = " .. replaced)
print("text = " .. text)
print("swapped = " .. swapped)

-- 字符串不可变:不能按索引赋值
local ok, err = pcall(function()
  text[3] = "2"
end)
-- ok = false
-- err = main.lua:23: attempt to index a string
-- value (upvalue 'text')
print("ok = " .. tostring(ok))
print("err = " .. err)