我想让 lua 脚本读取自定义配置文件
personal.txt
[user4]
id=1234
code=9876
[user3]
id=765
code=fh723
Run Code Online (Sandbox Code Playgroud)
所以我可以读取或写入数据
您可以使用 lua 模块进行配置:
-- config.lua
local _M = {}
_M.user3 = {
id = 765,
code = "fh723",
}
_M.user4 = {
id = 1234,
code = "9876",
}
return _M
Run Code Online (Sandbox Code Playgroud)
-- main.lua
local config = require "config"
print (config.user3.id)
print (config.user3.code)
print (config.user4.id)
print (config.user4.code)
-- Also you can edit the module table
config.user4.id = 12345
print (config.user4.id)
Run Code Online (Sandbox Code Playgroud)
输出:
765
fh723
1234
9876
12345
为此,您应该使配置文件成为 Lua 兼容格式:
--personal.txt
user4 = {
id=1234,
code=9876,
}
user3 = {
id=765,
code=fh723,
}
Run Code Online (Sandbox Code Playgroud)
然后您可以使用加载文件loadfile并传入自定义环境以将内容放入:
local configEnv = {} -- to keep it separate from the global env
local f,err = loadfile("personal.txt", "t", configEnv)
if f then
f() -- run the chunk
-- now configEnv should contain your data
print(configEnv.user4) -- table
else
print(err)
end
Run Code Online (Sandbox Code Playgroud)
当然,有多种方法可以做到这一点,这只是一种简单且相对安全的方法。