How can I catch the values in changed config file

229 Views Asked by At

I have caught the value in the config file like this:

file = io.open("testch", "r") -- testch is config file in same directory
file:read("*l")

file:seek("cur", 17)
version = file:read("*l")
_, _, version = string.find(version, "(%d+.%d+)'")

file:seek("cur", 19)
serialnum = file:read("*l")
_, _, serialnum = string.find(serialnum, "(%d+)'")

file:seek("cur", 15)
power = file:read("*l")
_, _, power = string.find(power, "(%d+)'")

io.close(file)

/* below code is config file in the same directory with upper one */
config test
       option version '1.0'
       option serialnum '1234567890'
       option power '30'

However, when I click the Save&Apply button in the Luci for changing the value in config file, the changed array goes to below.

That's my problem. When config file's array order is changed, my solution can't apply in that case. (My solution can be applied in fixed case.)

Is there a solution that can apply to every case(with config file's array is changed case)?

1

There are 1 best solutions below

1
On

My personal preference would be to use Lua as a configuration language. It is very simple to accomplish when using Lua already; it allows you to use a Turing-complete language and user-defined libraries for advanced configuration; and totally avoids the problems you are having.

Simply reformat your config file to be valid Lua and use loadfile() to load the config file as a chunk, and execute if there are no issues. The variable s in the below code is the environment in which the Lua config file will execute. Giving it an empty table means you pass nothing for the configuration script to use (no table library, pairs() function, etc.). You can pass in your own environment table (ENV), but that is considered incredibly unsafe, as the config script could overwrite your environment causing breakages in new and hard-to-track ways, or allow an attacker to run malicious code. The best thing to do is to create the configuration environment anew according to the needs of the configuration script. And make sure to sanitize your inputs! Don't trust the user to not be idiotic or evil.

config:

version = '1.0'
serialnum = '1234567890'
power = '30'

load.lua:

local s = {}
assert(loadfile("config", "t", s))()

print(s.version)
print(s.serialnum)
print(s.power)