You can do this to load (uses last post saving system):
Code: Select all
function loadData()
if love.filesystem.exists("savedata.txt") then
local txt = love.filesystem.read("savedata.txt")
local s = txt:split(";")
for i = 1, #s do
local s2 = s[i]:split(" = ")
local value = s2[2]
if value == "true" then
value = true
elseif value == "false" then
value = false
elseif value == "nil" then
value = nil
elseif tonumber(value) then
value = tonumber(value)
end
_G[s2[1]] = value
end
end
end
This would require the string:split function (not by me):
Code: Select all
function string:split(delimiter)
local result = {}
local from = 1
local delim_from, delim_to = string.find( self, delimiter, from )
while delim_from do
table.insert( result, string.sub( self, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( self, delimiter, from )
end
table.insert( result, string.sub( self, from ) )
return result
end
But I think it'd be better if you use lua as your main form of saving-loading data:
To save them, you can do this:
Code: Select all
function saveData(t) --t is a table of variables names, like {"speed", "gravity", "mapname"}
local s = ""
for i = 1, #t do
s = s .. t[i] .. " = "
if type(_G[t[i]]) == "table" then
s = s .. tabletostring(t[i])
elseif type(_G[t[i]]) == "string" then
s = s .. "\"" .. _G[t[i]] .. "\""
else
s = s .. tostring(_G[t[i]])
end
if i ~= #t then
s = s .. "\r\n"
end
end
love.filesystem.write("savedata.lua", s)
end
And the table-to-string function:
Code: Select all
function tabletostring(t)
local t = t
if type(t) == "string" then
t = _G[t]
end
local ret = "{"
for i, v in pairs(t) do
if type(i) ~= "number" then
ret = ret .. i .. " = "
end
if type(v) == "table" then
ret = ret .. tabletostring(v)
elseif type(v) == "string" then
ret = ret .. "\"" .. v .. "\""
else
ret = ret .. tostring(v)
end
ret = ret .. ", "
end
return string.sub(ret, 1, -3) .. "}"
end
To load, you have two ways: "require" at your code's beginning:
Or later, with [wiki]love.filesystem.load[/wiki]:
Code: Select all
local chunk = love.filesystem.load("savedata.lua")
chunk()