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

Help with code | Incrementing by one

Started by LELS, 24 February 2013 - 09:43 PM
LELS #1
Posted 24 February 2013 - 10:43 PM
I've written this code to give out software for free on an SMP server and it all works, but I'm having this major (and most likely - nooby) problem of not able to increment by one. Also, because the computers restart every time the server restarts, I want to make sure each count is stored in a file.

Code is:

if fs.exists("count") == true then
asdf = fs.open("count", "r")
local hold = asdf.readLine()
asdf.close()
count = tonumber(hold)
else
asdf = fs.open("count", "w")
asdf.close()
local count = tonumber(0)
end
term.write(count)
while true do
if disk.isPresent("top") == true then
  if fs.exists("disk/startup") == true then
   fs.delete("disk/startup")
  end
  if fs.exists("disk/readme") == true then
   fs.delete("disk/readme")
  end
  fs.copy("time", "disk/startup")
  fs.copy("readme", "disk/readme")
  disk.setLabel("top", "Script")
  disk.eject("top")
  count = count + 1

  file = fs.open("count", "w")
  file.write(count)
  file.close()
end
sleep(1)
end
Lyqyd #2
Posted 26 February 2013 - 06:36 AM
Split into new topic.
LBPHacker #3
Posted 26 February 2013 - 08:42 AM
Try this:



local count
if fs.exists("count") then
    asdf = fs.open("count", "r")
    count = tonumber(asdf.readLine()) or 0
    asdf.close()
else
    count = 0
    asdf = fs.open("count", "w")
    file.write(count)
    asdf.close()
end
term.write(count)
while true do
    if disk.isPresent("top") == true then
        if fs.exists("disk/startup") then
            fs.delete("disk/startup")
        end
        if fs.exists("disk/readme") then
            fs.delete("disk/readme")
        end
        fs.copy("time", "disk/startup")
        fs.copy("readme", "disk/readme")
        disk.setLabel("top", "Script")
        disk.eject("top")
        count = count + 1

        file = fs.open("count", "w")
        file.write(count)
        file.close()
    end
    sleep(1)
end
remiX #4
Posted 26 February 2013 - 08:57 AM
What exactly is the problem?
Does it not save to the file?
Does it not read from the file?

hmm?*
LELS #5
Posted 02 March 2013 - 09:34 AM
Sorry - should have mentioned - the error is "startup:27: attempt to perform arithmetic __add on nil and number"
LBPHacker #6
Posted 02 March 2013 - 08:58 PM
Then the solution is what I've mentioned a week ago. You've declared count inside an IF block, and when the program reaches the end of the IF block, it garbagecollects count. So it's nil. The first line of the code I've posted declares count outside everything, so it should work.
LELS #7
Posted 02 March 2013 - 11:02 PM
Ah, I see - Thanks :)/>