最近在上班lua使用的比较多,打算系统的学习一下,然后先把菜鸟的教程看完在看官方文档以及unlua,之前我更新过一个unlua最重要的地图,但是现在看起来后半部分与实际开发其实脱轨了,因为实际项目不一定是那些api和需要学习的组件,所以还是以实际为主,把基础打好,官方的一些重点的api,库文件搞懂再说
一、字符串基础
1.1 字符串的创建
在Lua中,字符串可以使用三种方式表示:
-- 1. 单引号
local str1 = 'Hello, Lua!'
-- 2. 双引号
local str2 = "Hello, World!"
-- 3. 双括号(多行字符串)
local str3 = [[
这是一个
多行
字符串
]]
-- 4. 长括号(可嵌套,等号数量要匹配)
local str4 = [=[
字符串内容 [[可以包含]] 方括号
]=]
1.2 转义字符
Lua支持常见的转义序列:
print("换行:第一行\n第二行")
print("制表符:\t缩进文本")
print("双引号:\"引号内的内容\"")
print("反斜杠:\\")
print("空字符:\0")
二、字符串操作
2.1 字符串连接
-- 使用 .. 操作符
local name = "Lua"
local greeting = "Hello, " .. name .. "!"
print(greeting) -- 输出: Hello, Lua!
-- 字符串与数字连接(自动转换)
local version = 5.4
local msg = "Lua " .. version
print(msg) -- 输出: Lua 5.4
2.2 字符串长度
local str = "Hello"
print(#str) -- 输出: 5
print(string.len(str)) -- 输出: 5
2.3 字符串查找
local text = "Hello, Lua Programming"
-- 查找子串
local start, finish = string.find(text, "Lua")
print(start, finish) -- 输出: 8 10
-- 模式匹配查找
local match = string.match(text, "Lua (%w+)")
print(match) -- 输出: Programming
三、字符串常用函数
3.1 大小写转换
local str = "Hello Lua"
print(string.upper(str)) -- 输出: HELLO LUA
print(string.lower(str)) -- 输出: hello lua
3.2 字符串截取
local str = "Hello, World!"
-- 子字符串
print(string.sub(str, 1, 5)) -- 输出: Hello
print(string.sub(str, 8)) -- 输出: World!
print(string.sub(str, -6, -1)) -- 输出: World!
3.3 字符串替换
local str = "I like apples and apples are tasty"
-- 替换所有匹配
local new_str = string.gsub(str, "apples", "oranges")
print(new_str) -- 输出: I like oranges and oranges are tasty
-- 限制替换次数
local limited = string.gsub(str, "apples", "oranges", 1)
print(limited) -- 输出: I like oranges and apples are tasty
3.4 字符串重复
local str = "Ha"
print(string.rep(str, 3)) -- 输出: HaHaHa
print(string.rep("-", 20)) -- 输出: --------------------
3.5 字符串格式化
local name = "Alice"
local age = 25
local height = 1.68
-- 类似C语言的printf
local msg = string.format("Name: %s, Age: %d, Height: %.2f", name, age, height)
print(msg) -- 输出: Name: Alice, Age: 25, Height: 1.68
四、模式匹配(Pattern Matching)
Lua的模式匹配使用不同于正则表达式的语法,但功能强大:
local text = "The price is $19.99 and $29.99"
-- 查找所有数字
for price in string.gmatch(text, "%$?%d+%.?%d*") do
print("Found:", price)
end
-- 常用模式匹配字符:
-- . 任意字符
-- %a 字母
-- %d 数字
-- %w 字母数字
-- %s 空白字符
-- %u 大写字母
-- %l 小写字母
-- [] 字符类
-- + 重复一次或多次
-- * 重复零次或多次
-- - 重复零次或多次(最短匹配)
-- ? 可选
五、字符串与表
5.1 字符串分割
function split(str, delimiter)
local result = {}
local pattern = string.format("([^%s]+)", delimiter)
for match in string.gmatch(str, pattern) do
table.insert(result, match)
end
return result
end
local parts = split("apple,banana,orange", ",")
for i, v in ipairs(parts) do
print(i, v)
end
5.2 表连接为字符串
local fruits = {"apple", "banana", "orange"}
local str = table.concat(fruits, ", ")
print(str) -- 输出: apple, banana, orange
六、性能优化技巧
6.1 避免在循环中拼接字符串
-- 不推荐(性能差)
local result = ""
for i = 1, 1000 do
result = result .. i .. ","
end
-- 推荐(使用表连接)
local parts = {}
for i = 1, 1000 do
table.insert(parts, i)
end
local result = table.concat(parts, ",")
6.2 预编译模式
-- 当需要多次使用相同模式时
local pattern = "%d+"
local compiled_pattern = string.gmatch("", pattern)
local text = "123 abc 456 def"
for number in string.gmatch(text, pattern) do
print(number)
end
七、实战示例
7.1 简单的模板引擎
function render(template, data)
return (template:gsub("%$(%w+)", data))
end
local template = "Hello, $name! Your score is $score."
local data = {name = "Alice", score = 95}
print(render(template, data))
7.2 字符串验证
function isEmail(email)
return email:match("[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?")
end
function isPhoneNumber(phone)
return phone:match("^%d%d%d%-%d%d%d%d%-%d%d%d%d$")
end
八、最佳实践
-
一致性:在项目中统一使用一种字符串引号风格
-
使用string库:优先使用string库函数而非自己实现
-
注意编码:Lua字符串是字节序列,处理非ASCII字符时要小心
-
性能考虑:大量字符串操作时考虑使用table.concat
-
模式匹配:理解Lua模式与正则表达式的区别
总结
Lua的字符串处理功能虽然简单,但通过string库提供的函数和强大的模式匹配功能,能够满足大部分文本处理需求。掌握这些技巧后,你就能高效地在Lua中进行各种字符串操作了。记住实践是最好的学习方法,多写代码,多实验!