We can now load lua scripts properly

This commit is contained in:
wheremyfoodat 2023-12-16 16:36:03 +02:00
parent c57f2db6c0
commit 6386605b97
6 changed files with 73 additions and 2 deletions

View file

@ -51,6 +51,31 @@ void LuaManager::loadFile(const char* path) {
}
}
void LuaManager::loadString(const std::string& code) {
// Initialize Lua if it has not been initialized
if (!initialized) {
initialize();
}
// If init failed, don't execute
if (!initialized) {
printf("Lua initialization failed, file won't run\n");
haveScript = false;
return;
}
int status = luaL_loadstring(L, code.c_str()); // load Lua script
int ret = lua_pcall(L, 0, 0, 0); // tell Lua to run the script
if (ret != 0) {
haveScript = false;
fprintf(stderr, "%s\n", lua_tostring(L, -1)); // tell us what mistake we made
} else {
haveScript = true;
}
}
void LuaManager::signalEventInternal(LuaEvent e) {
lua_getglobal(L, "eventHandler"); // We want to call the event handler
lua_pushnumber(L, static_cast<int>(e)); // Push event type

View file

@ -195,6 +195,11 @@ void MainWindow::dispatchMessage(const EmulatorMessage& message) {
delete message.path.p;
break;
case MessageType::LoadLuaScript:
emu->getLua().loadString(*message.string.str);
delete message.string.str;
break;
case MessageType::Pause: emu->pause(); break;
case MessageType::Resume: emu->resume(); break;
case MessageType::TogglePause: emu->togglePause(); break;
@ -259,3 +264,11 @@ void MainWindow::keyReleaseEvent(QKeyEvent* event) {
case Qt::Key_Backspace: releaseKey(HID::Keys::Select); break;
}
}
void MainWindow::loadLuaScript(const std::string& code) {
EmulatorMessage message{.type = MessageType::LoadLuaScript};
// Make a copy of the code on the heap to send via the message queue
message.string.str = new std::string(code);
sendMessage(message);
}

View file

@ -1,6 +1,10 @@
#include "panda_qt/text_editor.hpp"
#include <QPushButton>
#include <QVBoxLayout>
#include "panda_qt/main_window.hpp"
using namespace Zep;
TextEditorWindow::TextEditorWindow(QWidget* parent, const std::string& filename, const std::string& initialText)
@ -13,8 +17,25 @@ TextEditorWindow::TextEditorWindow(QWidget* parent, const std::string& filename,
zepWidget.GetEditor().SetGlobalMode(Zep::ZepMode_Standard::StaticName());
zepWidget.GetEditor().InitWithText(filename, initialText);
QVBoxLayout* mainLayout = new QVBoxLayout();
setLayout(mainLayout);
QPushButton* button = new QPushButton(tr("Load script"), this);
button->setFixedSize(100, 20);
connect(button, &QPushButton::pressed, this, [this]() {
if (parentWidget()) {
auto buffer = zepWidget.GetEditor().GetMRUBuffer();
const std::string text = buffer->GetBufferText(buffer->Begin(), buffer->End());
static_cast<MainWindow*>(parentWidget())->loadLuaScript(text);
} else {
// This should be unreachable, only here for safety purposes
printf("Text editor does not have any parent widget, click doesn't work :(\n");
}
});
mainLayout->addWidget(button);
mainLayout->addWidget(&zepWidget);
}