Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

How to load host.conf file variables in lua script

I need to load configuration variables from .conf file in lua script, and use those variables to connect to a database. I have tried using:

require "host.conf"
loadfile("host.conf") - error with unexpected token '#' 
os.execute("pathToConfFile/host.lua") - and I have created a lua host file with variables in bash shell
io.popen("host.conf") etc..

None of these solutions are valid. Is there a way to use the existing host.conf file in lua, and avoid the unexpected token error? Thank you for your suggestions.

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
local original = io .open('host.conf')
local hostconf = {}  --  copy contents into Lua table

for line in original :lines() do
    table .insert( hostconf, line )
end ; io .close( original )

print( hostconf[1] )  --  prints line 1

You haven't specified what format your host.conf comes in, but you'll likely want to parse it better than just throwing contents in a list. Perhaps splitting each line into head / tail, based upon a delimiter ( comma, space, whatever you have between variable & value )

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share