rpcabrera
rpcabrera

Reputation: 15

Reading text files in Lua

I am sorry for a duplicate post or something. I am just trying to confirm this one because I have seen similar post and did the same yet my output is not what i wanted to be the problem is to read a text file in Lua language. Here's my code:

   function fileExists(filename)
         file = io.open(filename, "r")
         if file == nil then
              return false
         else
              return true
         end
   end

  if fileExists ("myFile.txt") then
            print ("Hello")
  else
            print("not found")
  end

It keeps returning false and print not found. And also am trying to open a .lrc file instead of .txt. What is wrong with that simple, little lines of code?

Upvotes: 1

Views: 6102

Answers (2)

Andrew Filonov
Andrew Filonov

Reputation: 46

Your code is ok, except for the file closing part:

     file = io.open(filename, "r")
     if file == nil then
          return false
     else
          file.close(file)
          return true

Do you really have the file myFile.txt in current directory?

%ls -l
-rwxr--r--  1 aef  wheel  324 23 апр 10:24 a.lua
-rw-r--r--  1 aef  wheel    0 23 апр 10:16 myFile.txt
%lua-5.1 a.lua
Hello

Upvotes: 3

hjpotter92
hjpotter92

Reputation: 80649

If you're opening a .lrc file, and providing the filename as .txt it will give an error. I tried your program on a custom .ps1 file of mine, in the parent folder to the lua file, and it worked fine.Check for yourself

Upvotes: 0

Related Questions