Skip to content

Latest commit

 

History

History
542 lines (399 loc) · 10.5 KB

File metadata and controls

542 lines (399 loc) · 10.5 KB

TOML.lua API 文档

TOML.lua 库的完整 API 参考。


目录


概述

local toml = require("toml")

TOML.lua 模块提供了将 TOML 数据解析为 Lua 表和将 Lua 表编码为 TOML 格式的功能。


解析函数

toml.parse(input)

将 TOML 字符串解析为 Lua 表。

参数:

  • input (string) - TOML 文档字符串

返回:

  • table|nil - 解析后的 Lua 表数据,错误时返回 nil
  • string|nil - 解析失败时的错误信息

抛出: 无(错误作为第二个返回值返回)

示例:

local data, err = toml.parse('name = "Tom"\nage = 42')

if data then
  print(data.name)  -- "Tom"
  print(data.age)   -- 42
else
  print("Error:", err)
end

支持的 TOML 特性:

  • 字符串(基本、字面、多行)
  • 数字(整数、浮点数、十六进制、八进制、二进制)
  • 布尔值
  • 数组(嵌套、混合类型)
  • 表(表头、点号键)
  • 内联表
  • 表数组

toml.parse_file(path)

将 TOML 文件解析为 Lua 表。

参数:

  • path (string) - TOML 文件路径

返回:

  • table|nil - 解析后的 Lua 表数据,错误时返回 nil
  • string|nil - 解析失败时的错误信息

抛出: 无(错误作为第二个返回值返回)

示例:

local config, err = toml.parse_file("config.toml")

if config then
  print(config.title)
  print(config.database.host)
else
  print("Failed to read config:", err)
end

错误条件:

  • 文件不存在
  • 文件无法读取(权限问题)
  • 无效的 TOML 语法

编码函数

toml.encode(data, options)

将 Lua 表编码为 TOML 格式字符串。

参数:

  • data (table) - 要编码的 Lua 表
  • options (table, 可选) - 编码选项

返回:

  • string - TOML 格式字符串

抛出: 如果 data 不是表,则抛出错误

编码选项:

选项 类型 默认值 描述
indent number 2 缩进空格数
sort_keys boolean false 按字母顺序排序键
use_table_headers boolean false 对嵌套表使用 [header] 语法
inline_max_keys number 3 内联表格式的最大键数
use_array_table_format boolean true 对表数组使用 [[array]] 格式

默认编码行为:

