How to read a file in the same script directory using Lua

Asked

Viewed 388 times

1

I’m trying to make a small script, but I’m facing some difficulties

local lab = nil
local f = io.open("/input-lab.txt", "r")
print(f)

I wanted to open a file that is in the same directory as the script and be able to read its data, let’s say input-lab.txt had the following data

111101
100001
101101
101001
101111

So I wanted this file somehow and to be able to generate a string based on it kind

"111101\n100001\n101101\n101001\n101111"

But I can’t get the script to read the file in the same directory, how do I do this?

  • 2

    in the directory where the script is, or in the current directory ? if it is in the current directory is easy, just put "input-lab.txt" or ". /input-lab.txt"...if it is specifically in the script directory I think there is no easy way (remember that you can be in the /x/y/x directory and the script is in the /a/b/c directory)

  • what would be the current directory is as I know?

1 answer

2


You can do it:

for linhas in io.lines("input-lab.txt") do
    print(linhas)
end

or

local f = "input-lab.txt"

for linhas in io.lines(f) do
    print(linhas)
end

or

local f = io.lines("input-lab.txt")

for linhas in f do
    print(linhas)
end

They will all return:

111101
100001
101101
101001
101111

if this file is in a put folder

pastadoarquivo/arquivo.txt
ou pastadoarquivo/outrapasta/arquivo.txt

Browser other questions tagged

You are not signed in. Login or sign up in order to post.