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

[LUA] pcall and sleep()

Started by BlackRa1n, 23 March 2012 - 09:05 PM
BlackRa1n #1
Posted 23 March 2012 - 10:05 PM
Hello,
I am trying to write a small code:

print("Now shutting down!")
sleep(3)
os.shutdown()

I don't want the user to be able to terminate the code/program so I want to use pcall, but where do I use it?
Liraal #2
Posted 23 March 2012 - 10:09 PM
pcall(sleep,3)
Advert #3
Posted 23 March 2012 - 10:13 PM
You're better off using os.pullEventRaw here; if you use pcall in combination with sleep, then it'll skip the remaining time:


local nTimeBefore = os.time()
pcall(sleep, 3)
local nTimeAfter = os.time()
print("Time before: ", nTimeBefore)
print("Time after: ", nTimeAfter)
print("Difference: ", nTimeAfter - nTimeBefore)

If you use os.pullEventRaw:


function psleep(n)
local tTimer = os.startTimer(n)
for sEvent, t in os.pullEventRaw do
  if sEvent == "timer" and t = tTimer then
   break
  end
end
end


local nTimeBefore = os.time()
psleep(3)
local nTimeAfter = os.time()
print("Time before: ", nTimeBefore)
print("Time after: ", nTimeAfter)
print("Difference: ", nTimeAfter - nTimeBefore)



*Code untested, but should work.
BlackRa1n #4
Posted 23 March 2012 - 10:18 PM
A 'then' is expected on the string 4, even though I can see there is one there…
Advert #5
Posted 23 March 2012 - 11:15 PM
Whoops, missed an equal sign:



function psleep(n)
local tTimer = os.startTimer(n)
for sEvent, t in os.pullEventRaw do
  if sEvent == "timer" and t == tTimer then
   break
  end
end
end


local nTimeBefore = os.time()
psleep(3)
local nTimeAfter = os.time()
print("Time before: ", nTimeBefore)
print("Time after: ", nTimeAfter)
print("Difference: ", nTimeAfter - nTimeBefore)
coolblockj #6
Posted 24 March 2012 - 02:51 AM
Whoops, missed an equal sign:



function psleep(n)
local tTimer = os.startTimer(n)
for sEvent, t in os.pullEventRaw do
  if sEvent == "timer" and t == tTimer then
   break
  end
end
end


local nTimeBefore = os.time()
psleep(3)
local nTimeAfter = os.time()
print("Time before: ", nTimeBefore)
print("Time after: ", nTimeAfter)
print("Difference: ", nTimeAfter - nTimeBefore)
Wouldn't it be easier to just do

os.pullEvent = os.pullEventRaw
print("Now shutting down!")
sleep(3)
os.shutdown()
Sorry if i am wrong, that just seems easiest
Advert #7
Posted 24 March 2012 - 03:05 AM
I guess that comes down to what you define 'easier' as.

Personally, I prefer having clean/re-usable code rather than the shorter line count.
BlackRa1n #8
Posted 24 March 2012 - 08:31 AM
Thanks! :)/>/>
It works now! Now, I need to actually look at the code and work out what it means! All I know at the moment is that it works! xD
I'm new to LUA :(/>/>