build: add build script and CMake helper for compiled packages

Compiling the compiler, the example and the demo by hand is error prone, so a
single script keeps the whole flow reproducible and ignores build outputs.
This commit is contained in:
BlackAngelTV committed 2026-11-18 08:48:05 +01:00
1 parent ab5ff6978a
commit 1ededcd655
6 files changed
+161

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
add_lua_package(luacpp_example_lua
ROOT "${CMAKE_CURRENT_SOURCE_DIR}/lua"
MODULES mathx.lua greet.lua
NAMESPACE demo)
add_executable(luacpp_example main.cpp)
target_link_libraries(luacpp_example PRIVATE luacpp_example_lua)
+14
View File
@@ -0,0 +1,14 @@
-- Example module that requires another compiled module.
local mathx = require("demo.mathx")
local M = {}
function M.hello(name)
return "Bonjour " .. name .. " !"
end
function M.double_factorial(n)
return mathx.factorial(n) * 2
end
return M
+29
View File
@@ -0,0 +1,29 @@
-- Example Lua module compiled into the C++ package demo::mathx.
local M = {}
function M.add(a, b)
return a + b
end
function M.factorial(n)
local result = 1
for i = 2, n do
result = result * i
end
return result
end
function M.summarise(values)
local total = 0
local count = #values
for _, v in ipairs(values) do
total = total + v
end
return {
sum = total,
count = count,
average = count > 0 and total / count or 0,
}
end
return M
+40
View File
@@ -0,0 +1,40 @@
// Shows how compiled Lua modules are consumed as C++ packages.
#include <iostream>
#include <vector>
#include <luacpp/rt.hpp>
#include "greet.hpp"
#include "mathx.hpp"
int main() {
luacpp::State state;
// 1. Namespaced facade generated from the exported Lua functions.
auto mathx = demo::mathx::bind(state);
auto greet = demo::greet::bind(state);
std::cout << "mathx.add(2, 3) = " << mathx.add(2, 3).to_string() << "\n";
std::cout << "mathx.factorial(6) = " << mathx.factorial(6).to_string() << "\n";
std::cout << "greet.hello(\"Buffy\") = " << greet.hello("Buffy").to_string() << "\n";
std::cout << "greet.double_factorial(5) = " << greet.double_factorial(5).to_string() << "\n";
// 2. Dynamic module handle (fallback when no facade is generated).
luacpp::Module mathx_module = state.module("demo.mathx");
std::vector<luacpp::Value> values{3.0, 4.0, 5.0};
luacpp::Value summary = mathx_module.get("summarise").call(values);
std::cout << "summarise({3,4,5}).sum = " << summary.get("sum").to_string() << "\n";
std::cout << "summarise({3,4,5}).average = " << summary.get("average").to_string() << "\n";
// 3. Host values visible from Lua, and Lua errors turned into C++ exceptions.
state.set_global("cpp_value", luacpp::Value(42));
state.do_string("print('lua sees cpp_value = ' .. cpp_value)");
try {
mathx.add("not a number", 1);
} catch (const luacpp::Error& error) {
std::cout << "caught Lua error: " << error.what() << "\n";
}
return 0;
}