AnsweredAssumed Answered

More lua fun. a closure to return an itterator to return sequential nimids

Question asked by RobPol on Jul 18, 2012
Latest reply on Jul 21, 2012 by 1_keithk

I was using a script with raw alarm that could generate multiple alarms within a second. As rawalarm is seeded with the system time on each invocation and the system time is returned with 1 sec granularity this was causing multiple alarms with the same nimid.


I thought this was the perfect chance to start playing with closures in lua. Here is a little factory function that returns an itterator function that returns sequential nimids. It also extends the nimbus class with nimbus.nimid () Enjoy...


-- get_nimid_itterator


-- A function to generate a function to generates sequential nimids
-- This function returns a function that captures its initial
-- values (a closure).
-- This ensures we can return multiple nimids in the same second
-- without getting the same nimid due to math random being seeded
-- with the current time to 1 sec granularity

get_nimid_itterator = function ()
   key = ""
   local key_root = mid(base,math.random(1,26),1) .. mid(base,math.random(1,26),1)
   local key_mid  = math.random(1,100000000)
   local key_end  = math.random(1,100000)

   -- uncomment next line if you want to see rollover of the last five digits

   -- key_end = 99994

   return function()
      key_end = key_end + 1
      if key_end == 100000 then
         key_mid = key_mid + 1
         key_end = 0
      return key_root .. sprintf ("%08d", key_mid) .. "-" .. sprintf ("%05d", key_end)


-- add it to the nimbus class

nimbus.nimid = get_nimid_itterator()


-- Test it
for i=1,10 do
   print (nimbus.nimid())