Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- We require our libraries and modules here
- local component = require("component")
- local modem = component.modem
- local io = require("io")
- local event = require("event")
- local fs = require("filesystem")
- -- This line will allow the user to easily specify how many
- -- ports, and messages, we want to use with the program.
- local ports, msgs = ...
- -- This ensures that the proper amount of arguments are being used,
- -- and if not, will display proper usage of running the program
- if #({...}) ~= 2 then
- error("Usage: Logger (# of ports to listen to, starting at 1) (# of messages to write to file before program ends.", 0)
- return
- end
- -- You can ignore this snippet of code, unless you're
- -- ping. Or unless you really want to wait half an hour
- -- for all ports to open. Luckily if you're running this
- -- on a Minecraft server, you will only need to do this once,
- -- so long as you set a high enough message count.
- if ports == "potato" then
- ports = 65535
- end
- -- This is to check whether or not the argument being passed
- -- as ports is actually a number, and not words or symbols.
- if not tonumber(ports) then
- error("The port needs to be a number!",0)
- return
- end
- -- Same thing as our first check, only here we're checking the
- -- messages amount argument.
- if not tonumber(msgs) then
- error("The amount of messages needs to be a number!", 0)
- return
- end
- -- Now, we have to open our ports that we want to listen to.
- -- Note the maximum on our range is the variable we defined in our
- -- first argument.
- for prt = 1,ports do
- modem.open(prt)
- end
- -- This is where the magic happens. This is where we open our log file, or
- -- create one if it doesn't exist, and listen for messages to write to our
- -- file until we've caught enough messages to satisfy our second argument.
- local h = io.open("Logs.txt", "a")
- for n = 1, tonumber(msgs) do
- local _, _, from, port, _, message = event.pull("modem_message")
- print("Got a message from " .. from .. " on port " .. port .. ": " .. tostring(message))
- h:write("Got a message from " .. from .. " on port " .. port .. ": " .. tostring(message) .. "\n")
- end
- -- Now that we have enough messages, we can close the ports we opened earlier on.
- modem.close()
- -- Notice I didn't specify a port? That's because
- -- by default in OC, when a port isn't defined, all
- -- ports are closed when this method is called.
- -- Now we must close our log file to ensure that it saves.
- h:close()
- -- This lets the user know that the logs were successfully saved.
- -- Huzzah!
- print("Saved logs to Logs.txt.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement