Lua 标准库提供了一系列有用的函数和模块,可以帮助我们更高效地完成常见任务。本章将介绍一些重要的标准库,并通过实际应用来展示它们的用法。

8.1 字符串库

字符串库提供了处理字符串的各种函数。

  1. local s = "Hello, Lua!"
  2. -- 字符串长度
  3. print(#s) -- 输出: 11
  4. -- 字符串转换
  5. print(string.upper(s)) -- 输出: HELLO, LUA!
  6. print(string.lower(s)) -- 输出: hello, lua!
  7. -- 子字符串
  8. print(string.sub(s, 1, 5)) -- 输出: Hello
  9. -- 查找和替换
  10. print(string.find(s, "Lua")) -- 输出: 8 10
  11. print(string.gsub(s, "Lua", "World")) -- 输出: Hello, World! 1
  12. -- 字符串格式化
  13. print(string.format("Pi: %.2f", math.pi)) -- 输出: Pi: 3.14

8.2 表处理库

表处理库提供了操作表的函数。

  1. local t = {10, 20, 30, 40, 50}
  2. -- 插入和删除
  3. table.insert(t, 60)
  4. table.remove(t, 1)
  5. print(table.concat(t, ", ")) -- 输出: 20, 30, 40, 50, 60
  6. -- 排序
  7. table.sort(t)
  8. print(table.concat(t, ", ")) -- 输出: 20, 30, 40, 50, 60
  9. -- 最大值(Lua 5.2+)
  10. print(table.maxn(t)) -- 输出: 5

8.3 数学库

数学库提供了基本的数学函数。

  1. -- 基本运算
  2. print(math.abs(-10)) -- 输出: 10
  3. print(math.floor(3.7)) -- 输出: 3
  4. print(math.ceil(3.7)) -- 输出: 4
  5. -- 三角函数
  6. print(math.sin(math.pi / 2)) -- 输出: 1.0
  7. -- 随机数
  8. math.randomseed(os.time())
  9. print(math.random()) -- 输出: 01之间的随机数
  10. print(math.random(1, 10)) -- 输出: 110之间的随机整数

8.4 输入输出库

IO库提供了文件操作和标准输入输出的功能。

  1. -- 读取文件
  2. local file = io.open("example.txt", "r")
  3. if file then
  4. local content = file:read("*all")
  5. print(content)
  6. file:close()
  7. end
  8. -- 写入文件
  9. local file = io.open("output.txt", "w")
  10. if file then
  11. file:write("Hello, World!\n")
  12. file:close()
  13. end
  14. -- 用户输入
  15. print("Enter your name:")
  16. local name = io.read()
  17. print("Hello, " .. name)

8.5 操作系统库

OS库提供了与操作系统交互的函数。

  1. -- 当前时间
  2. print(os.date()) -- 输出当前日期和时间
  3. -- 执行系统命令
  4. os.execute("echo Hello from system")
  5. -- 获取环境变量
  6. print(os.getenv("PATH"))
  7. -- 测量代码执行时间
  8. local start = os.clock()
  9. for i = 1, 1000000 do end
  10. print(string.format("Time taken: %.2f seconds", os.clock() - start))

8.6 实例:配置文件解析器

让我们创建一个简单的配置文件解析器,它可以读取和写入配置文件。

  1. local ConfigParser = {}
  2. function ConfigParser.read(filename)
  3. local config = {}
  4. local file = io.open(filename, "r")
  5. if not file then return config end
  6. for line in file:lines() do
  7. local key, value = line:match("^(%w+)%s*=%s*(.+)$")
  8. if key and value then
  9. config[key] = value
  10. end
  11. end
  12. file:close()
  13. return config
  14. end
  15. function ConfigParser.write(filename, config)
  16. local file = io.open(filename, "w")
  17. if not file then return false end
  18. for key, value in pairs(config) do
  19. file:write(string.format("%s = %s\n", key, value))
  20. end
  21. file:close()
  22. return true
  23. end
  24. -- 使用示例
  25. local config = ConfigParser.read("config.ini")
  26. config.newSetting = "value"
  27. ConfigParser.write("config.ini", config)

8.7 实例:简单的文本游戏

最后,让我们使用学到的知识创建一个简单的文本冒险游戏。

  1. local game = {
  2. player = {
  3. name = "",
  4. health = 100,
  5. inventory = {}
  6. },
  7. locations = {
  8. {name = "Forest", description = "A dark and mysterious forest."},
  9. {name = "Cave", description = "A damp and echoing cave."},
  10. {name = "Mountain", description = "A tall and snowy mountain."}
  11. },
  12. currentLocation = 1
  13. }
  14. function game.start()
  15. print("Welcome to the Text Adventure!")
  16. print("What's your name?")
  17. game.player.name = io.read()
  18. print("Hello, " .. game.player.name .. "! Your adventure begins.")
  19. game.showLocation()
  20. end
  21. function game.showLocation()
  22. local location = game.locations[game.currentLocation]
  23. print("\nYou are in the " .. location.name)
  24. print(location.description)
  25. game.showOptions()
  26. end
  27. function game.showOptions()
  28. print("\nWhat would you like to do?")
  29. print("1. Move to next location")
  30. print("2. Check inventory")
  31. print("3. Quit")
  32. local choice = tonumber(io.read())
  33. if choice == 1 then
  34. game.moveToNextLocation()
  35. elseif choice == 2 then
  36. game.checkInventory()
  37. elseif choice == 3 then
  38. print("Thanks for playing!")
  39. os.exit()
  40. else
  41. print("Invalid choice. Try again.")
  42. game.showOptions()
  43. end
  44. end
  45. function game.moveToNextLocation()
  46. game.currentLocation = game.currentLocation % #game.locations + 1
  47. game.showLocation()
  48. end
  49. function game.checkInventory()
  50. print("\nInventory:")
  51. if #game.player.inventory == 0 then
  52. print("Your inventory is empty.")
  53. else
  54. for _, item in ipairs(game.player.inventory) do
  55. print("- " .. item)
  56. end
  57. end
  58. game.showOptions()
  59. end
  60. -- 开始游戏
  61. game.start()

练习

  1. 扩展配置文件解析器,使其支持注释和节(sections)。
  2. 为文本游戏添加更多功能,如战斗系统、物品收集和使用等。
  3. 创建一个使用 Lua 标准库的简单日志系统,支持不同的日志级别和输出格式。

通过本章的学习,你应该能够熟练使用 Lua 的标准库,并能够将这些知识应用到实际项目中。这些库和技能将大大提高你的 Lua 编程效率和能力。