Skip to content

Bug: assert(not coroutine.running()) in sync API #7

Closed
@linrongbin16

Description

@linrongbin16

Hi,

In current implementation, there is an issue: linrongbin16/gitlinker.nvim#257

@loganswartz found it is always failed on this line (on fedora 41, but worked on MacOS M1 and ubuntu 20.04):

https://github.com/linrongbin16/gitlinker.nvim/blob/df0c4e342742812186f87e32caf82b3e5e288a84/lua/gitlinker/commons/async.lua#L78

Note: it is copied from here:

assert(not coroutine.running())

I found the comments says there is a API break change in coroutine.running() between lua51 and lua52:

async.nvim/lua/async.lua

Lines 16 to 23 in ad097c9

-- Coroutine.running() was changed between Lua 5.1 and 5.2:
-- - 5.1: Returns the running coroutine, or nil when called by the main thread.
-- - 5.2: Returns the running coroutine plus a boolean, true when the running
-- coroutine is the main one.
--
-- For LuaJIT, 5.2 behaviour is enabled with LUAJIT_ENABLE_LUA52COMPAT
--
-- We need to handle both.

In a previous version, there's a M.running() to handle this:

-- Note: coroutine.running() was changed between Lua 5.1 and 5.2:
-- - 5.1: Returns the running coroutine, or nil when called by the main thread.
-- - 5.2: Returns the running coroutine plus a boolean, true when the running
--   coroutine is the main one.
--
-- For LuaJIT, 5.2 behaviour is enabled with LUAJIT_ENABLE_LUA52COMPAT
--
-- We need to handle both.
--- Returns whether the current execution context is async.
---
--- @treturn boolean?
function M.running()
  local current = coroutine.running()
  if current and handles[current] then
    return true
  end
end

And there is a strict parameter to tolerate some errors:

--- Create a function which executes in an async context but
--- called from a non-async context.
--- @tparam function func
--- @tparam boolean strict Error when called in non-async context
function M.void(func, strict)
  vim.validate({ func = { func, "function" } })
  return function(...)
    if M.running() then
      if strict then
        error("This function must run in a non-async context")
      end
      return func(...)
    end
    return M.run(func, nil, ...)
  end
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions