fileluapathiolove2d

Can't read file in Lua after I moved the .love file elsewhere


So I zipped my Love2D project and it works when I launch it in the same folder, but elsewhere my io.open doesn't work. Here's my file system:

...
utils
   |json.lua  <-- library I use for encoding and decoding
   |JSONHandler.lua
   |parameters.json
conf.lua
main.lua
...

I get my error in JSONHandler.lua where I have:

local json = require "utils/json"

Handler = {
   filename = "utils/parameters.json",
   params = {},
   ...
}

function Handler:init()
   local o = {}
   setmetatable(o, self)
   self.__index = self

   local file = io.open(self.filename, "r")
   local content = file:read("a")
   ...

My file ends up being nil

I tried many different relative paths for filename but nothing worked so I'm wondering how .love files handle paths, how should I track to my parameters.json?


Solution

  • It probably works when you do not move the .love file because it still has access to the original files from the working directory.

    Lua can not read content in zip files out of the box, but Love2d offers love.filesystem.

    It also has file wrappers, but if you just want to read the content prefer read:

    local content = love.filesystem.read(self.filename)
    

    Note that you can only read files in the love zip, in the working directory and in the save directory.