0

I'm new to the Lua I/O, but have been using Lua elsewhere for almost two years now. I have this line:

for line in io.lines("myfile.txt") do

but it always results in a "No such file or directory" error. "myfile.txt" is in the same directory as the Lua file.

Where should I put the file "myfile.txt"?

2 Answers 2

3

for line in io.lines(assert(io.open("myfile.txt"))) do

-- The lines function accepts a file in its argument, while on the other hand, open accepts a string and returns the file.

Sign up to request clarification or add additional context in comments.

2 Comments

Wait, now it gives me "Bad argument #1 - string expected, got userdata."
Nevermind - I used io.lines() and set the default input before with io.input("myfile.txt").
0

I had same problem but fixed it with the following code - This code demonstrates iteration with io.open ...

function getHostnameFromHostFile(ip)
    local hostName = "unknown";
    local hostFile = io.open("/etc/hosts");

    for line in hostFile:lines() do
        if line and string.find(line, ip) then
            hostName = line:match("[a-zA-Z][a-zA-Z0-9]+");
        end
    end
    return hostName;
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.