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

Can't get monitor to work

Started by BrofistKittycat, 27 January 2017 - 01:30 AM
BrofistKittycat #1
Posted 27 January 2017 - 02:30 AM
Hello, I have been trying to make a program which will display the current Minecraft time on my advanced computer. I can't figure out what's wrong, I don't think that it's the code but I will put it anyways:

function tim()
  m = peripheral.wrap("right")
  i = textutils.formatTime(os.time())
  m.clear()
  m.setCursorPos(1,2)
  m.write(i)
  m.setCursorPos(1,1)
  m.write("Time Monitor v.0.1")
  sleep(0.1)
  tim()
end
tim()
What my problem is is that the program works perfectly with any monitor that isn't more than 1 block high. I'm new here, and so I looked through the other posts and posting guides, so I hope I am doing this right. :P/> Also, I don't get an error from it. No error on the monitor, none on the PC. Please help! I will continue experimenting around.
BrofistKittycat #2
Posted 27 January 2017 - 02:47 AM
Nevermind! I'm new here (noob) so I don't know how to remove this, but all I had to do was place the monitors in a different order.
Bomb Bloke #3
Posted 27 January 2017 - 11:16 AM
There's a bit of a problem with your code in that it'll crash within about a half minute or so.

Every time you call a function, Lua adds a new instance of that running function into what's called the "function stack". When a function ends, it gets knocked off the stack and the one beneath it resumes from where it left off.

Your script calls tim() over and over without allowing any of the running function instances to end. When the stack fills up, it'll crash (in the case of LuaJ, which ComputerCraft uses, you'll get a Java-based "array index out of bounds" error or somesuch).

The solution is to use a proper loop structure, such as "while". A re-write of your script might look like:

local m = peripheral.find("monitor")  -- We only need to define "m" once.

m.clear()
m.setCursorPos(1,1)
m.write("Time Monitor v.0.1")

while true do  -- A loop that repeats indefinitely.
	m.setCursorPos(1,2)
	m.clearLine()
	m.write(textutils.formatTime(os.time()))
	sleep(1)
end

http://lua-users.org/wiki/ControlStructureTutorial
Edited on 27 January 2017 - 10:18 AM