This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
mrpoopy345's profile picture

Why is this code erasing the file?

Started by mrpoopy345, 05 May 2015 - 08:39 PM
mrpoopy345 #1
Posted 05 May 2015 - 10: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?
Creator #2
Posted 05 May 2015 - 11:30 PM
you forget to h.close()
Lignum #3
Posted 05 May 2015 - 11: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.