github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/lib/runtimelib/lua/time.quotas.lua (about)

     1  -- Test time bound contexts
     2  
     3  -- A time bound context stops when the time is exceeded
     4  local n = 0
     5  local ctx = runtime.callcontext({kill={millis=10}}, function()
     6      local ctx = runtime.context()
     7      print(ctx.kill.millis, ctx.kill.seconds)
     8      --> =10	0.01
     9      while true do
    10          n = n + 1
    11      end
    12  end)
    13  
    14  -- The context was killed
    15  print(ctx)
    16  --> =killed
    17  
    18  -- It lasted for at least 1e6ms
    19  print(ctx.used.millis >= 10)
    20  --> =true
    21  
    22  -- It didn't last much more than that (could be flaky)
    23  print(ctx.used.millis <= 20)
    24  --> =true
    25  
    26  -- Significant work was done while it lasted (could be flaky)
    27  print(n > 20000)
    28  --> =true
    29  
    30  -- The outer context keeps track of time spent in the inner context
    31  local ctx = runtime.callcontext({kill={seconds=0.1}}, function()
    32      for i = 1, 3 do
    33          runtime.callcontext({kill={millis=10}}, function()
    34              while true do end
    35          end)
    36      end
    37  end)
    38  
    39  print(ctx.used.millis >= 30)
    40  --> =true
    41  
    42  -- Nested contexts are bound by the time limit of their parent context.
    43  local ctx = runtime.callcontext({kill={millis=10}}, function()
    44          runtime.callcontext({}, function ()
    45              print(runtime.context().kill.millis)
    46              --> =10
    47          end)
    48          runtime.callcontext({kill={seconds=1}}, function()
    49              print(runtime.context().kill.millis <= 10)
    50              --> =true
    51          end)
    52  end)