Tocuto

Lua Asyncio (heavy example)

Apr 25th, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.62 KB | None | 0 0
  1. do
  2.     local _, nickname = pcall(nil)
  3.     tfm.get.room.owner = string.match(nickname, "(.-)%.")
  4. end
  5.  
  6. local await = coroutine.yield
  7. local loop = Loop()
  8. loop.max_runtime = 20 -- You can play a bit with these values
  9. loop.iteration_cooldown = 5000 -- This specific configuration will run almost anything
  10. loop.accept_faster = false -- It is the best one when you need to spam a bunch of heavy tasks!
  11.  
  12. function useTooMuchRuntime(howMany)
  13.     local start = os.time()
  14.     while os.time() - start < howMany do end
  15. end
  16.  
  17. -- You can spam the spacebar. It will run anyways. If you spam it, it will be a bit slower and it will
  18. -- not print anything for some time, but it will run!
  19.  
  20. function keyboardTask(player, key, down, x, y)
  21.     print("Key pressed, executing some code!! Current task runtime is " .. loop.current_task.real_runtime() .. "ms")
  22.     await(Task(useTooMuchRuntime, 30)) -- We create the task and we yield it so
  23.     print("Half of the code has been executed. Executing the other half! Runtime is " .. loop.current_task.runtime .. "ms")
  24.     await(Task(useTooMuchRuntime, 30))
  25.     print("Alright, ended running the code! The total runtime is " .. loop.current_task.real_runtime() .. "ms")
  26. end
  27.  
  28. function eventKeyboard(...)
  29.     local start = os.time()
  30.  
  31.     loop.add_task(Task(keyboardTask, ...))
  32.  
  33.     loop.run_tasks(start) -- We can call this function from any event, and it is better
  34.     -- because it will run faster when it cans!
  35. end
  36.  
  37. function eventLoop()
  38.     loop.run_tasks() -- We don't call it as eventLoop = loop.run_tasks because the eventLoop has arguments, and it will just break the system
  39. end
  40.  
  41. system.bindKeyboard(tfm.get.room.owner, 32, true, true)
Add Comment
Please, Sign In to add comment