如何让 LUA 脚本读取我的配置文件

use*_*431 2 lua config

我想让 lua 脚本读取自定义配置文件

personal.txt

[user4]
id=1234
code=9876

[user3]
id=765
code=fh723
Run Code Online (Sandbox Code Playgroud)

所以我可以读取或写入数据

Win*_*e93 6

您可以使用 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

  • 使用模块和 require 而不是 loadfile 的缺点是 require 缓存 package.loaded 表中的值。因此,如果 config.lua 更改,则不会反映在对 require("config") 的新调用中 (2认同)

Moo*_*oop 5

为此,您应该使配置文件成为 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)

当然,有多种方法可以做到这一点,这只是一种简单且相对安全的方法。