feat(lua): added basic threading
This commit is contained in:
parent
a1bd6e1bbc
commit
26459c9275
2 changed files with 24 additions and 13 deletions
|
@ -7,6 +7,7 @@
|
|||
#include "objects/datamodel.h"
|
||||
#include "datatypes/ref.h"
|
||||
#include "lua.h"
|
||||
#include <luajit-2.1/lua.h>
|
||||
|
||||
Script::Script(): Instance(&TYPE) {
|
||||
source = "print \"Hello, world!\"";
|
||||
|
@ -18,25 +19,33 @@ Script::~Script() {
|
|||
void Script::Run() {
|
||||
lua_State* L = dataModel().value()->GetService<ScriptContext>()->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<Workspace>()).PushLuaValue(L);
|
||||
lua_rawset(L, -3);
|
||||
lua_pushstring(Lt, "workspace");
|
||||
Data::InstanceRef(dataModel().value()->GetService<Workspace>()).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() {
|
||||
|
|
|
@ -6,6 +6,8 @@
|
|||
|
||||
class DEF_INST_(explorer_icon="script") Script : public Instance {
|
||||
AUTOGEN_PREAMBLE
|
||||
|
||||
lua_State* thread;
|
||||
public:
|
||||
Script();
|
||||
~Script();
|
||||
|
|
Loading…
Add table
Reference in a new issue