feat(lua): added basic threading

This commit is contained in:
maelstrom 2025-05-06 19:44:53 +02:00
parent a1bd6e1bbc
commit 26459c9275
2 changed files with 24 additions and 13 deletions

View file

@ -7,6 +7,7 @@
#include "objects/datamodel.h" #include "objects/datamodel.h"
#include "datatypes/ref.h" #include "datatypes/ref.h"
#include "lua.h" #include "lua.h"
#include <luajit-2.1/lua.h>
Script::Script(): Instance(&TYPE) { Script::Script(): Instance(&TYPE) {
source = "print \"Hello, world!\""; source = "print \"Hello, world!\"";
@ -18,25 +19,33 @@ Script::~Script() {
void Script::Run() { void Script::Run() {
lua_State* L = dataModel().value()->GetService<ScriptContext>()->state; lua_State* L = dataModel().value()->GetService<ScriptContext>()->state;
// Create thread
this->thread = lua_newthread(L);
lua_State* Lt = thread;
// Initialize script globals // Initialize script globals
lua_getglobal(L, "_G"); lua_getglobal(Lt, "_G");
lua_pushstring(L, "game"); lua_pushstring(Lt, "game");
Data::InstanceRef(dataModel().value()).PushLuaValue(L); Data::InstanceRef(dataModel().value()).PushLuaValue(Lt);
lua_rawset(L, -3); lua_rawset(Lt, -3);
lua_pushstring(L, "workspace"); lua_pushstring(Lt, "workspace");
Data::InstanceRef(dataModel().value()->GetService<Workspace>()).PushLuaValue(L); Data::InstanceRef(dataModel().value()->GetService<Workspace>()).PushLuaValue(Lt);
lua_rawset(L, -3); lua_rawset(Lt, -3);
lua_pop(L, 1); lua_pop(Lt, 1); // _G
luaL_loadstring(L, source.c_str()); // Load source and push onto thread stack as function ptr
int status = lua_pcall(L, 0, LUA_MULTRET, 0); luaL_loadstring(Lt, source.c_str());
if (status != 0) {
Logger::error(lua_tostring(L, -1)); int status = lua_resume(Lt, 0);
lua_pop(L, 1); 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() { void Script::Stop() {

View file

@ -6,6 +6,8 @@
class DEF_INST_(explorer_icon="script") Script : public Instance { class DEF_INST_(explorer_icon="script") Script : public Instance {
AUTOGEN_PREAMBLE AUTOGEN_PREAMBLE
lua_State* thread;
public: public:
Script(); Script();
~Script(); ~Script();