I am using JSON files to store tile IDs which I use for rendering my game world. I store my JSON files in a subfolder of my main project folder and I load the file with the function shown below. When I open my app in the simulator by double clicking main.lua directly from file explorer, it runs great, but when I open Corona Simulator and select my project from there or build my project and run it on my testing device, it gives me a null reference error when I attempt to use the data I loaded.
Here is the function to load a table from a JSON file:
function fileIO.loadJSONFile (fileName) local path = fileName local contents = "" local loadingTable = {} local file = io.open (path, "r") if file then local contents = file:read ("\*a") loadingTable = json.decode (contents) io.close (file) return loadingTable end return nil end
Here is the usage (the way I render my tiles shouldn’t matter, so that part can pretty much be ignored. I have marked the important lines in large letters :P):
function wr:renderChunkFile (path) local data = fileIO.loadJSONFile (path) --DATA IS LOADED HERE self:renderChunk (data) end function wr:renderChunk (data) local a, b = 1 if (self.img ~= nil) then a = #self.img + 1 self.img[a] = {} else self.img[1] = {} end if (self.chunks ~= nil) then b = #self.chunks + 1 self.chunks[b] = display.newGroup () else self.chunks[1] = display.newGroup () end for i = 1, #data do -- Y axis ERROR IS THROWN HERE self.img[a][i] = {} for j = 1, #data[i] do -- Z axis self.img[a][i][j] = {} for k = 1, #data[i][j] do -- X axis if (data[i + 1] ~= nil) then if (data[i + 1][j][k] \< self.transparentLimit) then self.img[a][i][j][k] = display.newImage ("images/tiles/"..data[i][j][k]..".png", k\*self.tileWidth, display.contentHeight -j\*self.tileDepth - i\*self.tileThickness) self.chunks[b]:insert (self.img[a][i][j][k]) elseif(data[i + 1] == nil) then self.img[a][i][j][k] = display.newImage ("images/tiles/"..data[i][j][k]..".png", k\*self.tileWidth, display.contentHeight -j\*self.tileDepth - i\*self.tileThickness) self.chunks[b]:insert (self.img[a][i][j][k]) end end end end end end
When it gets to the line “for i = 1, #data do” it tells me it is trying to access the length of a nil field. My initial thought was that maybe my file names are incorrect for the Android operating system, so I made all my folders completely alphabetical, but this had no effect. I was also thinking that maybe APK files had a nesting limit on resource folders, so I brought all my resources to the root project folder and that still had no effect. Where did I go wrong here?