Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 26 additions & 11 deletions .github/workflows/c-cpp.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,13 @@ jobs:

- name: Install Dependencies
run: |
sudo apt-get update
pkg="liblua${{ matrix.lua_version }}-dev"
if [ "${{ matrix.lua_version }}" = "5.1" ]; then pkg=liblua5.1-0-dev; fi
sudo apt-get install -y "$pkg"
for attempt in 1 2 3 4 5; do
sudo apt-get update && sudo apt-get install -y "$pkg" && break
if [ "$attempt" = 5 ]; then exit 1; fi
sleep $((attempt * 15))
done

- name: Configure CMake
env:
Expand All @@ -47,24 +50,33 @@ jobs:
steps:
- uses: actions/checkout@v4

- name: Install LuaJIT
- name: Checkout pinned LuaJIT 2.1 sources
uses: actions/checkout@v4
with:
repository: LuaJIT/LuaJIT
ref: b82d612fe6d4d9901e63cb9fb9d7ddd201b03180
path: .ci-deps/luajit-src
persist-credentials: false

- name: Build shared LuaJIT
run: |
sudo apt-get update
sudo apt-get install -y libluajit-5.1-dev pkg-config
make -C .ci-deps/luajit-src -j"$(nproc)"
make -C .ci-deps/luajit-src install PREFIX="$PWD/.ci-deps/luajit"

- name: Configure CMake
run: |
LUA_INC=$(pkg-config --cflags-only-I luajit | awk '{print substr($1,3)}')
LUA_LIBDIR=$(pkg-config --variable=libdir luajit)
cmake -B build -DCMAKE_BUILD_TYPE=Release -DBLUA_BUILD_TESTS=ON \
-DLUA_INCLUDE_DIR="${LUA_INC}" \
-DLUA_LIBRARY="${LUA_LIBDIR}/libluajit-5.1.so"
-DLUA_INCLUDE_DIR="$PWD/.ci-deps/luajit/include/luajit-2.1" \
-DLUA_LIBRARY="$PWD/.ci-deps/luajit/lib/libluajit-5.1.so" \
-DCMAKE_BUILD_RPATH="$PWD/.ci-deps/luajit/lib"

- name: Build
run: |
cmake --build build --config Release

- name: Run Tests
env:
LD_LIBRARY_PATH: ${{ github.workspace }}/.ci-deps/luajit/lib
run: |
ctest --test-dir build --output-on-failure -C Release

Expand Down Expand Up @@ -134,8 +146,11 @@ jobs:
- uses: actions/checkout@v4
- name: Install Lua
run: |
sudo apt-get update
sudo apt-get install -y liblua5.4-dev
for attempt in 1 2 3 4 5; do
sudo apt-get update && sudo apt-get install -y liblua5.4-dev && break
if [ "$attempt" = 5 ]; then exit 1; fi
sleep $((attempt * 15))
done
- name: Configure Debug
run: |
cmake -B build -DCMAKE_BUILD_TYPE=Debug -DBLUA_ENABLE_SANITIZERS=${{ matrix.sanitizers }} \
Expand Down
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,9 @@ Testing/
*.swo
*~
.DS_Store

# Local Lua trees used for box builds, not part of the project
deps-lua/

# CI-only source builds, not part of the project
.ci-deps/
47 changes: 44 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,52 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

Prepared for a possible **v1.1.0** cut. Tagging and a GitHub Release are **not** created by this
change and still need explicit approval.

