Skip to content

Instantly share code, notes, and snippets.

@dmitmel
Created December 17, 2021 17:31
Show Gist options
  • Save dmitmel/04deb4f02266af57fec694b854fec208 to your computer and use it in GitHub Desktop.
Save dmitmel/04deb4f02266af57fec694b854fec208 to your computer and use it in GitHub Desktop.
Example of a semi-practical usage of vim.loop.new_work
local function async_scandir(dirname, callback)
local function work_callback(dirname)
local uv = require('luv')
local fs, err = uv.fs_scandir(dirname)
if err then
return err
end
local entry_names = {}
local entry_types = {}
local i = 0
while true do
local name, type_or_err, err_code = uv.fs_scandir_next(fs)
if err_code then
return type_or_err
elseif not name then
break
else
i = i + 1
entry_names[i] = name
entry_types[i] = type_or_err
end
end
return nil, i, table.concat(entry_names, '\0'), table.concat(entry_types, '\0')
end
local function work_done_callback(err, entries_count, entry_names, entry_types)
if err then
return callback(err)
end
entry_names = vim.split(entry_names, '\0')
entry_types = vim.split(entry_types, '\0')
assert(#entry_names == entries_count)
assert(#entry_types == entries_count)
local entries = {}
for i = 1, entries_count do
entries[i] = { name = entry_names[i], type = entry_types[i] }
end
callback(nil, entries)
end
local work = vim.loop.new_work(work_callback, work_done_callback)
local _, err = vim.loop.queue_work(work, dirname)
if err then
callback(err)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment