keith_k

Lua tip: Replacing sleep() function

Discussion created by keith_k on Nov 21, 2008
Latest reply on Nov 22, 2008 by carstein.seeberg
In a different thread on this forum, Carstein warned that using sleep() in NAS Lua scripts can be dangerous because that would block the NAS from terminating or restarting.  He recommended using a for loop to call sleep() multiple times in a row for very short durations.  I have been reading up on Lua lately, and I realized that because functions are first-class variables in Lua, you can redefine them.  This would save you the trouble of changing the sleep() calls throughout a script.  There is also an interesting feature/trick call closures that works well for this.  Here is some sample code:
do
   local orig_sleep = sleep
   sleep = function (seconds)
      for i = 1,seconds do
         -- Sleep for 1 second at a time
         orig_sleep(1000)
      end
   end
end
The sleep() function is first saved as the orig_sleep() function, which is local within the do...end.  Because it is local to that block, it is visible to the new sleep() function I defined but not the rest of the script.  Now there is no way to accidentally call the original and possibly problematic sleep() function.

I plan to put this into a "library" file and require() it at the beginning of my Lua scripts (or at least thost that need to sleep for some reason).

Question for Nimsoft:  Have you considered redefining the Lua sleep() function in the NAS to prevent the types of problems described above?

Regards,
Keith

Outcomes