Lua写配置文件

来源:互联网 发布:淘宝达人帖子范文 编辑:程序博客网 时间:2024/05/29 02:11
zc = 
{
configTest = 
   {
sub = {A = 0, B = 1},
str = "I'm string!",
num = 4,
},

debug = false,
}

pcall(loadfile('luaConfig.lua'))

function write_table_to_file(prefix, tbl, luaConfig)
   luaConfig = luaConfig or nil
   local do_close = false
   if luaConfig == nil then
      luaConfig = io.open('luaConfig.lua', 'w')
      do_close = true
   end
   for key,val in pairs(tbl) do
      if type(val) == 'table' then
        write_table_to_file(prefix .. '.' .. tostring(key), val, luaConfig)
      else
         if type(val) == 'string' then
            val = '"' .. val .. '"'
         end
         msg = string.format('%s = %s', prefix .. '.' .. tostring(key), tostring(val) .. '\n')
         luaConfig:write(msg)
      end
   end
   if do_close then
      luaConfig:close()
      luaConfig = nil
      print(luaConfig)
   end
end

zc.debug = true

write_table_to_file('zc', zc)