Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make LUA script read my config file

Tags:

config

lua

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

like image 201
akram Avatar asked Sep 03 '25 03:09

akram


2 Answers

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.

like image 123
Moop Avatar answered Sep 05 '25 01:09

Moop


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

like image 31
Wine93 Avatar answered Sep 05 '25 01:09

Wine93