This repository has been archived on 2019-08-24. You can view files and clone it, but cannot push or open issues or pull requests.
asyncio/test.lua

90 lines
2.2 KiB
Lua

-- Testing
local async function iter(i)
asyncio.yield(0)
for i = 1, 5 do
print('Waiting 1 second because iterators')
asyncio.sleep(1)
print('Finished waiting, yield-ing ' .. i .. '...')
asyncio.yield('#' .. i)
end
print('Finished iterating!')
end
print('Hello from the test file, waiting for other mods to load...')
asyncio.defer()
print('Done, starting iteration.')
async for i, _ in iter(1) do
print('Hello from the asyncio code!')
print('Got ' .. i)
end
print('Iterating over all items')
async for k, _ in asyncio.pairs(minetest.registered_items) do
print('Heavy operation:', k)
end
print('Done')
minetest.register_chatcommand('/alua', {
privs = {server=true},
help = 'Executes asyncio lua commands.',
-- This function has to use minetest.chat_send_player as it is executed
-- asynchronously and return values aren't sent to non-asynchronous
-- functions.
func = async function(name, param)
local func, msg = asyncio.loadstring(param)
if not func then
minetest.chat_send_player(name, 'Load error: ' .. tostring(msg))
return
end
local good, msg = pcall(func)
if good then
minetest.chat_send_player(name, 'Code executed.')
else
minetest.chat_send_player(name, 'Error executing code: ' ..
tostring(msg))
end
end,
})
-- More testing
local lock = asyncio.Lock()
local async function do_something()
print('Acquiring lock...')
lock:acquire()
print('Acquired the lock, doing something...')
asyncio.sleep(5)
print('Releasing the lock...')
lock:release()
end
for i = 1, 5 do
asyncio.run_async(do_something)
end
-- Wait for the above functions to finish.
lock:acquire()
lock:release()
-- Events
local event = asyncio.Event()
local async function do_something_else()
print('Waiting on the event...')
event:wait()
print('Event triggered, waiting 5 seconds.')
asyncio.sleep(5)
print('Done.')
end
for i = 1, 5 do
asyncio.run_async(do_something_else)
end
-- Set the event
asyncio.sleep(5)
print('Running event:set()...')
event:set()
print('Finished running event:set().')