user1632861
user1632861

Reputation:

Lua file reading and writing error

Sorry if there's already a topic like this, but I couldn't find any that have something to do with Lua... So I'm basically having some problems in writing and reading files, here's what I've done:

hp = 25

file = io.open("player.txt","w")
if file==nil then
    io.output("player.txt")
    io.close()
end
file:write(hp)
file:close()

and it seems to work fine, it's just perfect... but then when I'm trying to add the file:write(hp) inside the if-sentence, it doesn't work. Also if I'll add file:read("*line") right after file:write(hp), this is what it says in player.txt:

25b[NUL]ÈñZ[NUL]
file = io.open("player.txt","w")

So what am I doing wrong? Also [NUL] is black block with white "NUL" text in it in notepad++ but it can't be copied here.

Edit: Hmmh, seems like the whole code is messed, up it always rewrites the whole file ;o

Edit2: Had actually no idea what I was talking about, nowadays I can understand file controlling bit more, here's what it should've been or what I tried to do:

function existsFile(path)
    x = io.open(path)
    if x == nil then
        io.close()
        return false
    else
        x:close()
        return true
    end
end

if not existsFile("player.txt") then
    file = io.open("player.txt", "w")
    file:write(25)
    hp = 25
    file:close()
else
    file = io.open("player.txt", "r")
    hp = file:read("*number")
    file:close()
end

And I know it doest look anything like the code I first posted, but that's what I basically meant.

Upvotes: 1

Views: 11711

Answers (3)

jhocking
jhocking

Reputation: 5577

The "if" block checks if "file" is nil, so that code block will never run.

read() doesn't work because you opened the file in "w" (write) mode.

Erasing the whole file is the expected behavior of write mode. In that mode the file is first erased and then you write new data to it.

Upvotes: 0

BMitch
BMitch

Reputation: 263549

Sounds like you're confused about the flags on io.open. Check the manual to be sure what you really want is the w flag since that overwrites everything.

Trying to do a file:write when you're in the if shouldn't work, and I'm not sure why you'd expect it to, since file is nil. You're saying that if the file couldn't be opened, then try to write this to the file, which doesn't make sense to me.

Upvotes: 0

Mikita Belahlazau
Mikita Belahlazau

Reputation: 15434

Could you explain what you are trying to do in this code? Why do you need to check if file is nil? When you open file for writing, lua automatically creates it if not exists. "w" mode means, that you you're erase all data in file and write new data May be you need "a" mode? In this mode new lines are added at the end of file.

Upvotes: 1

Related Questions