默认情况下,toml.encode() 使用易读格式:

  • 表数组使用 [[array]] 语法(如 [[proxies]]
  • 嵌套表使用点号键(如 auth.method = "token"
  • 节与节之间有适当的空行
  • 文件以换行符结束

这使得输出更易于阅读和编辑,特别是对于配置文件。

示例:

local data = {
  name = "Tom",
  age = 42,
  items = {"a", "b", "c"}
}

-- 基本编码
local toml_string = toml.encode(data)
-- 输出: age = 42\nname = "Tom"\nitems = ["a", "b", "c"]

-- 排序键
local sorted = toml.encode(data, {sort_keys = true})

-- 使用表头
local with_headers = toml.encode({
  database = {host = "localhost", port = 5432}
}, {use_table_headers = true})
-- 输出: \n[database]\n  host = "localhost"\n  port = 5432

编码行为:

  • 简单值:编码为 key = value
  • 基本数组:编码为 key = [v1, v2, v3]
  • 表数组(默认):编码为 [[key]] 格式,每个元素单独一行
  • 表数组(紧凑):当 use_array_table_format = false 时,编码为内联:key = [{k1=v1}, {k2=v2}]
  • 小型嵌套表(< inline_max_keys):编码为 key = {k1 = v1, k2 = v2}
  • 大型嵌套表:编码为点号键(parent.child.key = value
  • 使用 use_table_headers:使用 TOML 节头

toml.encode_file(data, path, options)

将 Lua 表编码并写入 TOML 文件。

参数:

  • data (table) - 要编码的 Lua 表
  • path (string) - 输出文件路径
  • options (table, 可选) - 编码选项(与 toml.encode 相同)

返回:

  • boolean - 成功时返回 true
  • string|nil - 失败时的错误信息

抛出: 无(错误作为第二个返回值返回)

示例:

local data = {
  title = "My App",
  version = "1.0.0"
}

local ok, err = toml.encode_file(data, "config.toml")

if ok then
  print("Config saved successfully")
else
  print("Failed to save:", err)
end

错误条件:

  • data 不是表
  • path 不可写(权限问题、目录不存在)
  • 磁盘已满

验证函数

toml.validate(data)

验证解析后的 TOML 数据结构。

参数:

  • data (any) - 要验证的数据

返回:

  • boolean - 有效时返回 true
  • string|nil - 无效时的错误信息

示例:

local valid, err = toml.validate({name = "Tom"})

if valid then
  print("Data is valid")
else
  print("Validation failed:", err)
end

验证规则:

  • 数据必须是表
  • 当前执行基本验证
  • 未来版本将添加更多验证规则

错误处理

解析错误

解析错误包含详细的位置信息:

local data, err = toml.parse('name =')

-- err 包含:
-- "Parse error: Parse error at line 1, column 6: Expected value"

文件错误

文件错误包含操作系统级别的错误信息:

local data, err = toml.parse_file("nonexistent.toml")

-- err 包含:
-- "Cannot open file: nonexistent.toml: No such file or directory"

编码错误

编码错误作为 Lua 错误抛出:

local ok, err = pcall(function()
  toml.encode("not a table")  -- 抛出错误
end)

if not ok then
  print("Encode error:", err)
end

高级用法

往返转换

解析和编码时保留数据:

local original = {
  name = "Tom",
  config = {
    debug = true,
    port = 8080
  }
}

-- 编码为 TOML
local toml_string = toml.encode(original)

-- 解析回来
local parsed = toml.parse(toml_string)

-- 数据被保留
assert(parsed.name == original.name)
assert(parsed.config.port == original.config.port)

自定义格式化

控制 TOML 输出格式化:

local data = {
  z = 1,
  a = 2,
  database = {
    host = "localhost",
    port = 5432
  }
}

-- 排序键,无缩进
local compact = toml.encode(data, {
  sort_keys = true,
  indent = 0
})

-- 使用表头和缩进
local formatted = toml.encode(data, {
  sort_keys = true,
  use_table_headers = true,
  indent = 4
})

表数组格式(默认)

默认行为 - 使用易读的 [[array]] 格式:

local config = {
  server = "example.com",
  services = {
    {name = "web", port = 80, enabled = true},
    {name = "db", port = 5432, enabled = true}
  },
  auth = {
    method = "token",
    key = "secret"
  }
}

-- 默认编码(易读格式)
local toml_string = toml.encode(config)
-- 输出:
-- server = "example.com"
-- auth.method = "token"
-- auth.key = "secret"
--
-- [[services]]
--   name = "web"
--   port = 80
--   enabled = true
-- [[services]]
--   name = "db"
--   port = 5432
--   enabled = true

-- 紧凑编码(内联数组)
local toml_compact = toml.encode(config, {
  use_array_table_format = false
})
-- 输出:
-- server = "example.com"
-- auth = {method = "token", key = "secret"}
-- services = [{name = "web", port = 80, enabled = true}, {name = "db", port = 5432, enabled = true}]

何时使用哪种格式:

  • 默认([[array]]:配置文件、易读的输出、版本控制
  • 紧凑(内联):数据交换、自动化处理、最小化输出

处理数组

解析和操作数组:

local toml_string = [[
items = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
]]

local data = toml.parse(toml_string)

-- 访问数组元素
print(data.items[1])      -- "apple"
print(data.numbers[3])    -- 3

-- 添加到数组
table.insert(data.items, "grape")

-- 编码回来
local updated = toml.encode(data)

嵌套表结构

处理复杂的嵌套结构:

local toml_string = [[
[database]
host = "localhost"
port = 5432

[database.credentials]
username = "admin"
password = "secret"
]]

local data = toml.parse(toml_string)

-- 访问嵌套值
print(data.database.host)              -- "localhost"
print(data.database.credentials.username) -- "admin"

-- 修改嵌套值
data.database.port = 3306
data.database.timeout = 30

-- 编码回来
local updated = toml.encode(data)

内联表首选项

控制何时使用内联表:

local data = {
  server = {
    host = "localhost",
    port = 8080,
    ssl = true
  }
}

-- 默认:使用内联表(3 个键 <= inline_max_keys)
local toml1 = toml.encode(data)
-- 输出: server = {host = "localhost", port = 8080, ssl = true}

-- 强制使用表头
local toml2 = toml.encode(data, {
  inline_max_keys = 0,
  use_table_headers = true
})
-- 输出: \n[server]\n  host = "localhost"\n  port = 8080\n  ssl = true

数据类型映射

TOML 到 Lua

TOML 类型 Lua 类型 示例
字符串 string "hello"
整数 number 42
浮点数 number 3.14
布尔值 boolean true
数组 table [1, 2, 3]
table [section]
内联表 table {key = value}

Lua 到 TOML

Lua 类型 TOML 类型 示例
string 字符串 "hello"
number (int) 整数 42
number (float) 浮点数 3.14
boolean 布尔值 true
table (数组) 数组 [1, 2, 3]
table (映射) key = value

最佳实践

1. 始终检查返回值

local data, err = toml.parse_file("config.toml")
if not data then
  -- 处理错误
  return nil, err
end

2. 使用往返来更新配置

-- 读取配置
local config = toml.parse_file("config.toml")

-- 修改
config.new_setting = true

-- 写回(未来版本将保留注释)
toml.encode_file(config, "config.toml")

3. 验证输入

if type(input) ~= "string" then
  return nil, "Input must be a string"
end

local data = toml.parse(input)

4. 使用选项获得易读的输出

local toml_string = toml.encode(data, {
  sort_keys = true,
  indent = 2
})

限制

  1. 注释保留:往返期间会丢失注释(计划在未来版本中添加)
  2. 表顺序:不保证键的顺序(除非 sort_keys = true

版本历史

  • 0.2.0-alpha: 添加序列化(encode、encode_file)
  • 0.1.0-alpha: 初始版本,支持解析

更多示例请参见 examples/ 目录。