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

17
assets/pages/lua-test.lua Normal file
View File

@@ -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

View File

@@ -2,4 +2,8 @@
<h1>Lua test page</h1>
<p>This button uses <code>NavigateTo('about')</code> lua code instead of a registered C++ event</p>
<button onclick="NavigateTo('about')">Go to About Page</button>
<p>This button calls <code>LuaTest.Test()</code> from the scoped `lua-test.lua` file</p>
<button onclick="LuaTest.Test(event)">Click me!</button>
<p id="lua-counter"></p>
</div>

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) {