function LoadLevel()
num_moves=0
levelnum = tostring(level)
map=string.format("%s%s", "./levels/", levelnum)
map=string.format("%s%s", map, ".lua")
if(io.open(map, r)==nil) then --open the file first to make sure it's there
level=1 --wrap back to start
gamefield=nil
screen.waitVblankStart(60) --short delay
LoadLevel(1) --call yourself to load first level since we ran out.
io.close()
else -- yep it's there better close it
io.close()
gamefield=nil
if(level~=1) then
screen.waitVblankStart(60) --short delay
end
dofile(map)
mappos=StartupPosition()
return 1
end
end
This is my load level code which works perfectly for the first 10 times.
My game will always crash on the 11th time dofile is called. It's not the specific 11th file because I've changed that to one that works for a previous load.
error: cannot read ./levels/11.lua
Error: No script file found.
file, msg = io.open(name, "r")
if not file then print(msg) end
and they are not even closing the io.open again...
I think files are GC'ed and then closed automaticly, but should be better to close it. If you open too many files and they are not GC'ed, opening the next file will cause an error.
I'm using this for loading and saving the options in Snake, which are all strings, except "speed", which results in the hack in loadOptions :-)
options = { speed = 2, level = "desert", music = "on", sound = "on" }
function saveOptions()
file = io.open(optionsFile, "w")
if file then
for key, value in options do
file:write(key .. "=" .. value .. "\n")
end
file:close()
end
end
function loadOptions()
file = io.open(optionsFile, "r")
if file then
for line in file:lines() do
equal = string.find(line, "=")
if equal then
key = string.sub(line, 1, equal - 1)
value = string.sub(line, equal + 1)
if key == "speed" then value = tonumber(value) end
options[key] = value
end
end
file:close()
end
end