-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoption.lua
More file actions
95 lines (81 loc) · 2.37 KB
/
Copy pathoption.lua
File metadata and controls
95 lines (81 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
---解析命令行参数
---@param args string[] 参数列表
---@return table config 解析后的配置对象
local function parse_args(args)
local config = {}
local i = 1
while i <= #args do
local arg = args[i]
if arg:sub(1, 2) == "--" then
-- 长参数格式:--key=value 或 --key value
local key, value = arg:match("^%-%-([^=]+)=(.+)$")
if key then
-- --key=value 格式
config[key] = value
i = i + 1
else
-- --key value 格式
key = arg:sub(3)
if i + 1 <= #args and args[i + 1]:sub(1, 1) ~= "-" then
config[key] = args[i + 1]
i = i + 2
else
-- 布尔标志
config[key] = true
i = i + 1
end
end
elseif arg:sub(1, 1) == "-" and #arg > 1 then
-- 短参数格式:-k value
local key = arg:sub(2)
if i + 1 <= #args and args[i + 1]:sub(1, 1) ~= "-" then
config[key] = args[i + 1]
i = i + 2
else
-- 布尔标志
config[key] = true
i = i + 1
end
end
-- 忽略其他未识别的参数
i = i + 1
end
return config
end
---将字符串转换为适当的类型
---@param value string 输入值
---@return boolean|number|string 转换后的值
local function convert_type(value)
-- 尝试转换为数字
local num = tonumber(value)
if num then
return num
end
-- 尝试转换为布尔值
if value == "true" then
return true
elseif value == "false" then
return false
end
-- 保持为字符串
return value
end
---解析命令行参数(带类型转换)
---@param args string[] 参数列表
---@return table<string,number|string|boolean> config 解析后的配置对象
local function parse_args_typed(args)
local config = parse_args(args)
-- 转换值类型
for key, value in pairs(config) do
if type(value) == "string" then
config[key] = convert_type(value)
end
end
return config
end
-- 返回解析函数供其他脚本使用
local _M = {
parse = parse_args,
parse_typed = parse_args_typed,
}
return _M