[Lua] Confusing error when calling async_retval from unyieldable thread/main

Just a kind of annoying error people sometimes run into where calling an async funcref doesn’t output the error that occurred.

exports('async', function()
    Wait(0)

    return 1
end)

local n = exports.test:async()

print(n)

When calling exportProcessResult the result is attempt to yield from outside a coroutine, which gets stripped during prefixNewlines.

That error message is still a bit confusing for the average user, and can be somewhat improved by modifying the assertion inside Citizen.Await.

if not coroutine.isyieldable() then
	error("Current execution context is not in the scheduler, you should use CreateThread / SetTimeout or Event system (AddEventHandler) to be able to Await")
end
[         script:test] citizen:/scripting/lua/scheduler.lua:110: Current execution context is not in the scheduler, you should use CreateThread / SetTimeout or Event system (AddEventHandler) to be able to Await
[         script:test] Error loading script server.lua in resource test: @test/server.lua:7:

Message could probably still be improved but makes more sense than mentioning coroutines to users. prefixNewlines still needs to be corrected, however.

… to be fair, I think any main chunk should rather be wrapped in a coroutine itself (to be scheduled and ticked right after script initialization) so that this will Just Work and there’s also less of a need for a CreateThread wrapped around random one-off code.

This should be fixed in tweak(scripting/lua): run main chunks of a script in a coroutine · citizenfx/fivem@436151f · GitHub but this might have some regression risk if unlucky - although this is unlikely, since CreateThreadNow invokes a lua_resume right away.

The repro code at least correctly prints 1 now.

1 Like