From cd46d7bd203b69e6d163fd19e38600d9feae6e56 Mon Sep 17 00:00:00 2001 From: jacqueline Date: Tue, 21 Nov 2023 16:20:01 +1100 Subject: Make lua db iterators async --- src/lua/lua_database.cpp | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) (limited to 'src/lua/lua_database.cpp') diff --git a/src/lua/lua_database.cpp b/src/lua/lua_database.cpp index 545dcd31..d8ae86f6 100644 --- a/src/lua/lua_database.cpp +++ b/src/lua/lua_database.cpp @@ -56,17 +56,28 @@ static const struct luaL_Reg kDatabaseFuncs[] = {{"indexes", indexes}, {NULL, NULL}}; static auto db_iterate(lua_State* state) -> int { + luaL_checktype(state, 1, LUA_TFUNCTION); + int callback_ref = luaL_ref(state, LUA_REGISTRYINDEX); + database::Iterator* it = *reinterpret_cast( lua_touserdata(state, lua_upvalueindex(1))); - auto res = it->Next(); - if (res) { - database::IndexRecord** record = reinterpret_cast( - lua_newuserdata(state, sizeof(uintptr_t))); - *record = new database::IndexRecord(*res); - luaL_setmetatable(state, kDbRecordMetatable); - return 1; - } + it->Next([=](std::optional res) { + events::Ui().RunOnTask([=]() { + lua_rawgeti(state, LUA_REGISTRYINDEX, callback_ref); + if (res) { + database::IndexRecord** record = + reinterpret_cast( + lua_newuserdata(state, sizeof(uintptr_t))); + *record = new database::IndexRecord(*res); + luaL_setmetatable(state, kDbRecordMetatable); + } else { + lua_pushnil(state); + } + lua_call(state, 1, 0); + luaL_unref(state, LUA_REGISTRYINDEX, callback_ref); + }); + }); return 0; } -- cgit v1.2.3