I want make lua script read custom config file
personal.txt
[user4]
id=1234
code=9876
[user3]
id=765
code=fh723
so i can read or write data
To do this, you should make the config file a Lua compatible format:
--personal.txt
user4 = {
id=1234,
code=9876,
}
user3 = {
id=765,
code=fh723,
}
Then you can load the file using loadfile
and pass in a custom environment to place the contents into:
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
Of course, there are multiple ways to do this, this is just a simple, and relatively safe way.
You can use lua module to make your config:
-- config.lua
local _M = {}
_M.user3 = {
id = 765,
code = "fh723",
}
_M.user4 = {
id = 1234,
code = "9876",
}
return _M
Then you can require the module, and use the field in module table as you like:
-- 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)
Output:
765
fh723
1234
9876
12345
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With