Search code examples
iolua

Reading/writing a properties file with lua


In java i'm used to using the built in classes for reading and writing properties files but something similar doesn't exist for lua.

Whats the simplest way to save a name and a value to file and then get the value back using the name?


Solution

  • The simplest way would be something like this:

    local name, value = "abc", 123
    local f = io.open("outfile", "w")
    f:write("return {" .. name .. " = " .. value .. "}")
    f:close()
    
    ---
    
    local t = dofile("outfile")
    print( t[name] )
    --> 123
    

    This works, but isn't very secure as dofile() just executes whatever Lua code it finds in the file. If the file returns a table full of your saved values as it does here then it works just great, but someone could easily edit this file to contain os.execute("sudo rm -rf /") or other such delightful fun.

    It's possible to make this more robust with judicious use of setfenv() and debug.sethook(), but if you want to do it properly you should use one of the many serialisation libraries for Lua, a selection of which can be found here.