From 26459c9275af63c4065a67c39d6b093531f6eef3 Mon Sep 17 00:00:00 2001 From: maelstrom Date: Tue, 6 May 2025 19:44:53 +0200 Subject: [PATCH] feat(lua): added basic threading --- core/src/objects/script.cpp | 35 ++++++++++++++++++++++------------- core/src/objects/script.h | 2 ++ 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/core/src/objects/script.cpp b/core/src/objects/script.cpp index 0b1349e..bb10697 100644 --- a/core/src/objects/script.cpp +++ b/core/src/objects/script.cpp @@ -7,6 +7,7 @@ #include "objects/datamodel.h" #include "datatypes/ref.h" #include "lua.h" +#include Script::Script(): Instance(&TYPE) { source = "print \"Hello, world!\""; @@ -18,25 +19,33 @@ Script::~Script() { void Script::Run() { lua_State* L = dataModel().value()->GetService()->state; + // Create thread + this->thread = lua_newthread(L); + lua_State* Lt = thread; + // Initialize script globals - lua_getglobal(L, "_G"); + lua_getglobal(Lt, "_G"); - lua_pushstring(L, "game"); - Data::InstanceRef(dataModel().value()).PushLuaValue(L); - lua_rawset(L, -3); + lua_pushstring(Lt, "game"); + Data::InstanceRef(dataModel().value()).PushLuaValue(Lt); + lua_rawset(Lt, -3); - lua_pushstring(L, "workspace"); - Data::InstanceRef(dataModel().value()->GetService()).PushLuaValue(L); - lua_rawset(L, -3); + lua_pushstring(Lt, "workspace"); + Data::InstanceRef(dataModel().value()->GetService()).PushLuaValue(Lt); + lua_rawset(Lt, -3); - lua_pop(L, 1); + lua_pop(Lt, 1); // _G - luaL_loadstring(L, source.c_str()); - int status = lua_pcall(L, 0, LUA_MULTRET, 0); - if (status != 0) { - Logger::error(lua_tostring(L, -1)); - lua_pop(L, 1); + // Load source and push onto thread stack as function ptr + luaL_loadstring(Lt, source.c_str()); + + int status = lua_resume(Lt, 0); + if (status > LUA_YIELD) { + Logger::error(lua_tostring(Lt, -1)); + lua_pop(Lt, 1); // Pop return value } + + lua_pop(L, 1); // Pop the thread } void Script::Stop() { diff --git a/core/src/objects/script.h b/core/src/objects/script.h index c435568..0a112a2 100644 --- a/core/src/objects/script.h +++ b/core/src/objects/script.h @@ -6,6 +6,8 @@ class DEF_INST_(explorer_icon="script") Script : public Instance { AUTOGEN_PREAMBLE + + lua_State* thread; public: Script(); ~Script();