Files
BlackAngelTV 517ed0bf4d feat(compiler): add a Lua 5.4 to C++ module transpiler
Each Lua module becomes a header/source pair exposing a C++ namespace, so Lua
code can be linked and consumed like any C++ package while keeping the exact
semantics of the official 5.4 VM.
2026-11-18 08:48:05 +01:00

71 lines
2.5 KiB
CMake

# add_lua_package(<target>
# ROOT <dir> # directory the Lua module names are relative to
# MODULES <a.lua> [b.lua ...]
# [OUTPUT_DIR <dir>] # where the .hpp/.cpp files are generated
# [NAMESPACE <ns>]) # C++ namespace prefix, also prefixes Lua module names
#
# Creates an OBJECT library <target> holding the compiled Lua modules. Link it
# into an executable to make the modules part of the binary:
#
# add_lua_package(my_lua ROOT lua MODULES mathx.lua pkg/util.lua)
# target_link_libraries(my_app PRIVATE my_lua)
#
# The OBJECT library is used (instead of a static library) so that every module
# translation unit is kept, including the ones only reachable through `require`.
function(add_lua_package target)
cmake_parse_arguments(ARG "" "ROOT;OUTPUT_DIR;NAMESPACE" "MODULES" ${ARGN})
if(NOT ARG_MODULES)
message(FATAL_ERROR "add_lua_package(${target}): MODULES is required")
endif()
if(NOT TARGET luacpp)
message(FATAL_ERROR "add_lua_package(${target}): the 'luacpp' executable target is required")
endif()
if(NOT ARG_ROOT)
set(ARG_ROOT "${CMAKE_CURRENT_SOURCE_DIR}")
endif()
get_filename_component(_root "${ARG_ROOT}" ABSOLUTE)
if(ARG_OUTPUT_DIR)
get_filename_component(_out "${ARG_OUTPUT_DIR}" ABSOLUTE)
else()
set(_out "${CMAKE_CURRENT_BINARY_DIR}/luacpp_${target}")
endif()
set(_namespace_args "")
if(ARG_NAMESPACE)
set(_namespace_args --namespace "${ARG_NAMESPACE}")
endif()
set(_sources "")
foreach(_module IN LISTS ARG_MODULES)
get_filename_component(_abs "${_module}" ABSOLUTE BASE_DIR "${_root}")
if(NOT EXISTS "${_abs}")
message(FATAL_ERROR "add_lua_package(${target}): module not found: ${_abs}")
endif()
file(RELATIVE_PATH _rel "${_root}" "${_abs}")
string(REGEX REPLACE "\\.lua$" "" _stem "${_rel}")
string(REGEX REPLACE "/init$" "" _stem "${_stem}")
set(_hpp "${_out}/${_stem}.hpp")
set(_cpp "${_out}/${_stem}.cpp")
add_custom_command(
OUTPUT "${_hpp}" "${_cpp}"
COMMAND luacpp "${_abs}" --root "${_root}" --output "${_out}" ${_namespace_args}
DEPENDS "${_abs}" $<TARGET_FILE:luacpp>
COMMENT "luacpp: compiling ${_rel}"
VERBATIM)
list(APPEND _sources "${_cpp}")
endforeach()
add_library(${target} OBJECT ${_sources})
target_include_directories(${target} PUBLIC "${_out}")
target_link_libraries(${target} PUBLIC luacpp::rt)
set_target_properties(${target} PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED ON
POSITION_INDEPENDENT_CODE ON)
endfunction()