You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test.lua 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. -- Testing
  2. local async function iter(i)
  3. asyncio.yield(0)
  4. for i = 1, 5 do
  5. print('Waiting 1 second because iterators')
  6. asyncio.sleep(1)
  7. print('Finished waiting, yield-ing ' .. i .. '...')
  8. asyncio.yield('#' .. i)
  9. end
  10. print('Finished iterating!')
  11. end
  12. print('Hello from the test file, waiting for other mods to load...')
  13. asyncio.defer()
  14. print('Done, starting iteration.')
  15. async for i, _ in iter(1) do
  16. print('Hello from the asyncio code!')
  17. print('Got ' .. i)
  18. end
  19. print('Iterating over all items')
  20. async for k, _ in asyncio.pairs(minetest.registered_items) do
  21. print('Heavy operation:', k)
  22. end
  23. print('Done')
  24. minetest.register_chatcommand('/alua', {
  25. privs = {server=true},
  26. help = 'Executes asyncio lua commands.',
  27. -- This function has to use minetest.chat_send_player as it is executed
  28. -- asynchronously and return values aren't sent to non-asynchronous
  29. -- functions.
  30. func = async function(name, param)
  31. local func, msg = asyncio.loadstring(param)
  32. if not func then
  33. minetest.chat_send_player(name, 'Load error: ' .. tostring(msg))
  34. return
  35. end
  36. local good, msg = pcall(func)
  37. if good then
  38. minetest.chat_send_player(name, 'Code executed.')
  39. else
  40. minetest.chat_send_player(name, 'Error executing code: ' ..
  41. tostring(msg))
  42. end
  43. end,
  44. })
  45. -- More testing
  46. local lock = asyncio.Lock()
  47. local async function do_something()
  48. print('Acquiring lock...')
  49. lock:acquire()
  50. print('Acquired the lock, doing something...')
  51. asyncio.sleep(5)
  52. print('Releasing the lock...')
  53. lock:release()
  54. end
  55. for i = 1, 5 do
  56. asyncio.run_async(do_something)
  57. end
  58. -- Wait for the above functions to finish.
  59. lock:acquire()
  60. lock:release()
  61. -- Events
  62. local event = asyncio.Event()
  63. local async function do_something_else()
  64. print('Waiting on the event...')
  65. event:wait()
  66. print('Event triggered, waiting 5 seconds.')
  67. asyncio.sleep(5)
  68. print('Done.')
  69. end
  70. for i = 1, 5 do
  71. asyncio.run_async(do_something_else)
  72. end
  73. -- Set the event
  74. asyncio.sleep(5)
  75. print('Running event:set()...')
  76. event:set()
  77. print('Finished running event:set().')