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

Logging with fs.open in IF

Started by TheLuke, 11 June 2014 - 05:09 PM
TheLuke #1
Posted 11 June 2014 - 07:09 PM
Hello again,

i got one more question using my little logfile.

Everytime, when a computer sends a command to my computer and it is not the authorized one, the program should save the senderId in a logfile.

My Program so far:

term.clear()
term.setCursorPos(1,1)

write("I'm your Server with ID: ")
write(os.getComputerID())
 
rednet.open("bottom")
local senderId, message, protocol = rednet.receive()

if senderId == 1 then
shell.run(message)

else
local file = fs.open("log", "a")
file.writeLine("BadBoy with ID: ")    -- Line 15 (see below)
file.write(senderId)
file.close()

end

The Progam itself doesnt give any errors, but if it get's a command from a computer which is not authorized, it says:
"startup: 15: attempt to index ? (a nil value)"

I dont get it - what's wrong?
MKlegoman357 #2
Posted 11 June 2014 - 07:17 PM
It probably cannot open the file, but I may be wrong… Although I see something that might interest you: file.writeLine( text ) adds a newline character after it writes 'text' to the file, meaning that your log file would look something like this:


BadBoy with ID:
15BadBoy with ID:
2
TheLuke #3
Posted 11 June 2014 - 07:25 PM
Oh tanks for this advise with Line problem :)/>
This Programm is the called startup and placed in the C: section, what i mean is there are no other files or directorys, but you are right:

I just tipped: edit log & saved.
Restartet the Computer and tryed -> Worked!

Thanks!

Edit: Is there a way to solve the problem that fs.open cannot open a file there?

Edit2:
The Logfile looks like:

BadBoy with ID: 6. 0

Any ideas where the ". 0" an the end comes from?
Edited on 11 June 2014 - 05:27 PM
MKlegoman357 #4
Posted 11 June 2014 - 07:28 PM
Oh, right. If the file does not exist fs.open will not be able to open it in append mode. To fix your issue you should first check if it exists and if it doesn't - create it.
TheLuke #5
Posted 11 June 2014 - 07:34 PM
Ah! Thanks a lot!
Bomb Bloke #6
Posted 12 June 2014 - 01:58 AM
I'd put this example on the fs.open() page a while back:

local h = fs.open("abcd", fs.exists("abcd") and "a" or "w")

It'll work regardless as to whether the file "abcd" exists or not. If you're not interested in appending, then you can just open your files in "w" mode without worrying about the issue.

The Logfile looks like:

BadBoy with ID: 6. 0

Any ideas where the ". 0" an the end comes from?

Use tostring() to format away unwanted decimals. Eg:

file.write( tostring( senderId ) )

Or you could concatenate that with the text of the previous line, like so:

file.writeLine("BadBoy with ID: " .. tostring( senderId ))
TheLuke #7
Posted 12 June 2014 - 12:10 PM
Ah! Nice to know :)/>

The function tostring is very nice :D/>
Thanks!