Jump to content




Why is this code erasing the file?


  • You cannot reply to this topic
2 replies to this topic

#1 mrpoopy345

  • Members
  • 148 posts
  • LocationMy Computer

Posted 05 May 2015 - 09:39 PM

I am trying to make a golfing language in lua (Stupid, I know, but fun) and this is the code for my compiler:
tbl = {}
h = fs.open("testfile", "r")
r = h.readLine()
while r do
if string.find(r, "if ") then
 table.insert(tbl, r.." then")
 ify = 1
else
 if ify == 1 then
  if string.sub(r, 1, 1) ~= " " then
   table.insert(tbl, table.getn(tbl)+1, "end")
   ify = 0
  else
   table.insert(tbl, r)
  end
end
end
r = h.readLine()
end
h.close()
h = fs.open("testfile", "w")
for k,v in pairs(tbl) do
 h.writeLine(v)
 print(v)
end
And what this code is supposed to do is turn this:
if 2 == 2
 print("Yes")
into this:
if 2 == 2 then
 print("Yes")
end
But for some reason it just wipes the file and there becomes nothing in tbl. Why is this?

#2 Creator

    Mad Dash Victor

  • Members
  • 2,168 posts
  • LocationYou will never find me, muhahahahahaha

Posted 05 May 2015 - 10:30 PM

you forget to h.close()

#3 Lignum

  • Members
  • 558 posts

Posted 05 May 2015 - 10:31 PM

You need to flush the file when you're done writing to apply the changes to the file. You can do this using the file.flush() function. file.close() will also automatically do this as well.
So, you need this at the end of your code:
h.close()

Also, please avoid the usage of globals. Globals are slower than locals and will exist until a reboot. Additionally, any program on the computer can access them after their creation.
Try running your program and then typing "tbl" in the Lua prompt. It should display the contents of tbl as they were when your program ended.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users