Configuration – Using Lua for Writing Config Files

anti-patternsconfigurationlua

I heard that Lua is great for configuration files, so long as you are secure about it. Lua has been used as config files by programs such as awesome and (recently) conky.

However, I also heard that using programming to configure a program is an anti-pattern.

Since Lua does not get compiled as part of the program, would this prove as an exception?

Here's a hint of what Lua might look like as a config file:

return {
  rootdir = "/abc/123",
  debug = true,
  things = {
    "foo",
    "bar",
    "baz",
    "qux"
  }
}

Best Answer

The needs for any language that you use for configuration files are the same, regardless of whether it is a programming language or not:

  1. The people who use it can do so reasonably effectively. If actual human beings aren't writing them, then it needs to be readable by programs. And possibly debugged by programmers.

    Lua's table syntax was actually derived from an older configuration file format, so it is equally as effective as JavaScript for this purpose (what do you think JSON is?). It's about as self-documenting as such things, with comments and so forth.

  2. Improper configuration files should not break your program. Or worse, hijack it. It's very easy to sandbox a Lua state, in that you have to do actual work in order to make a Lua state do something.

    However, the biggest thing you need to worry about is a pre-compiled Lua script breaking your encapsulation. Which means you need a mechanism to prevent loading pre-compiled Lua scripts as config files. Lua 5.2 and above provide this. For Lua 5.1, if you don't take special care, you can create a gaping security hole in your program.

  3. Reading/writing the file needs to be reasonably easy for code. Lua's table interface can be a bit wordy, but with a couple of wrapper functions, it should be no problem to deal with it.

  4. If errors show up in the file, you should be able to give a reasonable error message. Lua's parser is not the greatest, but it's not terrible at giving error messages.

That being said, given the number of XML and JSON parsers out there, I wouldn't bother using "LON" as a configuration language unless my program already incorporated Lua in some other way.

Related Topic