Can now add a lua file with the same name as a page for page-scoped lua functionality

This commit is contained in:
2026-07-12 20:40:32 -05:00
parent 78fe9a9abc
commit 017776a7f3
3 changed files with 45 additions and 2 deletions

View File

@@ -1,9 +1,13 @@
#include "app.hpp"
#include <RmlUi/Core/Core.h>
#include <RmlUi/Core/Factory.h>
#include <RmlUi/Lua/Interpreter.h>
#include <RmlUi/Lua.h>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <lauxlib.h>
#include <lua.h>
#include <sstream>
App::App(Rml::Context *ctx, ApplicationData *appData)
@@ -64,6 +68,22 @@ bool App::NavigateTo(const std::string &pageName) {
return false;
}
TeardownCurrentPage();
std::string luaPath = GetAssetsPath() + "/pages/" + pageName + ".lua";
if (std::filesystem::exists(luaPath)) {
std::string luaContent;
if (ReadFile(luaPath, luaContent)) {
lua_State *L = Rml::Lua::Interpreter::GetLuaState();
if (luaL_dostring(L, luaContent.c_str()) != LUA_OK) {
std::cout << "[LUA ERROR] Failed to run page script " << pageName << ".lua: "
<< lua_tostring(L, -1) << "\n";
lua_pop(L, 1);
}
}
}
std::string path = GetAssetsPath() + "/pages/" + pageName + ".rml";
std::string content;
if (!ReadFile(path, content)) {
@@ -71,8 +91,6 @@ bool App::NavigateTo(const std::string &pageName) {
return false;
}
TeardownCurrentPage();
if (Rml::DataModelConstructor constructor = ctx->CreateDataModel(pageName)) {
page->SetupDataModel(constructor);
page->model = constructor.GetModelHandle();
@@ -150,6 +168,10 @@ std::string App::GetAssetsPath() {
void App::TeardownCurrentPage() {
if (!currentPage) return;
lua_State* L = Rml::Lua::Interpreter::GetLuaState();
lua_pushnil(L);
lua_setglobal(L, currentPage->GetName().c_str());
currentPage->OnExit();
if (currentPage->hasModel) {