### Added
- Richer errors: missing Lua functions/tables include the path or name (`no function 'foo'`,
`no table 'bar' in path '...'`); conversion failures include a position prefix
(`argument 2:`, `return 1:`, `element 3:`).
- Value objects and smart pointers: copy-constructible registered classes can be pushed/read by
value (Lua owns the copy); `const T*` is a non-owning borrow; `std::unique_ptr<T>` can be moved
into Lua but not recovered; `std::shared_ptr<T>` shares the control block and can be recovered
only from exact-type shared-backed userdata.
- Inheritance: `reg_base<Derived, Base>` lets a derived pointer be used where a base is expected,
without weakening unrelated same-address type checks or adding implicit downcasts. Base methods
and properties are looked up on derived objects after `reg_base`.
- Lua-side DX: `reg_class_overload` (arity-only, including `self`); `__call` constructors on the
registered type name (`A(1)`); field properties via `__index` / `__newindex` in addition to
`get_` / `set_` methods; C++ `std::tuple` / `std::pair` multi-return.
- Sequence container indices use `lua_Integer` (`lua_rawgeti` / `lua_rawseti` on Lua 5.3+; a
pushinteger + rawget/rawset fallback on 5.1/5.2 when the index does not fit `int`).
`lua_createtable` hints are clamped to `int`.

### Changed
- CMake `project(bLua VERSION 1.1.0)`; `find_package(bLua 1.0)` still matches under
`SameMajorVersion`.
- README / README_CN: Lua 5.1, 5.2, and LuaJIT are listed as Supported (CI), matching already-green
remote jobs; document the new APIs and lifetime rules.

### Fixed
- Conversion-error context is stored in the Lua registry rather than `thread_local`, so LuaJIT
(shared library) still reports native `std::exception` messages through `call_lua_*` instead of
"unknown C++ exception".
- Callbacks no longer `lua_call` from inside the C++ exception boundary; Lua errors are caught
with `lua_pcall` and rethrown as C++ so MSVC does not abort with `0xC0000409` when `luaL_error`
would otherwise longjmp through a `try` block.
- `pcall_checked` no longer compares against `LUA_OK`, which is absent in Lua 5.1; it treats a
non-zero `lua_pcall` result as failure, matching the other protected-call sites.

### CI follow-up
- Permit LuaJIT's foreign unwinder through callback boundaries while still translating typed
native C++ exceptions, including non-`std::exception` throws; do not mark the boundary noexcept.
- Windows CI builds pinned official Lua 5.4.7 sources with MSVC instead of downloading an
unbounded latest vcpkg port from lua.org; all regression/relocation tests remain enabled.
- Linux LuaJIT CI builds a pinned LuaJIT 2.1 shared library from source instead of
`apt-get install libluajit-5.1-dev`, after Ubuntu universe mirrors returned 503s.
Official Lua 5.x jobs retry `apt-get` on the same class of transient fetch errors.
- Windows CI builds pinned official Lua 5.4.7 sources (lua/lua commit used by `test/lua-runtime`)
with MSVC, not a vcpkg Lua port or an unbounded lua.org download; all regression/relocation
tests remain enabled.

