It is currently June 26th, 2019, 10:55 pm

ReadIni and WriteIni - Preserving Order

Discuss the use of Lua in Script measures.
User avatar
raiguard
Posts: 631
Joined: June 25th, 2015, 7:02 pm
Location: The Sky, USA

ReadIni and WriteIni - Preserving Order

raiguard » July 2nd, 2016, 1:37 am

So I'm attempting to utilize the ReadIni and WriteIni functions that jsmorley wrote, but have run into a major problem: When storing the values in a table, they become unordered. This means that when I use WriteIni to write those values to another file, they are written in a random order.

I actually already have a solution for this: To nest each 'section = {key=value}' pair inside its own table, to nest every 'key=value' pair inside of its own table as well, and iterate using ipairs. But this makes the tables extremely messy and unnecessarily complicated.

For example, it turns

Code: Select all

exampleTable = {
	Variables = {
		var1 = 'foo',
		var2 = 'bar'
	}
}
into

Code: Select all

exampleTable = {
	{ Variables = {
		{ var1 = 'foo' },
		{ var2 = 'bar'}
		}
	}
}
Yeah, that's ugly.

So is there a better way to do it? The original functions are included below.

Code: Select all

function ReadIni(inputfile)
	local file = assert(io.open(inputfile, 'r'), 'Unable to open ' .. inputfile)
	local tbl, section = {}
	local num = 0
	for line in file:lines() do
		num = num + 1
		if not line:match('^%s-;') then
			local key, command = line:match('^([^=]+)=(.+)')
			if line:match('^%s-%[.+') then
				section = line:match('^%s-%[([^%]]+)'):lower()
				if not tbl[section] then tbl[section] = {} end
			elseif key and command and section then
				tbl[section][key:lower():match('^s*(%S*)%s*$')] = command:match('^s*(.-)%s*$')
			elseif #line > 0 and section and not key or command then
				print(num .. ': Invalid property or value.')
			end
		end
	end
	if not section then print('No sections found in ' .. inputfile) end
	file:close()
	return tbl
end

function WriteIni(inputtable, filename)
	assert(type(inputtable) == 'table', ('WriteIni must receive a table. Received %s instead.'):format(type(inputtable)))

	local file = assert(io.open(filename, 'w'), 'Unable to open ' .. filename)
	local lines = {}

	for section, contents in pairs(inputtable) do
		table.insert(lines, ('\[%s\]'):format(section))
		for key, value in pairs(contents) do
			table.insert(lines, ('%s=%s'):format(key, value))
		end
		table.insert(lines, '')
	end

	file:write(table.concat(lines, '\r\n'))
	file:close()
end
”We are pretty sure that r2922 resolves the regression in resolution caused by a reversion to a revision.” - jsmorley, 2017