From 017776a7f3008b97bfaa7bc74b8826c80cb9347a Mon Sep 17 00:00:00 2001 From: chris bell Date: Sun, 12 Jul 2026 20:40:32 -0500 Subject: [PATCH] Can now add a lua file with the same name as a page for page-scoped lua functionality --- assets/pages/lua-test.lua | 17 +++++++++++++++++ assets/pages/lua-test.rml | 4 ++++ src/app.cpp | 26 ++++++++++++++++++++++++-- 3 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 assets/pages/lua-test.lua diff --git a/assets/pages/lua-test.lua b/assets/pages/lua-test.lua new file mode 100644 index 0000000..8320eaa --- /dev/null +++ b/assets/pages/lua-test.lua @@ -0,0 +1,17 @@ +LuaTest = {} + +local counter = 0 + +function LuaTest.Test(event) + counter = counter + 1 + + local document = event.current_element.owner_document + + local target = document:GetElementById("lua-counter") + if target then + target.inner_rml = "Lua Counter: " .. counter + end + + print("Lua counter incremented to: " .. counter) + +end \ No newline at end of file diff --git a/assets/pages/lua-test.rml b/assets/pages/lua-test.rml index 623c967..f9e728c 100644 --- a/assets/pages/lua-test.rml +++ b/assets/pages/lua-test.rml @@ -2,4 +2,8 @@

Lua test page

This button uses NavigateTo('about') lua code instead of a registered C++ event

+ +

This button calls LuaTest.Test() from the scoped `lua-test.lua` file

+ +

diff --git a/src/app.cpp b/src/app.cpp index 6f28135..25a9b95 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -1,9 +1,13 @@ #include "app.hpp" #include #include +#include +#include #include #include #include +#include +#include #include 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) {