### Safety / contract changes after PR #2
- Class registration data and copied type names are now state-local. `set_type_name<T>` /
Expand Down Expand Up @@ -43,7 +84,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Container helpers: `std::vector` / `std::map` ↔ Lua table via `push_vector` / `to_vector` / `push_map` / `to_map` and matching `native_to_lua` / `lua_to_native` specializations for common element types.
- API DX: `reg_constructor`, `reg_property` (data member or getter/setter), `reg_enum`, and `reg_global_overload` (dispatch by argument count).
- Stronger tests: type errors, GC/ownership, custom deleter, nullptr string, multi-return edge cases, containers, ctor/property/enum/overload.
- CI: Windows (vcpkg Lua) and Linux LuaJIT jobs; existing Linux (GCC/Clang × Lua 5.1–5.4) and macOS jobs retained.
- CI: Windows (pinned official Lua 5.4.7 / MSVC via `test/lua-runtime`) and Linux LuaJIT jobs; existing Linux (GCC/Clang × Lua 5.1–5.4) and macOS jobs retained.
- Docs: Lua version compatibility matrix in README / README_CN.

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 3.15...3.30)
project(bLua
VERSION 1.0.0
VERSION 1.1.0
DESCRIPTION "A lightweight, header-only C++17 Lua bridge library"
HOMEPAGE_URL "https://github.com/esrrhs/bLua"
LANGUAGES CXX
Expand Down
69 changes: 56 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ A header-only C++ and Lua glue/bridge library (`b` stands for bridge). Built on
* **Non-intrusive**: No need to inherit from any base class or decorate classes with intrusive macros.
* **Configurable ownership**: Owning / non-owning / custom deleter so Lua `__gc` does not free C++-owned pointers.
* **Stable type names**: User-provided metatable names (demangled `typeid` fallback on GCC/Clang).
* **API DX**: Constructors, properties, enums, and arity-based free-function overloads.
* **API DX**: `__call` constructors, field properties, enums, arity-based free-function and class-method overloads, and C++ `std::tuple` / `std::pair` multi-return.
* **Value objects and smart pointers**: Copy-in class values, `const T*` borrows, move-only `std::unique_ptr`, and `std::shared_ptr` sharing.
* **Inheritance**: `reg_base<Derived, Base>` so a derived pointer can be used where a base is expected.
* **Modern CMake**: First-class support for `find_package(bLua)`, `FetchContent`, and CTest unit testing.

## Lua version matrix
Expand All @@ -30,8 +32,8 @@ A header-only C++ and Lua glue/bridge library (`b` stands for bridge). Built on
|---------|--------|-------|
| Lua 5.4 | Supported (CI) | Primary target |
| Lua 5.3 | Supported (CI) | |
| Lua 5.2 | Supported (CI configuration) | Version-neutral getter wrappers |
| Lua 5.1 / LuaJIT | Supported (CI configuration) | Private compatibility helpers; no Lua API macro overrides |
| Lua 5.2 | Supported (CI) | Version-neutral getter wrappers |
| Lua 5.1 / LuaJIT | Supported (CI) | Private compatibility helpers; no Lua API macro overrides |

## Usage

Expand Down Expand Up @@ -60,18 +62,25 @@ bLua::reg_class_func(L, "set_string", &A::set_string);
// bLua::reg_class_with_deleter<A>(L, my_free_A, "A");

// Constructor / property / enum / overload
bLua::reg_constructor<A, int>(L, "A_new");
bLua::reg_property(L, "a", &A::m_a); // get_a / set_a
bLua::reg_constructor<A, int>(L, "A_new"); // also enables A(1) via __call
bLua::reg_property(L, "a", &A::m_a); // a.a field plus get_a / set_a
bLua::reg_enum<Color>(L, "Color", {{"Red", Color::Red}, {"Green", Color::Green}});
bLua::reg_global_overload(L, "add", add1, add2); // dispatch by argument count
// bLua::reg_class_overload(L, "add", static_cast<int(A::*)() const>(&A::add),
// static_cast<int(A::*)(int) const>(&A::add));
// bLua::reg_base<Derived, Base>(L); // after both classes are registered
// bLua::push(L, std::make_unique<A>(1)); // move ownership into Lua
// bLua::push(L, std::make_shared<A>(1)); // share ownership with Lua
```

Then invoke them in Lua:

```lua
local a = newA()
local a = newA() -- or A() / A(1) after reg_constructor
a:set_int(123)
print("a:get_int() ", a:get_int())
a.a = 10 -- field property
print("a.a", a.a)
a:set_string("abc")
print("a:get_string() ", a:get_string())
```
Expand All @@ -94,7 +103,9 @@ const char* name = bLua::get_type_name<B>(L); // borrowed until state closes
* Within one state, the same address and type reuse one live userdata. An explicit
`push(L, ptr, ownership)` with conflicting ownership is rejected, never silently adopted.
Implicit pushes/returned pointers reuse an existing wrapper's policy; class defaults apply
only to new wrappers. Different types at the same address are rejected (no inheritance casts).
only to new wrappers. Unrelated types at the same address are rejected. After `reg_base<Derived, Base>`,
a derived pointer may be used where a base is expected, and base methods/properties are visible
on derived objects; implicit downcasts are not performed.
* Constructors always return Lua-owned objects, even for a non-owning class default.
Custom deleters must match the allocation and must not throw; each wrapper calls its captured
deleter at most once. Repeated `__gc` is harmless; methods/properties reject finalized objects.
Expand All @@ -109,7 +120,9 @@ const char* name = bLua::get_type_name<B>(L); // borrowed until state closes
### Errors and type conversion

`call_lua_global_func` / `call_lua_table_func` return an error string for Lua execution,
missing functions/tables, native exceptions, and result/argument conversion failures. The
missing functions/tables, native exceptions, and result/argument conversion failures.
Lookup failures include the function or table path (`no function 'foo'`, `no table 'bar' in path '...'`).
Conversion failures include a position prefix (`argument 2:`, `return 1:`, `element 3:`). The
caller's Lua stack is restored. Result values are converted before updating outputs, so a
conversion failure does not partially overwrite them. Debug/traceback is optional; arbitrary
Lua error objects get a safe fallback message. Function/path lookup uses raw table keys,
Expand All @@ -130,11 +143,41 @@ longjmp over C++ temporaries during allocations; treat it as fatal rather than r

### Overload / property scope

`reg_global_overload` dispatches by argument count only and rejects duplicate arities before
replacing the global function. Same-arity, type-based overload resolution is not implemented;
use distinct Lua names or an explicit `static_cast` when selecting a C++ overloaded function.
`reg_property` creates `get_name`/`set_name` methods, not Lua field accessors. Const data members
are getter-only; const getter functions can be paired with a setter.
`reg_global_overload` and `reg_class_overload` dispatch by argument count only (class methods
include `self`) and reject duplicate arities before replacing the binding. Same-arity, type-based
overload resolution is not implemented; use distinct Lua names or an explicit `static_cast` when
selecting a C++ overloaded function.
`reg_property` still creates `get_name`/`set_name` methods and also installs Lua field accessors
through `__index` / `__newindex`. Const data members are getter-only; const getter functions can
be paired with a setter. `reg_constructor` still registers an optional named global and also
makes the registered type name a callable class table (`A(1)`). Additional named constructors
with the same arity reuse the existing `__call` slot.

Registered C++ functions may return `std::tuple` or `std::pair` to produce multiple Lua results.

### Inheritance, values, and smart pointers

Call `reg_base<Derived, Base>(L)` after both classes are registered and **before** objects are
pushed, so identity-cache aliases can be recorded. `Derived*` (and Derived userdata) may be passed
where `Base*` is expected. There is no implicit downcast: a standalone `Base*` is rejected as
`Derived*`. `reg_base` requires a unique, unambiguously `static_cast`-able public base; virtual
bases and ambiguous multiple inheritance are not supported. Unrelated types at the same address
are still rejected. Multiple distinct subobject addresses can be aliased when `static_cast`
adjusts the pointer.

Copy-constructible registered classes can be pushed and read by value: the push copies into a new
Lua-owned object; the get copies out of the userdata. `const T*` is always a non-owning borrow
and cannot be Lua-owned. `std::unique_ptr<T>` must be moved into Lua (`push(L, std::move(p))` or
returned from a registered function); Lua then owns the object. It cannot be recovered as a
`unique_ptr` (that would steal from Lua). `std::shared_ptr<T>` copies the control block into the
wrapper; `lua_to_native` / parameters recover a `shared_ptr<T>` only from an exact-type
shared-backed userdata, not from a raw/unique wrapper or a derived `shared_ptr`. Do not mix a
unique or raw-owning wrapper with a `shared_ptr` at the same address. As with other owning
wrappers, do not give multiple Lua states owning references to the same allocation.

Sequence containers use `lua_Integer` indices (`lua_rawgeti` / `lua_rawseti` on Lua 5.3+; a
`lua_pushinteger` + `lua_rawget` / `lua_rawset` fallback on 5.1/5.2 when the index does not fit
`int`). `lua_createtable` hints are clamped to `int` because that is what the Lua API accepts.

### 2. Containers
```cpp
Expand Down
Loading
Loading