1. 字符串库(string):
- string.sub(s, i, j): 返回字符串 s 从位置 i 到 j 的子串。
- string.len(s): 返回字符串 s 的长度。
- string.find(s, pattern): 在字符串 s 中查找匹配 pattern 的子串,返回其起始和结束位置。
- string.gsub(s, pattern, replace): 替换字符串 s 中匹配 pattern 的子串为 replace。
2. 表库(table):
- table.insert(table, pos, value): 在表 table 的位置 pos 处插入值 value。
- table.remove(table, pos): 移除表 table 的位置 pos 的元素。
- table.concat(table, sep): 将表 table 中的元素连接为字符串,使用分隔符 sep。
- table.sort(table, comp): 对表 table 进行排序,可传递比较函数 comp。
3. 数学库(math):
- math.abs(x): 返回 x 的绝对值。
- math.sqrt(x): 返回 x 的平方根。
- math.sin(x), math.cos(x), math.tan(x): 返回 x 的正弦、余弦、正切值。
- math.random(), math.randomseed(seed): 生成伪随机数,可设置种子。
4. 文件库(io):
- io.open(filename, mode): 以指定模式 mode 打开文件 filename,返回文件对象。
- file:read(format): 读取文件内容,可指定读取格式。
- file:write(data): 将数据写入文件。
- file:close(): 关闭文件。
5. 操作系统库(os):
- os.execute(command): 在操作系统中执行命令。
- os.time(): 返回当前的系统时间。
- os.date(format, time): 返回格式化的日期字符串,可指定格式和时间。
6. 调试库(debug):
- debug.debug(): 进入一个交互式的调试器。
- debug.traceback(): 返回当前的调用堆栈信息。
示例代码:
-- 字符串库示例
local myString = "Lua Programming"
print(string.sub(myString, 1, 3)) -- 输出: Lua
print(string.len(myString)) -- 输出: 16
print(string.find(myString, "Pro")) -- 输出: 5 12
print(string.gsub(myString, "Programming", "Scripting")) -- 输出: Lua Scripting
-- 表库示例
local myTable = {1, 2, 3}
table.insert(myTable, 2, 4)
table.remove(myTable, 3)
print(table.concat(myTable, ", ")) -- 输出: 1, 4
-- 数学库示例
print(math.abs(-5)) -- 输出: 5
print(math.sqrt(25)) -- 输出: 5
print(math.sin(math.pi)) -- 输出: 1.2246467991474e-16
-- 文件库示例
local file = io.open("example.txt", "w")
file:write("Hello, Lua!")
file:close()
-- 操作系统库示例
os.execute("echo Hello from the operating system")
-- 调试库示例
debug.debug()
这些库提供了在实际编程中经常用到的功能,帮助你更方便地进行字符串处理、表操作、数学计算、文件读写等任务。在编写 Lua 程序时,熟悉这些库的使用方式将大大提高你的开发效率。
转载请注明出处:http://www.pingtaimeng.com/article/detail/6509/Lua