wongkj
wongkj

Reputation: 33

Trouble reading txt file in Love2D

I am trying to read from a txt file in Lua, as shown below (main.lua):

local function read_file(filename)
    contents = io.open(filename, "r")
    if contents == nil then
        return false
    else
        io.close(contents)
        return true
    end
end

if read_file("myfile.txt") then
    print("Yes")
else
    print("Not found")
end

However, it keeps returning "Not found" even though myfile.txt is in the same directory as main.lua. I am currently using Lua with Love2D engine.

Upvotes: 1

Views: 850

Answers (1)

Aki
Aki

Reputation: 2938

While you might be tempted to use Lua's io in LÖVE I would suggest against it.

LÖVE has it's own love.filesystem. Consider:

if love.filesystem.getInfo("myfile.txt") then
   print("Yes")
   print(love.filesystem.read("myfile.txt"))
else
   print("Not found")
end

Behaviour of the love.filesystem is consistent between platforms supported by LÖVE and, in short, for selected operations it is:

  • Write/append - path of the file is relative to the save directory.
  • Read - path is first resolved against the save directory. If nothing is found then path is resolved against the content of the love archive or (if applicable) the source directory.

Save directory is a special directory for use of your application. In case of doubts, please refer to LÖVE's wiki.

As for why the example from the question might not be working - please see Egor's comment.

Upvotes: 4

Related Questions