Let's get started!
Most people don't really realize how textutils api powerful is, especially serialize function. We are going to use it.
[right]textutils.serialize() turns table into Lua code.[/right]
We are going to store config in table, we will call it 'config' for this tutorial.
Let's create our config first:
local function saveConfig(table, file)
-- Open config file in write mode
-- If failed, create error on level 2, will point to line of code from which function is called
local fConfig = fs.open(file, "w") or error("Cannot open file "..file, 2)
-- Write serialized table to config file
fConfig.write(textutils.serialize(table))
-- Save and close file
fConfig.close()
end
And test it:
saveConfig({1, 2, 3, ['herp'] = 'derp'}, "test")
Output will look like this:
{[1]=1,[2]=2,[3]=3,["herp"]="derp",}
Now, let's load config:
local function loadConfig(file)
-- Open config file in read mode
local fConfig = fs.open(file, "r")
-- Read whole file and unserialize it
local ret = textutils.unserialize(fConfig.readAll())
-- Close file
fConfig.close()
-- Return table
return ret
end
Test it:
local config = loadConfig("test")
print(config[1])
print(config[2])
print(config.herp)
Output:
1
2
derp
Full code:
local function saveConfig(table, file)
-- Open config file in write mode
-- If failed, create error on level 2, will point to line of code from which function is called
local fConfig = fs.open(file, "w") or error("Cannot open file "..file, 2)
-- Write serialized table to config file
fConfig.write(textutils.serialize(table))
-- Save and close file
fConfig.close()
end
local function loadConfig(file)
-- Open config file in read mode
local fConfig = fs.open(file, "r")
-- Read whole file and unserialize it
local ret = textutils.unserialize(fConfig.readAll())
-- Close file
fConfig.close()
-- Return table
return ret
end
saveConfig({1, 2, 3, ['herp'] = 'derp'}, "test")
local config = loadConfig("test")
print(config[1])
print(config[2])
print(config.herp)
So, here you go, configs are easy now!