Skip to content

Instantly share code, notes, and snippets.

@shyim
Created November 8, 2015 00:21
Show Gist options
  • Save shyim/9e2ccfa6437c4677ee89 to your computer and use it in GitHub Desktop.
Save shyim/9e2ccfa6437c4677ee89 to your computer and use it in GitHub Desktop.
Ini Reading for MTA
EasyIni = {}
EasyIni.__index = EasyIni
function EasyIni:loadFile(filename)
local self = setmetatable({}, EasyIni)
self.filename = filename
self.sections = {}
if not fileExists(filename) then
error("EasyIni: Couldn`t found the ini file "..filename)
return false
end
local file = fileOpen(filename)
local fileSize = fileGetSize(file)
local data = {}
if(fileSize > 0) then
local fileContent = fileRead(file, fileSize)
local fileContentAsLine = split(fileContent, "\n")
local lastSection = "root"
for _, row in pairs(fileContentAsLine) do
if string.match(row, "^%[(.+)%]$") then
lastSection = string.match(row, "^%[(.+)%]$")
if(not data[lastSection]) then
data[lastSection] = {}
table.insert(self.sections, lastSection)
end
elseif not string.match(row, ";$") then
local rowSplit = split(row, "=")
local rowSplitLength = table.getn(rowSplit)
if(rowSplitLength == 2) then
data[lastSection][rowSplit[1]] = rowSplit[2]
elseif(rowSplitLength > 2) then
local str = "";
local isFirst = true
for _,v in pairs(rowSplit) do
if(isFirst) then
isFirst = true
else
str = str .. v .. "="
end
end
str = string.sub(str, 0, -1)
data[lastSection][rowSplit[1]] = str
end
end
end
end
fileClose(file)
self.data = data
return self
end
function EasyIni:newFile(filename)
local self = setmetatable({},EasyIni)
self.data = {}
self.filename = filename
self.sections = {}
return self
end
function EasyIni:get(selection,name)
if self.data[selection] then
if self.data[selection][name] then
return self.data[selection][name]
else
return false
end
else
return false
end
end
function EasyIni:set(selection,name,value)
if not self.data[selection] then
self.data[selection] = {}
table.insert(self.sections, lastSection)
end
self.data[selection][name] = value
return true
end
function EasyIni:getAvailableSections()
return self.sections
end
function EasyIni:getAvailableSectionKeys(section)
local returnTable = {}
if(self.data[section]) then
for k,_ in pairs(self.data[section]) do
table.insert(returnTable, k)
end
return returnTable
else
return false
end
end
function getSection(section)
if(self.data[section]) then
return self.data[section]
else
return false
end
end
function EasyIni:save()
local string = ""
for selection,selectiontable in pairs(self.data) do
string = string.."["..selection.."]\n"
for k,v in pairs(selectiontable) do
string = string..k.."="..v.."\n"
end
end
local file = fileCreate(self.filename)
fileWrite(file,string)
fileClose(file)
return true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment