I have a function to check the contents of the folder:
function fileExists(theFile) local filePath = system.pathForFile(theFile, system.TemporaryDirectory) local results = false if filePath == nil then return false else local file = io.open(filePath, "r") --If the file exists, return true if file then io.close(file) results = true end return results end end
but to be honest, this involves already knowing which files you want to look for.
If it was me, I would have a json table which holds the numbers of each level
e.g.
{"1":1, "2":2, "3":3, ...etc..., "50":50}
Decode that to a Lua table:
loadFile = function( filename, base ) -- set default base dir if none specified if not base then base = system.DocumentsDirectory; end -- create a file path for corona i/o local path = system.pathForFile( filename, base ) -- will hold contents of file local contents -- io.open opens a file at path. returns nil if no file found local file = io.open( path, "r" ) if file then -- read all contents of file into a string contents = file:read( "\*a" ) io.close( file ) -- close the file after using it else print("defaulting to ResourceDirectory") jsonDefaulted = true local path2 = system.pathForFile( filename, system.ResourceDirectory ) local file2 = io.open(path2, "r") if file2 then contents = file2:read( "\*a" ) io.close (file2) end end return contents end local myTable = json.decode(loadFile("myData.json", system.DocumentsDirectory ))
and then when you want to choose a level just pick one of them at random as you said before. I would use math.randomseed(os.time()) to make it more randomised:
math.randomseed(os.time()) local myLevelNum = math.random(1, #myTable)
This would give you a number from 1, 50
Lets’s say it returned 34, so now you can go to level 34. However it sounds like you don’t want to be able to pick level 34 again? No problem, just remove number 34 from the table (and resave to the json file if it needs to be permanently removed from play).
table.remove(myTable, myLevelNum)
saveData = function(saveTable, fileName)
local savePath = system.pathForFile(fileName, system.DocumentsDirectory )
local saveFile = io.open(savePath, “w”)
saveFile:write(json.encode(saveTable))
io.close(saveFile)
print("Saved "…fileName)
end
saveData(myTable, myData.json)
The next time you call math.random, the lua table will not have number 34 in it. The next time the app is started, the json file will also not have the number 34 in it.
I’m not sure if this is exactly what you were after, but hopefully it helps.