如何让LUA脚本读取我的配置文件

时间:2016-12-16 03:19:21

标签: lua config

我想让lua脚本读取自定义配置文件

personal.txt

[user4]
id=1234
code=9876

[user3]
id=765
code=fh723

所以我可以读取或写入数据

3 个答案:

答案 0 :(得分:3)

您可以使用lua模块进行配置:

-- config.lua

local _M = {}

_M.user3 = {
    id = 765,
    code = "fh723",
}

_M.user4 = {
    id = 1234,
    code = "9876",
}

return _M

然后您可以require模块,并根据需要使用模块表中的字段:

-- 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)

<强>输出:

  

765
  fh723
  1234
  9876
  12345

答案 1 :(得分:2)

为此,您应该使配置文件成为Lua兼容格式:

--personal.txt

user4 = {
  id=1234,
  code=9876,
}

user3 = {
  id=765,
  code=fh723,
}

然后您可以使用loadfile加载文件并传入自定义环境以将内容放入:

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

当然,有多种方法可以做到这一点,这只是一种简单而且相对安全的方式。

答案 2 :(得分:0)

这是一种可能性。 (警告:未经100%测试,但似乎有效。) 您可以读取/写入任何此类文件,并根据哪些参数为零来添加,更新或删除条目。

--==============================================================================

local
function file_exists(path)
  local f = io.open(path)
  if f == nil then return end
  f:close()
  return path
end

--------------------------------------------------------------------------------
-- Read the whole configuration in a table such that each section is a key to
-- key/value pair table containing the corresponding pairs from the file.

function read_config(filename)
  filename = filename or ''
  assert(type(filename) == 'string')
  local ans,u,k,v,temp = {}
  if not file_exists(filename) then return ans end
  for line in io.lines(filename) do
    temp = line:match('^%[(.+)%]$')
    if temp ~= nil and u ~= temp then u = temp end
    k,v = line:match('^([^=]+)=(.+)$')
    if u ~= nil then
      ans[u] = ans[u] or {}
      if k ~= nil then
        ans[u][k] = v
      end
    end
  end
  return ans
end

--------------------------------------------------------------------------------
-- When all three parametes are nil, no action at all.
-- When both key and value are nil but section is not, delete section.
-- When only value is nil, delete key value pair for given section.

function write_config(filename,section,key,value)
  filename = filename or ''
  assert(type(filename) == 'string')
  if section == nil and key == nil and value == nil then return end
  local t = read_config(filename)       -- read existing configuration, if any

  if section ~= nil and value == nil then
    if key == nil then
      t[section] = nil                  --eliminate whole section
    else
      t[section][key] = nil             --eliminate key/value pair
    end
    goto WriteFile
  end

  if key:match '=' then
    error('An equals sign is not expected inside key')
  end

  t[section] = t[section] or {}         --create section if not present
  t[section][key] = value               --update key value

::WriteFile::                           -- write to file
  local fo = io.open(filename,'w')
  for k,v in pairs(t) do
    fo:write('['..k..']\n')
    for k,v in pairs(v) do
      fo:write(k..'='..v..'\n')
    end
    fo:write('\n')
  end
  fo:close()

  return t                              --return updated configuration table
end

--==============================================================================

--------------------------------------------------------------------------------
-- Example use
--------------------------------------------------------------------------------

f = 'personal.txt'                                --file to use

write_config(f,'user2','id','my_id')              --update key value pair
write_config(f,'user2','name','noone')            --add key value pair
write_config(f,'user3','id','818')                --update key value pair
write_config(f,'user3','xxx','whatever')          --add key value pair
write_config(f,'newuser','id','54321')            --create new user
write_config(f,'newuser','xxx','54321')           --create new key/value pair
write_config(f,'newuser','xxx')                   --remove key/value pair
write_config(f,'newuser')                         --remove section