I refactored property.lua a bit, but like the old one, you only save name, value pairs (not game objects). You use it like this:
props = Properties:new("myGame.settings") -- create/open myGame.settings
props:set("Sound", "On") -- set the Sound property to On
props:debug() -- print out the properties table
props:saveToFile() -- write myGame.settings
props:get("Sound") -- get the value of the Sound property
Include Properties.lua in your project folder and test in the Simulator. I put a print statement in the constructor that reveals the location of your file.
[code]
Properties = {}
Properties.__index = Properties
local function doesFileExist(theFile)
local datafile = io.open(theFile)
if datafile == nil then
return false
else
datafile:close()
return true
end
end
local function explode(d,p)
local t, ll
t={}
ll=0
if(#p == 1) then return {p} end
while true do
l=string.find(p,d,ll,true)
if l~=nil then
table.insert(t, string.sub(p,ll,l-1))
ll=l+1
else
table.insert(t, string.sub(p,ll))
break
end
end
return t
end
function Properties:new(filename)
local properties = {}
setmetatable(properties, Properties)
properties.kvMap={}
properties.filePath = system.pathForFile(
filename or “defaults”,
system.DocumentsDirectory
)
print(properties.filePath)
– what if it doesn’t exist???
if doesFileExist(properties.filePath) then
properties:getFromFile()
end
return properties
end
function Properties:debug()
for k,v in pairs(self.kvMap) do
print(" --> " … k … " = " … v)
end
end
function Properties:saveToFile()
local datafile, errStr
datafile, errStr = io.open(self.filePath, “w+”)
if not errStr == nil then
print(“Error occurred”)
end
print("saving to file " … self.filePath … “…”)
for k,v in pairs(self.kvMap) do
datafile:write(k … “=” … v … “\n”)
end
datafile:close()
end
function Properties:getFromFile()
local theLine, theLineValue
local datafile, errStr, line
datafile, errStr = io.open(self.filePath)
if datafile == nil then
print(“err " … errStr)
return nil
else
for line in datafile:lines() do
theLine = explode(”=" , line)
self:set(theLine[1] , theLine[2])
end
datafile:close()
end
end
function Properties:set(name, value)
self.kvMap[name] = value
end
function Properties:get(name, defaultValue)
local defaultValue = defaultValue or “”
if self.kvMap[name] == nil then
self.set(name, defaultValue)
end
return self.kvMap[name]
end
[/code] [import]uid: 58455 topic_id: 12352 reply_id: 45242[/import]