遍历字符串

基本类型 / 字符串

local word = "code"

-- gmatch(".") gives one byte at a time
for c in word:gmatch(".") do
  print(c)
end

-- Iterating with index: sub cuts one byte
for i = 1, #word do
  print("i = " .. i .. ", c = " .. word:sub(i, i))
end

-- Reverse iteration: the step is -1
for i = #word, 1, -1 do
  print(word:sub(i, i))
end

-- Reversed copy
local backwards = word:reverse()
-- backwards = edoc

-- byte gives the code of the byte
local code = word:byte(1)
-- code = 99

-- Not ASCII: "." walks bytes,
-- utf8.codes walks characters
local cafe = "caf\u{E9}"
local points = {}
for _, point in utf8.codes(cafe) do
  points[#points + 1] = point
end
-- points = 99, 97, 102, 233

print("backwards = " .. backwards)
print("code = " .. code)
print("points = " .. table.concat(points, ", "))