From 339949ee913545fc8b93506b2f1abee96d5e9ac4 Mon Sep 17 00:00:00 2001 From: esrrhs Date: Tue, 1 Dec 2026 21:18:52 +0800 Subject: [PATCH 1/5] feat: richer errors, values/smart pointers, inheritance, and Lua-side DX Add named lookup and positional conversion errors; by-value classes, const T* borrows, unique_ptr move-in and shared_ptr sharing; reg_base safe upcasts with inherited methods/properties; class method overloads, __call constructors, field properties, and tuple multi-return; and lua_Integer container indices. Prepare CMake/docs for a possible v1.1.0 without tagging a release. --- .gitignore | 3 + CHANGELOG.md | 34 ++- CMakeLists.txt | 2 +- README.md | 69 +++++- README_CN.md | 59 ++++- bLua.h | 585 ++++++++++++++++++++++++++++++++++++++++---- test/regression.cpp | 180 +++++++++++++- test/test.cpp | 8 + 8 files changed, 867 insertions(+), 73 deletions(-) diff --git a/.gitignore b/.gitignore index 4e0e44a..152ab8f 100644 --- a/.gitignore +++ b/.gitignore @@ -46,3 +46,6 @@ Testing/ *.swo *~ .DS_Store + +# Local Lua trees used for box builds, not part of the project +deps-lua/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 168faac..e2e6101 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,11 +7,39 @@ 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` can be moved + into Lua but not recovered; `std::shared_ptr` shares the control block and can be recovered + only from exact-type shared-backed userdata. +- Inheritance: `reg_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. + ### 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. +- 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` / @@ -43,7 +71,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 diff --git a/CMakeLists.txt b/CMakeLists.txt index e4f383b..46ceda2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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 diff --git a/README.md b/README.md index 36b0230..11095b5 100644 --- a/README.md +++ b/README.md @@ -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` 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 @@ -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 @@ -60,18 +62,25 @@ bLua::reg_class_func(L, "set_string", &A::set_string); // bLua::reg_class_with_deleter(L, my_free_A, "A"); // Constructor / property / enum / overload -bLua::reg_constructor(L, "A_new"); -bLua::reg_property(L, "a", &A::m_a); // get_a / set_a +bLua::reg_constructor(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(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(&A::add), +// static_cast(&A::add)); +// bLua::reg_base(L); // after both classes are registered +// bLua::push(L, std::make_unique(1)); // move ownership into Lua +// bLua::push(L, std::make_shared(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()) ``` @@ -94,7 +103,9 @@ const char* name = bLua::get_type_name(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`, + 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. @@ -109,7 +120,9 @@ const char* name = bLua::get_type_name(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, @@ -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(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` 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` copies the control block into the +wrapper; `lua_to_native` / parameters recover a `shared_ptr` 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 diff --git a/README_CN.md b/README_CN.md index c563dfd..84c514b 100644 --- a/README_CN.md +++ b/README_CN.md @@ -21,7 +21,9 @@ C++ 与 Lua 的胶水层(Header-only),`b` 代表 bridge。基于现代 C++ * **无侵入**:C++ 类无需继承任何基类或添加宏。 * **可配置所有权**:owning / non-owning / 自定义 deleter,避免非 Lua 拥有的指针被 `__gc` 误删。 * **稳定类型名**:可为类指定 metatable 名(GCC/Clang 上回退到 demangle 后的 typeid)。 -* **API 体验**:构造函数、属性、枚举、按参数个数分发的重载注册。 +* **API 体验**:`__call` 构造、字段属性、枚举、按参数个数分发的全局/类方法重载,以及 C++ `std::tuple` / `std::pair` 多返回值。 +* **值对象与智能指针**:按值拷贝入库、`const T*` 借用、`std::unique_ptr` 移动移交、`std::shared_ptr` 共享所有权。 +* **继承**:`reg_base`,派生类指针可用于期望基类的地方。 * **现代 CMake**:支持 `find_package(bLua)`、`FetchContent` 以及 CTest 单元测试。 ## Lua 版本兼容矩阵 @@ -30,8 +32,8 @@ C++ 与 Lua 的胶水层(Header-only),`b` 代表 bridge。基于现代 C++ |--------|------|------| | Lua 5.4 | 支持(CI) | 主目标 | | Lua 5.3 | 支持(CI) | | -| Lua 5.2 | 支持(已配置 CI) | 使用版本无关的 getter 包装 | -| Lua 5.1 / LuaJIT | 支持(已配置 CI) | 私有兼容辅助,不覆盖 Lua API 宏 | +| Lua 5.2 | 支持(CI) | 使用版本无关的 getter 包装 | +| Lua 5.1 / LuaJIT | 支持(CI) | 私有兼容辅助,不覆盖 Lua API 宏 | ## 用法 ### 1. Lua 调用 C++ @@ -58,17 +60,24 @@ bLua::reg_class_func(L, "set_string", &A::set_string); // bLua::reg_class_with_deleter(L, my_free_A, "A"); // 构造函数 / 属性 / 枚举 / 重载 -bLua::reg_constructor(L, "A_new"); -bLua::reg_property(L, "a", &A::m_a); // get_a / set_a +bLua::reg_constructor(L, "A_new"); // 同时启用 A(1)(__call) +bLua::reg_property(L, "a", &A::m_a); // a.a 字段以及 get_a / set_a bLua::reg_enum(L, "Color", {{"Red", Color::Red}, {"Green", Color::Green}}); bLua::reg_global_overload(L, "add", add1, add2); // 按参数个数分发 +// bLua::reg_class_overload(L, "add", static_cast(&A::add), +// static_cast(&A::add)); +// bLua::reg_base(L); // 两个类都注册之后 +// bLua::push(L, std::make_unique(1)); // 把所有权移交给 Lua +// bLua::push(L, std::make_shared(1)); // 与 Lua 共享所有权 ``` 然后在 Lua 中使用即可: ```lua -local a = newA() +local a = newA() -- 注册构造函数后也可用 A() / A(1) a:set_int(123) print("a:get_int() ", a:get_int()) +a.a = 10 -- 字段属性 +print("a.a", a.a) a:set_string("abc") print("a:get_string() ", a:get_string()) ``` @@ -90,7 +99,8 @@ const char* name = bLua::get_type_name(L); // 借用到状态关闭/名字变 `std::runtime_error`。跨编译器稳定的名字请显式指定,demangle 仅作回退。 * 同一状态中,同地址同类型复用活跃 userdata;显式 `push(L,ptr,ownership)` 与已有策略冲突会报错,不会偷偷接管。隐式推送/函数返回指针复用已有策略, - 类默认策略仅用于新包装。同地址不同类型拒绝绑定(不提供继承转换)。 + 类默认策略仅用于新包装。同地址的无关类型仍会拒绝。注册 `reg_base` 后, + 派生类指针可用于期望基类的场合,基类方法/属性在派生对象上可见;不会做隐式向下转换。 * 构造函数始终产生 Lua-owned 对象,即使类默认为 non-owning。 自定义 deleter 必须匹配分配方式且不得抛异常;每个包装最多调用一次。 重复 `__gc` 安全;已失效对象的方法/属性访问会报错。 @@ -104,6 +114,8 @@ const char* name = bLua::get_type_name(L); // 借用到状态关闭/名字变 `call_lua_global_func` / `call_lua_table_func` 将 Lua 错误、函数/路径缺失、 原生异常、参数/返回值转换失败转换为错误字符串,并恢复调用前的 Lua 栈。 +查找失败会带上函数或路径名(`no function 'foo'`、`no table 'bar' in path '...'`); +转换失败会带位置前缀(`argument 2:`、`return 1:`、`element 3:`)。 全部返回值转换成功才写入输出,转换失败不会部分修改结果;用户自定义 C++ 输出类型的赋值/分配异常不保证事务性。`debug.traceback` 可缺失,非字符串错误对象 也有兜底消息。函数和路径用原始 table key 查找,不触发 `__index`。 @@ -120,10 +132,35 @@ const char* name = bLua::get_type_name(L); // 借用到状态关闭/名字变 ### 重载与属性范围 -`reg_global_overload` 仅按参数个数分发;重复 arity 在替换全局函数前报错。 -同参数个数按类型选重载尚未实现,可使用不同 Lua 名;选择 C++ 重载函数时可显式 -`static_cast`。`reg_property` 生成 `get_name`/`set_name` 方法,不是 Lua 字段访问器; -const 数据成员只生成 getter,const getter 方法可配 setter。 +`reg_global_overload` 与 `reg_class_overload` 都只按参数个数分发(类方法计入 `self`), +重复 arity 在替换绑定前报错。同参数个数按类型选重载尚未实现,可使用不同 Lua 名; +选择 C++ 重载函数时可显式 `static_cast`。 +`reg_property` 仍生成 `get_name`/`set_name` 方法,并通过 `__index` / `__newindex` +安装字段访问器;const 数据成员只生成 getter,const getter 方法可配 setter。 +`reg_constructor` 仍可注册可选的命名全局函数,同时把类型名变成可调用的类表(`A(1)`)。 +同一 arity 的额外命名构造函数会复用已有的 `__call` 槽位。 + +注册到 Lua 的 C++ 函数可以返回 `std::tuple` 或 `std::pair`,对应多个 Lua 返回值。 + +### 继承、值对象与智能指针 + +在两个类都注册之后、**推送对象之前**调用 `reg_base(L)`,以便写入身份缓存别名。 +`Derived*`(以及 Derived userdata)可用于期望 `Base*` 的地方。不做隐式向下转换:独立的 +`Base*` 不能当作 `Derived*`。`reg_base` 要求唯一、可明确 `static_cast` 的公有基类;不支持 +虚基类和有歧义的多重继承。同地址的无关类型仍会拒绝。当 `static_cast` 需要调整地址时, +可以为不同子对象地址建立缓存别名。 + +可拷贝构造的已注册类可按值推送和读出:推送时拷贝为 Lua 拥有的新对象,读出时再拷贝。 +`const T*` 始终是非拥有借用,不能由 Lua 拥有。`std::unique_ptr` 必须移入 Lua +(`push(L, std::move(p))` 或由注册函数返回);随后由 Lua 拥有,不能再取回 `unique_ptr` +(那相当于从 Lua 偷走对象)。`std::shared_ptr` 会把控制块拷进包装;只有精确类型、 +且由 `shared_ptr` 推入的 userdata 才能再取出 `shared_ptr`,不能从 raw/unique 包装或 +派生类的 `shared_ptr` 恢复。不要在同一地址上混用 unique/原始 owning 包装与 `shared_ptr`。 +与其它 owning 包装一样,不要让多个 Lua 状态同时拥有同一块分配。 + +序列容器下标使用 `lua_Integer`(Lua 5.3+ 走 `lua_rawgeti` / `lua_rawseti`;在 5.1/5.2 上, +当下标无法装入 `int` 时回退到 `lua_pushinteger` + `lua_rawget` / `lua_rawset`)。 +`lua_createtable` 的容量提示会截断到 `int`,因为这是 Lua API 的限制。 ### 2. 容器转换 ```cpp diff --git a/bLua.h b/bLua.h index e1e7cc0..c2f5493 100644 --- a/bLua.h +++ b/bLua.h @@ -85,6 +85,41 @@ namespace bLua { lua_pushstring(L, name); lua_rawget(L, i); } + inline int table_hint(size_t n) { + constexpr size_t cap = static_cast(std::numeric_limits::max()); + return n > cap ? std::numeric_limits::max() : static_cast(n); + } + inline void rawgeti_idx(lua_State *L, int i, lua_Integer n) { + ensure_stack(L, 2); + i = absindex(L, i); +#if LUA_VERSION_NUM >= 503 + lua_rawgeti(L, i, n); +#else + if (n >= static_cast(std::numeric_limits::min()) && + n <= static_cast(std::numeric_limits::max())) { + lua_rawgeti(L, i, static_cast(n)); + } else { + lua_pushinteger(L, n); + lua_rawget(L, i); + } +#endif + } + inline void rawseti_idx(lua_State *L, int i, lua_Integer n) { + ensure_stack(L, 2); + i = absindex(L, i); +#if LUA_VERSION_NUM >= 503 + lua_rawseti(L, i, n); +#else + if (n >= static_cast(std::numeric_limits::min()) && + n <= static_cast(std::numeric_limits::max())) { + lua_rawseti(L, i, static_cast(n)); + } else { + lua_pushinteger(L, n); + lua_insert(L, -2); + lua_rawset(L, i); + } +#endif + } inline void globals(lua_State *L) { #if LUA_VERSION_NUM < 502 lua_pushvalue(L, LUA_GLOBALSINDEX); @@ -100,7 +135,38 @@ namespace bLua { stack_guard(const stack_guard &) = delete; stack_guard &operator=(const stack_guard &) = delete; }; - [[noreturn]] inline void fail(const char *s) { throw std::runtime_error(s); } + struct conv_scope { + const char *kind; + int index; + conv_scope *prev; + static conv_scope *&head() { + static thread_local conv_scope *h = nullptr; + return h; + } + conv_scope(const char *k, int i) : kind(k), index(i), prev(head()) { head() = this; } + ~conv_scope() { head() = prev; } + conv_scope(const conv_scope &) = delete; + conv_scope &operator=(const conv_scope &) = delete; + }; + inline std::string conv_prefix() { + std::vector stack; + for (auto *c = conv_scope::head(); c; c = c->prev) stack.push_back(c); + std::string pre; + for (auto it = stack.rbegin(); it != stack.rend(); ++it) { + if (!pre.empty()) pre += ": "; + pre += (*it)->kind; + if ((*it)->index > 0) { + pre += ' '; + pre += std::to_string((*it)->index); + } + } + return pre; + } + [[noreturn]] inline void fail(const std::string &s) { + auto pre = conv_prefix(); + throw std::runtime_error(pre.empty() ? s : pre + ": " + s); + } + [[noreturn]] inline void fail(const char *s) { fail(std::string(s ? s : "")); } // Never luaL_error while an exception / argument tuple is alive. All validation // below throws C++; only this outermost callback converts it to a Lua error. @@ -124,7 +190,12 @@ namespace bLua { template inline char type_key; template inline char meta_key; template inline char table_key; + template inline char class_table_key; + template inline char getters_key; + template inline char setters_key; + inline char parents_key; inline char cache_key; + enum class hold : unsigned char { none, shared }; template const std::string &fallback_name() { static const std::string name = [] { @@ -144,6 +215,16 @@ namespace bLua { ownership own = ownership::owning; void (*deleter)(T *) = &delete_object; bool registered = false; + struct upcast { + const void *derived_table; + const void *derived_type; + void *(*cast)(void *); + }; + struct base_alias { + void *(*to_base)(void *); + }; + std::vector upcasts; + std::vector bases; }; template int free_state(lua_State *L) { // Private metatable, not exposed through any object. @@ -176,11 +257,21 @@ namespace bLua { void *ptr; bool alive; bool owning; + hold extra_kind; + void *extra; + void (*drop_extra)(void *); }; template struct userdata { userdata_base base; void (*const deleter)(T *); // fixed when this wrapper is created }; + template void drop_holder(void *e) { delete static_cast(e); } + inline void clear_extra(userdata_base *ud) { + if (ud->drop_extra && ud->extra) ud->drop_extra(ud->extra); + ud->extra = nullptr; + ud->drop_extra = nullptr; + ud->extra_kind = hold::none; + } template userdata *test_object(lua_State *L, int i) { ensure_stack(L, 3); i = absindex(L, i); @@ -193,29 +284,121 @@ namespace bLua { auto ud = static_cast *>(lua_touserdata(L, i)); return ud->base.type == &type_key ? ud : nullptr; } + // Validate the metatable against a known derived type before reading bytes. + template T *try_upcast_ptr(lua_State *L, int i) { + ensure_stack(L, 4); + i = absindex(L, i); + if (lua_type(L, i) != LUA_TUSERDATA) return nullptr; + if (!lua_getmetatable(L, i)) return nullptr; + const auto &meta = state(L); + for (const auto &u : meta.upcasts) { + rawgetp(L, LUA_REGISTRYINDEX, u.derived_table); + const bool match = lua_rawequal(L, -1, -2); + lua_pop(L, 1); + if (!match) continue; + lua_pop(L, 1); + auto ud = static_cast(lua_touserdata(L, i)); + if (!ud || ud->type != u.derived_type) return nullptr; + if (!ud->alive || !ud->ptr) fail("object has been destroyed"); + return static_cast(u.cast(ud->ptr)); + } + lua_pop(L, 1); + return nullptr; + } template T *check_t(lua_State *L, int i) { - auto ud = test_object(L, i); - if (!ud) fail("wrong userdata type (or class is not registered)"); - if (!ud->base.alive || !ud->base.ptr) fail("object has been destroyed"); - return static_cast(ud->base.ptr); + if (auto ud = test_object(L, i)) { + if (!ud->base.alive || !ud->base.ptr) fail("object has been destroyed"); + return static_cast(ud->base.ptr); + } + if (auto *p = try_upcast_ptr(L, i)) return p; + auto &meta = state(L); + if (!meta.registered) fail("wrong userdata type (or class is not registered)"); + fail(std::string("expected ") + meta.name + " (or derived)"); } template int free_class(lua_State *L) { auto ud = test_object(L, 1); - if (!ud || !ud->base.alive) return 0; + if (!ud) return 0; auto p = static_cast(ud->base.ptr); + const bool alive = ud->base.alive; ud->base.ptr = nullptr; ud->base.alive = false; // invalidate before any possibly re-entrant deleter - if (ud->base.owning && p) ud->deleter(p); + if (alive && ud->base.owning && p && ud->deleter) ud->deleter(p); + clear_extra(&ud->base); return 0; } + template void alias_bases(lua_State *L, T *p, int cache_idx, int ud_idx) { + cache_idx = absindex(L, cache_idx); + ud_idx = absindex(L, ud_idx); + for (const auto &b : state(L).bases) { + void *addr = b.to_base(static_cast(p)); + lua_pushvalue(L, ud_idx); + rawsetp(L, cache_idx, addr); + } + } + template bool reuse_cached(lua_State *L, T *p, ownership own, void (*del)(T *), bool reuse_policy) { + if (auto ud = test_object(L, -1)) { + if (ud->base.alive) { + if (!reuse_policy && (ud->base.owning != (own == ownership::owning) || ud->deleter != del)) + fail("pointer ownership/deleter conflict"); + lua_remove(L, -2); + return true; + } + return false; + } + if (try_upcast_ptr(L, -1) == p) { + auto hdr = static_cast(lua_touserdata(L, -1)); + if (!hdr || !hdr->alive) fail("object has been destroyed"); + const bool cached_owning = hdr->owning; + if (!reuse_policy && cached_owning != (own == ownership::owning)) + fail("pointer ownership/deleter conflict"); + lua_remove(L, -2); + return true; + } + if (!lua_isnil(L, -1)) fail("pointer is already exposed with a different type"); + return false; + } template void push_ptr(lua_State *L, T *p, ownership own, bool reuse_policy = false) { - static_assert(!std::is_const_v, "const object pointers are not supported"); - if (!p) { lua_pushnil(L); return; } + using U = std::remove_const_t; + if constexpr (std::is_const_v) { + if (own == ownership::owning) fail("const pointers cannot be Lua-owned"); + push_ptr(L, const_cast(p), ownership::non_owning, reuse_policy); + return; + } else { + if (!p) { lua_pushnil(L); return; } + auto &meta = state(L); + if (!meta.registered) fail("register class before pushing its objects"); + auto del = own == ownership::owning ? meta.deleter : nullptr; + const int top = lua_gettop(L); + ensure_stack(L, 8); + try { + rawgetp(L, LUA_REGISTRYINDEX, &cache_key); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + lua_newtable(L); + lua_newtable(L); + lua_pushliteral(L, "v"); lua_setfield(L, -2, "__mode"); + lua_setmetatable(L, -2); + lua_pushvalue(L, -1); rawsetp(L, LUA_REGISTRYINDEX, &cache_key); + } + rawgetp(L, -1, p); + if (reuse_cached(L, p, own, del, reuse_policy)) return; + lua_pop(L, 1); + auto ud = static_cast *>(lua_newuserdata(L, sizeof(userdata))); + new (ud) userdata{{&type_key, p, true, own == ownership::owning, hold::none, nullptr, nullptr}, del}; + push_metatable(L); lua_setmetatable(L, -2); + lua_pushvalue(L, -1); rawsetp(L, -3, p); + alias_bases(L, p, -2, -1); + lua_remove(L, -2); + } catch (...) { lua_settop(L, top); throw; } + } + } + template void push_shared(lua_State *L, const std::shared_ptr &holder) { + if (!holder) { lua_pushnil(L); return; } + T *p = holder.get(); auto &meta = state(L); if (!meta.registered) fail("register class before pushing its objects"); - auto del = own == ownership::owning ? meta.deleter : nullptr; const int top = lua_gettop(L); - ensure_stack(L, 6); + ensure_stack(L, 8); try { rawgetp(L, LUA_REGISTRYINDEX, &cache_key); if (lua_isnil(L, -1)) { @@ -227,24 +410,35 @@ namespace bLua { lua_pushvalue(L, -1); rawsetp(L, LUA_REGISTRYINDEX, &cache_key); } rawgetp(L, -1, p); - if (!lua_isnil(L, -1)) { - auto ud = test_object(L, -1); - if (!ud) fail("pointer is already exposed with a different type"); - if (ud->base.alive) { - if (!reuse_policy && (ud->base.owning != (own == ownership::owning) || ud->deleter != del)) - fail("pointer ownership/deleter conflict"); - lua_remove(L, -2); - return; - } + if (auto ud = test_object(L, -1)) { + if (!ud->base.alive) fail("object has been destroyed"); + if (ud->base.extra_kind != hold::shared || !ud->base.extra) + fail("pointer ownership/deleter conflict"); + *static_cast *>(ud->base.extra) = holder; + lua_remove(L, -2); + return; } + if (!lua_isnil(L, -1)) fail("pointer is already exposed with a different type"); lua_pop(L, 1); auto ud = static_cast *>(lua_newuserdata(L, sizeof(userdata))); - new (ud) userdata{{&type_key, p, true, own == ownership::owning}, del}; + new (ud) userdata{{&type_key, p, true, true, hold::shared, + new std::shared_ptr(holder), &drop_holder>}, nullptr}; push_metatable(L); lua_setmetatable(L, -2); lua_pushvalue(L, -1); rawsetp(L, -3, p); + alias_bases(L, p, -2, -1); lua_remove(L, -2); } catch (...) { lua_settop(L, top); throw; } } + template void push_unique(lua_State *L, std::unique_ptr holder) { + if (!holder) { lua_pushnil(L); return; } + T *p = holder.release(); + try { + push_ptr(L, p, ownership::owning, false); + } catch (...) { + holder.reset(p); + throw; + } + } template struct converter; template T lua_to_native(lua_State *L, int i) { return converter::get(L, i); } @@ -330,8 +524,66 @@ namespace bLua { static void push(lua_State *L, std::nullptr_t) { lua_pushnil(L); } }; template struct converter, char>>> { - static T *get(lua_State *L, int i) { return lua_isnil(L, i) ? nullptr : check_t(L, i); } - static void push(lua_State *L, T *p) { push_ptr(L, p, state(L).own, true); } + static T *get(lua_State *L, int i) { + using U = std::remove_const_t; + if (lua_isnil(L, i)) return nullptr; + return check_t(L, i); + } + static void push(lua_State *L, T *p) { + using U = std::remove_const_t; + if constexpr (std::is_const_v) + push_ptr(L, const_cast(p), ownership::non_owning, true); + else + push_ptr(L, p, state(L).own, true); + } + }; + template struct is_unique_ptr : std::false_type {}; + template struct is_unique_ptr> : std::true_type {}; + template struct is_shared_ptr : std::false_type {}; + template struct is_shared_ptr> : std::true_type {}; + template struct is_std_vector : std::false_type {}; + template struct is_std_vector> : std::true_type {}; + template struct is_std_map : std::false_type {}; + template struct is_std_map> : std::true_type {}; + template struct is_tuple_like : std::false_type {}; + template struct is_tuple_like> : std::true_type {}; + template struct is_tuple_like> : std::true_type {}; + template struct is_optional : std::false_type {}; + template struct is_optional> : std::true_type {}; + template constexpr bool is_user_class_v = + std::is_class_v && std::is_copy_constructible_v && + !std::is_same_v && !std::is_same_v && + !is_unique_ptr::value && !is_shared_ptr::value && + !is_std_vector::value && !is_std_map::value && !is_tuple_like::value && + !is_optional::value; + template struct converter> { + static std::unique_ptr get(lua_State *, int) { + fail("unique_ptr can only be moved into Lua, not recovered"); + return {}; + } + static void push(lua_State *, const std::unique_ptr &) { + fail("unique_ptr must be moved into Lua"); + } + }; + template void native_to_lua(lua_State *L, std::unique_ptr &&v) { push_unique(L, std::move(v)); } + template struct converter> { + static std::shared_ptr get(lua_State *L, int i) { + if (lua_isnil(L, i)) return {}; + auto ud = test_object(L, i); + if (!ud) fail(std::string("expected shared_ptr-backed ") + state(L).name); + if (!ud->base.alive || !ud->base.ptr) fail("object has been destroyed"); + if (ud->base.extra_kind != hold::shared || !ud->base.extra) + fail("userdata is not shared_ptr-backed"); + return *static_cast *>(ud->base.extra); + } + static void push(lua_State *L, const std::shared_ptr &p) { push_shared(L, p); } + }; + template struct converter>> { + static T get(lua_State *L, int i) { return *check_t(L, i); } + static void push(lua_State *L, const T &v) { + auto p = std::make_unique(v); + push_unique(L, std::move(p)); + } }; template struct converter>> { using U = std::underlying_type_t; @@ -344,7 +596,10 @@ namespace bLua { if (!lua_istable(L, i)) fail("table expected for vector"); std::vector result; const size_t n = rawlen(L, i); result.reserve(n); for (size_t k = 1; k <= n; ++k) { - lua_rawgeti(L, i, static_cast(k)); + const lua_Integer idx = static_cast(k); + conv_scope scope("element", idx > 0 && idx <= std::numeric_limits::max() + ? static_cast(idx) : 0); + rawgeti_idx(L, i, idx); result.push_back(lua_to_native(L, -1)); lua_pop(L, 1); } return result; @@ -353,11 +608,11 @@ namespace bLua { const int top = lua_gettop(L); ensure_stack(L, 4); try { - lua_createtable(L, static_cast(v.size()), 0); + lua_createtable(L, table_hint(v.size()), 0); for (size_t k = 0; k < v.size(); ++k) { if constexpr (std::is_same_v) native_to_lua(L, static_cast(v[k])); else native_to_lua(L, v[k]); - lua_rawseti(L, -2, static_cast(k + 1)); + rawseti_idx(L, -2, static_cast(k + 1)); } } catch (...) { lua_settop(L, top); throw; } } @@ -371,8 +626,10 @@ namespace bLua { while (lua_next(L, i)) { // Preserve lua_next's original key even if a converter manipulates its slot. lua_pushvalue(L, -2); - K key = lua_to_native(L, -1); lua_pop(L, 1); - V value = lua_to_native(L, -1); + K key; V value; + { conv_scope scope("map key", 0); key = lua_to_native(L, -1); } + lua_pop(L, 1); + { conv_scope scope("map value", 0); value = lua_to_native(L, -1); } if (!result.emplace(std::move(key), std::move(value)).second) fail("duplicate converted map key"); lua_pop(L, 1); } @@ -382,7 +639,7 @@ namespace bLua { const int top = lua_gettop(L); ensure_stack(L, 4); try { - lua_createtable(L, 0, static_cast(m.size())); + lua_createtable(L, 0, table_hint(m.size())); for (const auto &kv : m) { native_to_lua(L, kv.first); if (lua_isnil(L, -1)) fail("nil map key"); @@ -405,7 +662,21 @@ namespace bLua { template struct function_traits : function_traits {}; template Tuple read_args([[maybe_unused]] lua_State *L, [[maybe_unused]] int offset, std::index_sequence) { - return Tuple{lua_to_native>(L, offset + static_cast(I))...}; + return Tuple{[&] { + conv_scope scope("argument", offset + static_cast(I)); + return lua_to_native>(L, offset + static_cast(I)); + }()...}; + } + template int push_result(lua_State *L, Tuple &&value) { + if constexpr (is_tuple_like>::value) { + return std::apply([&](auto &&...xs) { + (native_to_lua(L, std::forward(xs)), ...); + return static_cast(sizeof...(xs)); + }, std::forward(value)); + } else { + native_to_lua(L, std::forward(value)); + return 1; + } } template int call_function(lua_State *L) { using traits = function_traits; using args_type = typename traits::args; @@ -416,7 +687,7 @@ namespace bLua { else return func(a...); }; if constexpr (std::is_void_v) { std::apply(invoke, args); return 0; } - else { native_to_lua(L, std::apply(invoke, args)); return 1; } + else { return push_result(L, std::apply(invoke, args)); } } template void push_function(lua_State *L, F func) { if (func == nullptr) fail("null native function"); @@ -425,11 +696,75 @@ namespace bLua { lua_pushcclosure(L, boundary>, 1); } template int construct(lua_State *L) { + int offset = 1; + rawgetp(L, LUA_REGISTRYINDEX, &class_table_key); + if (lua_istable(L, -1) && lua_rawequal(L, 1, -1)) offset = 2; + lua_pop(L, 1); using tuple = std::tuple...>; - auto args = read_args(L, 1, std::index_sequence_for{}); + auto args = read_args(L, offset, std::index_sequence_for{}); auto obj = std::apply([](auto &...a) { return std::make_unique(a...); }, args); push_ptr(L, obj.get(), ownership::owning); obj.release(); return 1; } + // parents table layout: { base_mt, base_getters, base_setters, ... } most-derived first. + inline int class_index(lua_State *L) { + auto lookup = [&](int table, bool call_getter) -> bool { + lua_pushvalue(L, 2); + lua_rawget(L, table); + if (call_getter) { + if (!lua_isfunction(L, -1)) { lua_pop(L, 1); return false; } + lua_pushvalue(L, 1); + lua_call(L, 1, 1); + return true; + } + if (!lua_isnil(L, -1)) return true; + lua_pop(L, 1); + return false; + }; + if (lookup(lua_upvalueindex(1), false)) return 1; + if (lookup(lua_upvalueindex(2), true)) return 1; + rawgetp(L, lua_upvalueindex(1), &parents_key); + if (lua_istable(L, -1)) { + const size_t n = rawlen(L, -1); + for (size_t i = 1; i + 2 <= n; i += 3) { + rawgeti_idx(L, -1, static_cast(i)); + const bool have = lookup(lua_gettop(L), false); + lua_remove(L, have ? -2 : -1); + if (have) { lua_remove(L, -2); return 1; } + rawgeti_idx(L, -1, static_cast(i + 1)); + const bool got = lookup(lua_gettop(L), true); + lua_remove(L, got ? -2 : -1); + if (got) { lua_remove(L, -2); return 1; } + } + } + lua_pop(L, 1); + lua_pushnil(L); + return 1; + } + inline int class_newindex(lua_State *L) { + auto lookup = [&](int table) -> bool { + lua_pushvalue(L, 2); + lua_rawget(L, table); + if (!lua_isfunction(L, -1)) { lua_pop(L, 1); return false; } + lua_pushvalue(L, 1); + lua_pushvalue(L, 3); + lua_call(L, 2, 0); + return true; + }; + if (lookup(lua_upvalueindex(1))) return 0; + rawgetp(L, lua_upvalueindex(2), &parents_key); + if (lua_istable(L, -1)) { + const size_t n = rawlen(L, -1); + for (size_t i = 3; i <= n; i += 3) { + rawgeti_idx(L, -1, static_cast(i)); + const bool got = lookup(lua_gettop(L)); + lua_pop(L, 1); + if (got) { lua_pop(L, 1); return 0; } + } + } + lua_pop(L, 1); + const char *key = lua_type(L, 2) == LUA_TSTRING ? lua_tostring(L, 2) : "?"; + fail(std::string("no writable property '") + (key ? key : "?") + "'"); + } template int get_property(lua_State *L) { auto member = *static_cast(lua_touserdata(L, lua_upvalueindex(1))); native_to_lua(L, check_t(L, 1)->*member); return 1; @@ -442,7 +777,7 @@ namespace bLua { inline int dispatch(lua_State *L) { const int n = lua_gettop(L); lua_rawgeti(L, lua_upvalueindex(1), n); - if (!lua_isfunction(L, -1)) fail("no overload matches argument count"); + if (!lua_isfunction(L, -1)) fail(std::string("no overload matches argument count ") + std::to_string(n)); lua_insert(L, 1); lua_call(L, n, LUA_MULTRET); return lua_gettop(L); } inline void push_traceback(lua_State *L) { @@ -458,7 +793,11 @@ namespace bLua { }; template auto read_results([[maybe_unused]] lua_State *L, std::index_sequence) { return std::tuple>...>{ - lua_to_native>>(L, -static_cast(sizeof...(I)) + static_cast(I))...}; + [&] { + conv_scope scope("return", static_cast(I) + 1); + return lua_to_native>>( + L, -static_cast(sizeof...(I)) + static_cast(I)); + }()...}; } template int perform_call(lua_State *L) { auto &ctx = *static_cast *>(lua_touserdata(L, 1)); @@ -468,13 +807,27 @@ namespace bLua { globals(L); if (ctx.tables) { if (ctx.tables->empty()) fail("no tables"); + std::string path; for (const auto &name : *ctx.tables) { rawfield(L, -1, name.c_str()); lua_remove(L, -2); - if (!lua_istable(L, -1)) fail("no table in path"); + if (!path.empty()) path += '.'; + path += name; + if (!lua_istable(L, -1)) fail("no table '" + name + "' in path '" + path + "'"); } } rawfield(L, -1, ctx.name); lua_remove(L, -2); - if (!lua_isfunction(L, -1)) fail("no function"); + if (!lua_isfunction(L, -1)) { + std::string who = ctx.name ? ctx.name : ""; + if (ctx.tables && !ctx.tables->empty()) { + std::string path; + for (const auto &t : *ctx.tables) { + if (!path.empty()) path += '.'; + path += t; + } + fail("no function '" + path + "." + who + "'"); + } + fail("no function '" + who + "'"); + } std::apply([&](const auto &...a) { (native_to_lua(L, a), ...); }, ctx.args); // Only trivial locals cross Lua's error longjmp. Argument / result validation // uses C++ exceptions, not luaL_check*; user function errors stay in lua_pcall. @@ -517,8 +870,18 @@ namespace bLua { lua_pop(L, 1); lua_newtable(L); lua_pushcfunction(L, (internal::boundary>)); lua_setfield(L, -2, "__gc"); - lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); lua_pushlstring(L, wanted.data(), wanted.size()); lua_setfield(L, -2, "__name"); + lua_newtable(L); internal::rawsetp(L, LUA_REGISTRYINDEX, &internal::getters_key); + lua_newtable(L); internal::rawsetp(L, LUA_REGISTRYINDEX, &internal::setters_key); + lua_newtable(L); internal::rawsetp(L, -2, &internal::parents_key); + lua_pushvalue(L, -1); + internal::rawgetp(L, LUA_REGISTRYINDEX, &internal::getters_key); + lua_pushcclosure(L, internal::boundary, 2); + lua_setfield(L, -2, "__index"); + internal::rawgetp(L, LUA_REGISTRYINDEX, &internal::setters_key); + lua_pushvalue(L, -2); + lua_pushcclosure(L, internal::boundary, 2); + lua_setfield(L, -2, "__newindex"); lua_pushvalue(L, -1); internal::rawsetp(L, LUA_REGISTRYINDEX, &internal::table_key); lua_pushstring(L, wanted.c_str()); lua_pushvalue(L, -2); lua_rawset(L, LUA_REGISTRYINDEX); meta.name = std::move(wanted); meta.own = own; meta.deleter = del; meta.registered = true; @@ -537,8 +900,71 @@ namespace bLua { meta.name = name; } template const char *get_type_name(lua_State *L) { return internal::state(L).name.c_str(); } + template void reg_base(lua_State *L) { + static_assert(std::is_base_of_v && !std::is_same_v, + "reg_base requires a unique public base"); + if (!internal::state(L).registered || !internal::state(L).registered) + internal::fail("register both classes before reg_base"); + auto to_base = +[](void *p) -> void * { + return static_cast(static_cast(p)); + }; + auto &base = internal::state(L); + for (const auto &u : base.upcasts) { + if (u.derived_table == &internal::table_key) return; + } + base.upcasts.push_back({&internal::table_key, &internal::type_key, to_base}); + internal::state(L).bases.push_back({to_base}); + internal::stack_guard guard(L); + internal::push_metatable(L); + internal::rawgetp(L, -1, &internal::parents_key); + if (!lua_istable(L, -1)) { + lua_pop(L, 1); + lua_newtable(L); + lua_pushvalue(L, -1); + internal::rawsetp(L, -3, &internal::parents_key); + } + auto already = [&]() { + const size_t n = internal::rawlen(L, -1); + for (size_t i = 1; i <= n; i += 3) { + internal::rawgeti_idx(L, -1, static_cast(i)); + internal::rawgetp(L, LUA_REGISTRYINDEX, &internal::table_key); + const bool match = lua_rawequal(L, -1, -2); + lua_pop(L, 2); + if (match) return true; + } + return false; + }; + if (!already()) { + auto append = [&]() { + const int parents = lua_gettop(L); + auto push_entry = [&](auto /*tag*/, auto table, auto getters, auto setters) { + (void)table; + internal::rawgetp(L, LUA_REGISTRYINDEX, table); + lua_rawseti(L, parents, static_cast(internal::rawlen(L, parents) + 1)); + internal::rawgetp(L, LUA_REGISTRYINDEX, getters); + lua_rawseti(L, parents, static_cast(internal::rawlen(L, parents) + 1)); + internal::rawgetp(L, LUA_REGISTRYINDEX, setters); + lua_rawseti(L, parents, static_cast(internal::rawlen(L, parents) + 1)); + }; + push_entry(0, &internal::table_key, &internal::getters_key, &internal::setters_key); + internal::rawgetp(L, LUA_REGISTRYINDEX, &internal::table_key); + internal::rawgetp(L, -1, &internal::parents_key); + if (lua_istable(L, -1)) { + const size_t n = internal::rawlen(L, -1); + for (size_t i = 1; i <= n; ++i) { + internal::rawgeti_idx(L, -1, static_cast(i)); + lua_rawseti(L, parents, static_cast(internal::rawlen(L, parents) + 1)); + } + } + lua_pop(L, 2); + }; + append(); + } + } template void push(lua_State *L, const T &v) { internal::native_to_lua(L, v); } template void push(lua_State *L, T *v, ownership own) { internal::push_ptr(L, v, own); } + template void push(lua_State *L, std::unique_ptr v) { internal::push_unique(L, std::move(v)); } + template void push(lua_State *L, const std::shared_ptr &v) { internal::push_shared(L, v); } template void push_vector(lua_State *L, const std::vector &v) { push(L, v); } template std::vector to_vector(lua_State *L, int i) { return internal::lua_to_native>(L, i); } template void push_map(lua_State *L, const std::map &m) { push(L, m); } @@ -565,28 +991,99 @@ namespace bLua { internal::stack_guard guard(L); internal::push_metatable(L); internal::push_function(L, func); lua_setfield(L, -2, name); } - template void reg_constructor(lua_State *L, const char *name) { + template void reg_class_overload(lua_State *L, const char *name, F f, Fs...fs) { + using T = typename internal::function_traits::object; + internal::stack_guard guard(L); internal::push_metatable(L); + lua_newtable(L); + auto add = [&](auto func) { + using U = typename internal::function_traits::object; + static_assert(std::is_same_v, "overload methods must belong to the same class"); + using args = typename internal::function_traits::args; + constexpr int n = static_cast(std::tuple_size_v + 1); + lua_rawgeti(L, -1, n); + const bool duplicate = !lua_isnil(L, -1); lua_pop(L, 1); + if (duplicate) internal::fail("duplicate overload arity"); + internal::push_function(L, func); lua_rawseti(L, -2, n); + }; + add(f); (add(fs), ...); + lua_pushcclosure(L, internal::boundary, 1); lua_setfield(L, -2, name); + } + template void ensure_class_table(lua_State *L, const char *global_name) { + internal::rawgetp(L, LUA_REGISTRYINDEX, &internal::class_table_key); + if (lua_istable(L, -1)) return; + lua_pop(L, 1); + lua_newtable(L); + lua_newtable(L); + lua_newtable(L); + lua_pushcclosure(L, internal::boundary, 1); + lua_setfield(L, -2, "__call"); + lua_setmetatable(L, -2); + lua_pushvalue(L, -1); + internal::rawsetp(L, LUA_REGISTRYINDEX, &internal::class_table_key); + if (global_name && *global_name) { + lua_pushvalue(L, -1); + lua_setglobal(L, global_name); + } + } + template void reg_constructor(lua_State *L, const char *name = nullptr) { if (!internal::state(L).registered) internal::fail("register class before constructor"); - lua_pushcfunction(L, (internal::boundary>)); lua_setglobal(L, name); + internal::stack_guard guard(L); + if (name && *name) { + lua_pushcfunction(L, (internal::boundary>)); + lua_setglobal(L, name); + } + ensure_class_table(L, internal::state(L).name.c_str()); + if (!lua_getmetatable(L, -1)) internal::fail("missing class table metatable"); + lua_getfield(L, -1, "__call"); + if (!lua_isfunction(L, -1)) internal::fail("missing class table __call"); + lua_getupvalue(L, -1, 1); + constexpr int n = static_cast(sizeof...(A) + 1); + lua_rawgeti(L, -1, n); + const bool occupied = lua_isfunction(L, -1); lua_pop(L, 1); + if (!occupied) { + lua_pushcfunction(L, (internal::boundary>)); + lua_rawseti(L, -2, n); + } } template void reg_property(lua_State *L, const char *name, M T::*member) { internal::stack_guard guard(L); internal::push_metatable(L); using member_type = M T::*; - auto add = [&](const char *prefix, lua_CFunction fn) { - std::string method = std::string(prefix) + name; + auto make = [&](lua_CFunction fn) { auto mem = static_cast(lua_newuserdata(L, sizeof(member_type))); new (mem) member_type(member); - lua_pushcclosure(L, fn, 1); lua_setfield(L, -2, method.c_str()); + lua_pushcclosure(L, fn, 1); + }; + auto add_method = [&](const char *prefix, lua_CFunction fn) { + std::string method = std::string(prefix) + name; + make(fn); lua_setfield(L, -2, method.c_str()); }; - add("get_", internal::boundary>); - if constexpr (!std::is_const_v) add("set_", internal::boundary>); + add_method("get_", internal::boundary>); + make(internal::boundary>); + internal::rawgetp(L, LUA_REGISTRYINDEX, &internal::getters_key); + lua_pushvalue(L, -2); lua_setfield(L, -2, name); lua_pop(L, 2); + if constexpr (!std::is_const_v) { + add_method("set_", internal::boundary>); + make(internal::boundary>); + internal::rawgetp(L, LUA_REGISTRYINDEX, &internal::setters_key); + lua_pushvalue(L, -2); lua_setfield(L, -2, name); lua_pop(L, 2); + } } template void reg_property(lua_State *L, const char *name, R(T::*getter)() const) { const std::string method = std::string("get_") + name; reg_class_func(L, method.c_str(), getter); + internal::stack_guard guard(L); + internal::push_function(L, getter); + internal::rawgetp(L, LUA_REGISTRYINDEX, &internal::getters_key); + if (!lua_istable(L, -1)) internal::fail("class is not registered"); + lua_pushvalue(L, -2); lua_setfield(L, -2, name); } template void reg_property(lua_State *L, const char *name, R(T::*getter)() const, void(T::*setter)(A)) { reg_property(L, name, getter); const std::string method = std::string("set_") + name; reg_class_func(L, method.c_str(), setter); + internal::stack_guard guard(L); + internal::push_function(L, setter); + internal::rawgetp(L, LUA_REGISTRYINDEX, &internal::setters_key); + if (!lua_istable(L, -1)) internal::fail("class is not registered"); + lua_pushvalue(L, -2); lua_setfield(L, -2, name); } template void reg_enum(lua_State *L, const char *name, std::initializer_list> values) { static_assert(std::is_enum_v || std::is_integral_v, "enum or integer required"); diff --git a/test/regression.cpp b/test/regression.cpp index 82b51c2..ffba458 100644 --- a/test/regression.cpp +++ b/test/regression.cpp @@ -234,9 +234,187 @@ void test_containers_overloads() { CHECK(lua_gettop(L)==0); } } + +struct Base { + int b = 1; + virtual ~Base() = default; + int get_b() const { return b; } +}; +struct Derived : Base { + int d = 2; + int get_d() const { return d; } +}; +struct ValueObj { + int x = 0; + int get() const { return x; } +}; +int take_derived(Derived *d) { return d->d; } +struct Methods { + int v = 0; + Methods() = default; + explicit Methods(int x) : v(x) {} + int add() const { return v; } + int add(int x) const { return v + x; } + std::tuple pair() const { return {v, "ok"}; } +}; +int need_int(int x) { return x + 1; } +int read_const(const Obj *p) { return p ? p->value : -1; } +const Obj *as_const(Obj *p) { return p; } +int use_shared(std::shared_ptr p) { return p ? p->value : -1; } +std::shared_ptr ident_shared(std::shared_ptr p) { return p; } +int takes_obj(Obj *p) { return p->value; } +std::tuple make_pair() { return {4, "hi"}; } +void test_dx() { + Lua s; auto L = s.L; + const int before = Obj::destroyed; + bLua::reg_class(L, "Obj"); + bLua::reg_class(L, "Other"); + bLua::reg_class_func(L, "get", &Obj::get); + bLua::reg_class_func(L, "set", &Obj::set); + bLua::reg_property(L, "value", &Obj::value); + bLua::reg_global_func(L, "need_int", need_int); + bLua::reg_global_func(L, "read_const", read_const); + bLua::reg_global_func(L, "as_const", as_const); + bLua::reg_global_func(L, "use_shared", use_shared); + bLua::reg_global_func(L, "ident_shared", ident_shared); + bLua::reg_global_func(L, "takes_obj", takes_obj); + bLua::reg_global_func(L, "make_pair", make_pair); + + script(L, R"( + function good() return 12, 'hello' end + function wrong() return 12, {} end + path={inner={good=good}} + )"); + int number = 0; std::string text; + auto err = bLua::call_lua_global_func(L, "missing_fn", std::tie(number)); + CHECK(err && err->find("no function 'missing_fn'") != std::string::npos); + err = bLua::call_lua_table_func(L, {"missing_tbl"}, "good", std::tie(number)); + CHECK(err && err->find("no table 'missing_tbl'") != std::string::npos); + err = bLua::call_lua_table_func(L, {"path", "inner"}, "nope", std::tie(number)); + CHECK(err && err->find("no function 'path.inner.nope'") != std::string::npos); + number = -1; text = "old"; + err = bLua::call_lua_global_func(L, "wrong", std::tie(number, text)); + CHECK(err && err->find("return 2") != std::string::npos); + CHECK(number == -1 && text == "old"); + script(L, R"( + local ok, err = pcall(function() need_int('x') end) + assert(not ok and err:find('argument 1') and err:find('number expected')) + )"); + auto p = new Obj; + p->value = 8; + bLua::push(L, p); + lua_setglobal(L, "o"); + script(L, R"( + local ok, err = pcall(function() o:set('x') end) + assert(not ok and err:find('argument 2') and err:find('number expected')) + assert(read_const(o) == 8) + assert(as_const(o) == o) + assert(o.value == 8) + o.value = 9 + assert(o:get() == 9 and o:get_value() == 9) + )"); + + { + auto unique = std::make_unique(); + unique->value = 21; + bLua::push(L, std::move(unique)); + CHECK(!unique); + lua_setglobal(L, "owned"); + script(L, "assert(takes_obj(owned)==21); owned=nil; collectgarbage('collect'); collectgarbage('collect')"); + CHECK(Obj::destroyed == before + 1); + } + { + auto shared = std::make_shared(); + shared->value = 22; + std::weak_ptr weak = shared; + bLua::push(L, shared); + shared.reset(); + CHECK(!weak.expired()); + lua_setglobal(L, "shared"); + script(L, "assert(use_shared(shared)==22); shared=ident_shared(shared); shared=nil; collectgarbage('collect'); collectgarbage('collect')"); + CHECK(weak.expired()); + CHECK(Obj::destroyed == before + 2); + } + { + ValueObj src{15}; + bLua::reg_class(L, "ValueObj"); + bLua::reg_class_func(L, "get", &ValueObj::get); + bLua::push(L, src); // copy, Lua-owned + lua_setglobal(L, "vo"); + src.x = 99; + script(L, "assert(vo:get()==15); vo=nil; collectgarbage('collect'); collectgarbage('collect')"); + } + + bLua::reg_class(L, "Base"); + bLua::reg_class(L, "Derived"); + bLua::reg_base(L); + bLua::reg_base(L); // idempotent + bLua::reg_class_func(L, "get_b", &Base::get_b); + bLua::reg_class_func(L, "get_d", &Derived::get_d); + auto *derived = new Derived; + derived->b = 10; derived->d = 20; + bLua::push(L, derived); + lua_setglobal(L, "derived"); + script(L, "assert(derived:get_d()==20 and derived:get_b()==10)"); + bLua::push(L, static_cast(derived)); + lua_getglobal(L, "derived"); + CHECK(lua_rawequal(L, -1, -2)); + lua_pop(L, 2); + rejected(L, [&] { bLua::push(L, reinterpret_cast(derived)); }, "different type"); + auto *base_only = new Base; + bLua::push(L, base_only); + lua_setglobal(L, "base"); + bLua::reg_global_func(L, "take_derived", take_derived); + script(L, "assert(base:get_b()==1); assert(not pcall(function() return base:get_d() end))"); + script(L, "assert(take_derived(derived)==20)"); + script(L, "assert(not pcall(function() return take_derived(base) end))"); + + bLua::reg_class(L, "Methods"); + bLua::reg_constructor(L); + bLua::reg_constructor(L); + bLua::reg_class_overload(L, "add", + static_cast(&Methods::add), + static_cast(&Methods::add)); + bLua::reg_class_func(L, "pair", &Methods::pair); + bLua::reg_property(L, "v", &Methods::v); + script(L, R"( + local c = Methods() + assert(c.v == 0) + c.v = 4 + assert(c.v == 4 and c:get_v() == 4) + local c2 = Methods(3) + assert(c2:add() == 3 and c2:add(5) == 8) + local x, y = c2:pair() + assert(x == 3 and y == 'ok') + local a, b = make_pair() + assert(a == 4 and b == 'hi') + local ok, err = pcall(function() c2.missing = 1 end) + assert(not ok and err:find('no writable property')) + ok, err = pcall(function() c2:add(1,2) end) + assert(not ok and err:find('no overload matches argument count')) + )"); + + if (sizeof(lua_Integer) > sizeof(int)) { + lua_newtable(L); + const lua_Integer big = static_cast(std::numeric_limits::max()) + 1; + lua_pushinteger(L, 99); + bLua::internal::rawseti_idx(L, -2, big); + bLua::internal::rawgeti_idx(L, -1, big); + CHECK(lua_tointeger(L, -1) == 99); + lua_pop(L, 2); + std::map wide{{big, 42}, {1, 7}}; + bLua::push_map(L, wide); + auto back = bLua::to_map(L, -1); + CHECK(back.at(big) == 42 && back.at(1) == 7); + lua_pop(L, 1); + } + script(L, "derived=nil; base=nil; o=nil; collectgarbage('collect'); collectgarbage('collect')"); +} + int main() { try { - test_states(false); test_states(true); test_ownership(); test_errors(); test_containers_overloads(); + test_states(false); test_states(true); test_ownership(); test_errors(); test_containers_overloads(); test_dx(); std::puts("All lifetime/error/container regressions passed"); return 0; } catch (const std::exception &e) { std::fprintf(stderr,"%s\n",e.what()); return 1; } } + diff --git a/test/test.cpp b/test/test.cpp index d2b825c..a86f17b 100644 --- a/test/test.cpp +++ b/test/test.cpp @@ -204,6 +204,14 @@ static void test_constructor_property_enum_overload(lua_State *L) { "local a = A_new()\n" "a:set_a(10)\n" "assert(a:get_a() == 10)\n" + "assert(a.a == 10)\n" + "a.a = 11\n" + "assert(a.a == 11 and a:get_a() == 11)\n" + "local via_call = A()\n" + "via_call.a = 1\n" + "assert(via_call:get_a() == 1)\n" + "local via_call1 = A(5)\n" + "assert(via_call1:get_int() == 5)\n" "a:set_b('prop')\n" "assert(a:get_b() == 'prop')\n" "local a1 = A_new1(5)\n" From 2651ff1254b4194cdf72f097744dfc8ad4ac1050 Mon Sep 17 00:00:00 2001 From: esrrhs Date: Tue, 1 Dec 2026 21:54:51 +0800 Subject: [PATCH 2/5] fix: store conversion context in the Lua registry thread_local state around the C++ exception to luaL_error boundary caused LuaJIT (shared library) to report "unknown C++ exception" from call_lua_* instead of the native what(). Keep prefixes state-local and avoid TLS. --- CHANGELOG.md | 5 ++ bLua.h | 170 +++++++++++++++++++++++++++++---------------------- 2 files changed, 101 insertions(+), 74 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e2e6101..598c9d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,11 @@ change and still need explicit approval. - 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". + ### 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. diff --git a/bLua.h b/bLua.h index c2f5493..890eab4 100644 --- a/bLua.h +++ b/bLua.h @@ -135,22 +135,44 @@ namespace bLua { stack_guard(const stack_guard &) = delete; stack_guard &operator=(const stack_guard &) = delete; }; + // Conversion context lives in the Lua registry, not thread_local: LuaJIT's + // shared-library foreign DWARF unwinder mis-handles TLS access around the + // C++ exception -> luaL_error boundary (errors become "unknown C++ exception"). + inline char conv_key; + struct conv_scope; + inline conv_scope *load_scope(lua_State *L) { + if (!L) return nullptr; + const int top = lua_gettop(L); + lua_pushlightuserdata(L, &conv_key); + lua_rawget(L, LUA_REGISTRYINDEX); + auto *p = lua_type(L, -1) == LUA_TLIGHTUSERDATA + ? static_cast(lua_touserdata(L, -1)) : nullptr; + lua_settop(L, top); + return p; + } + inline void store_scope(lua_State *L, conv_scope *s) { + if (!L) return; + lua_pushlightuserdata(L, &conv_key); + if (s) lua_pushlightuserdata(L, s); + else lua_pushnil(L); + lua_rawset(L, LUA_REGISTRYINDEX); + } struct conv_scope { + lua_State *L; const char *kind; int index; conv_scope *prev; - static conv_scope *&head() { - static thread_local conv_scope *h = nullptr; - return h; + conv_scope(lua_State *state, const char *k, int i) + : L(state), kind(k), index(i), prev(load_scope(state)) { + store_scope(L, this); } - conv_scope(const char *k, int i) : kind(k), index(i), prev(head()) { head() = this; } - ~conv_scope() { head() = prev; } + ~conv_scope() { store_scope(L, prev); } conv_scope(const conv_scope &) = delete; conv_scope &operator=(const conv_scope &) = delete; }; - inline std::string conv_prefix() { + inline std::string conv_prefix(lua_State *L) { std::vector stack; - for (auto *c = conv_scope::head(); c; c = c->prev) stack.push_back(c); + for (auto *c = load_scope(L); c; c = c->prev) stack.push_back(c); std::string pre; for (auto it = stack.rbegin(); it != stack.rend(); ++it) { if (!pre.empty()) pre += ": "; @@ -162,11 +184,11 @@ namespace bLua { } return pre; } - [[noreturn]] inline void fail(const std::string &s) { - auto pre = conv_prefix(); + [[noreturn]] inline void fail(lua_State *L, const std::string &s) { + auto pre = conv_prefix(L); throw std::runtime_error(pre.empty() ? s : pre + ": " + s); } - [[noreturn]] inline void fail(const char *s) { fail(std::string(s ? s : "")); } + [[noreturn]] inline void fail(lua_State *L, const char *s) { fail(L, std::string(s ? s : "")); } // Never luaL_error while an exception / argument tuple is alive. All validation // below throws C++; only this outermost callback converts it to a Lua error. @@ -250,7 +272,7 @@ namespace bLua { } template void push_metatable(lua_State *L) { rawgetp(L, LUA_REGISTRYINDEX, &table_key); - if (!lua_istable(L, -1)) { lua_pop(L, 1); fail("class is not registered"); } + if (!lua_istable(L, -1)) { lua_pop(L, 1); fail(L, "class is not registered"); } } struct userdata_base { const void *type; @@ -299,7 +321,7 @@ namespace bLua { lua_pop(L, 1); auto ud = static_cast(lua_touserdata(L, i)); if (!ud || ud->type != u.derived_type) return nullptr; - if (!ud->alive || !ud->ptr) fail("object has been destroyed"); + if (!ud->alive || !ud->ptr) fail(L, "object has been destroyed"); return static_cast(u.cast(ud->ptr)); } lua_pop(L, 1); @@ -307,13 +329,13 @@ namespace bLua { } template T *check_t(lua_State *L, int i) { if (auto ud = test_object(L, i)) { - if (!ud->base.alive || !ud->base.ptr) fail("object has been destroyed"); + if (!ud->base.alive || !ud->base.ptr) fail(L, "object has been destroyed"); return static_cast(ud->base.ptr); } if (auto *p = try_upcast_ptr(L, i)) return p; auto &meta = state(L); - if (!meta.registered) fail("wrong userdata type (or class is not registered)"); - fail(std::string("expected ") + meta.name + " (or derived)"); + if (!meta.registered) fail(L, "wrong userdata type (or class is not registered)"); + fail(L, std::string("expected ") + meta.name + " (or derived)"); } template int free_class(lua_State *L) { auto ud = test_object(L, 1); @@ -339,7 +361,7 @@ namespace bLua { if (auto ud = test_object(L, -1)) { if (ud->base.alive) { if (!reuse_policy && (ud->base.owning != (own == ownership::owning) || ud->deleter != del)) - fail("pointer ownership/deleter conflict"); + fail(L, "pointer ownership/deleter conflict"); lua_remove(L, -2); return true; } @@ -347,26 +369,26 @@ namespace bLua { } if (try_upcast_ptr(L, -1) == p) { auto hdr = static_cast(lua_touserdata(L, -1)); - if (!hdr || !hdr->alive) fail("object has been destroyed"); + if (!hdr || !hdr->alive) fail(L, "object has been destroyed"); const bool cached_owning = hdr->owning; if (!reuse_policy && cached_owning != (own == ownership::owning)) - fail("pointer ownership/deleter conflict"); + fail(L, "pointer ownership/deleter conflict"); lua_remove(L, -2); return true; } - if (!lua_isnil(L, -1)) fail("pointer is already exposed with a different type"); + if (!lua_isnil(L, -1)) fail(L, "pointer is already exposed with a different type"); return false; } template void push_ptr(lua_State *L, T *p, ownership own, bool reuse_policy = false) { using U = std::remove_const_t; if constexpr (std::is_const_v) { - if (own == ownership::owning) fail("const pointers cannot be Lua-owned"); + if (own == ownership::owning) fail(L, "const pointers cannot be Lua-owned"); push_ptr(L, const_cast(p), ownership::non_owning, reuse_policy); return; } else { if (!p) { lua_pushnil(L); return; } auto &meta = state(L); - if (!meta.registered) fail("register class before pushing its objects"); + if (!meta.registered) fail(L, "register class before pushing its objects"); auto del = own == ownership::owning ? meta.deleter : nullptr; const int top = lua_gettop(L); ensure_stack(L, 8); @@ -396,7 +418,7 @@ namespace bLua { if (!holder) { lua_pushnil(L); return; } T *p = holder.get(); auto &meta = state(L); - if (!meta.registered) fail("register class before pushing its objects"); + if (!meta.registered) fail(L, "register class before pushing its objects"); const int top = lua_gettop(L); ensure_stack(L, 8); try { @@ -411,14 +433,14 @@ namespace bLua { } rawgetp(L, -1, p); if (auto ud = test_object(L, -1)) { - if (!ud->base.alive) fail("object has been destroyed"); + if (!ud->base.alive) fail(L, "object has been destroyed"); if (ud->base.extra_kind != hold::shared || !ud->base.extra) - fail("pointer ownership/deleter conflict"); + fail(L, "pointer ownership/deleter conflict"); *static_cast *>(ud->base.extra) = holder; lua_remove(L, -2); return; } - if (!lua_isnil(L, -1)) fail("pointer is already exposed with a different type"); + if (!lua_isnil(L, -1)) fail(L, "pointer is already exposed with a different type"); lua_pop(L, 1); auto ud = static_cast *>(lua_newuserdata(L, sizeof(userdata))); new (ud) userdata{{&type_key, p, true, true, hold::shared, @@ -447,14 +469,14 @@ namespace bLua { template struct converter && !std::is_same_v>> { static T get(lua_State *L, int i) { - if (lua_type(L, i) != LUA_TNUMBER) fail("number expected"); + if (lua_type(L, i) != LUA_TNUMBER) fail(L, "number expected"); #if LUA_VERSION_NUM >= 503 if (lua_isinteger(L, i)) { const lua_Integer n = lua_tointeger(L, i); if constexpr (std::is_unsigned_v) { - if (n < 0 || static_cast(n) > std::numeric_limits::max()) fail("integer out of range"); + if (n < 0 || static_cast(n) > std::numeric_limits::max()) fail(L, "integer out of range"); } else { - if (n < std::numeric_limits::lowest() || n > std::numeric_limits::max()) fail("integer out of range"); + if (n < std::numeric_limits::lowest() || n > std::numeric_limits::max()) fail(L, "integer out of range"); } return static_cast(n); } @@ -464,38 +486,38 @@ namespace bLua { const long double value = static_cast(n); const long double limit = std::ldexp(1.0L, std::numeric_limits::digits); const long double lower = std::is_signed_v ? -limit : 0.0L; - if (!(value >= lower && value < limit)) fail("integer out of range"); - if (std::trunc(n) != n) fail("integer expected"); + if (!(value >= lower && value < limit)) fail(L, "integer out of range"); + if (std::trunc(n) != n) fail(L, "integer expected"); return static_cast(n); } static void push(lua_State *L, T v) { if constexpr (std::is_unsigned_v) { if (v > static_cast>(std::numeric_limits::max())) - fail("integer does not fit lua_Integer"); + fail(L, "integer does not fit lua_Integer"); } else if constexpr (sizeof(T) > sizeof(lua_Integer)) { if (v < std::numeric_limits::lowest() || v > std::numeric_limits::max()) - fail("integer does not fit lua_Integer"); + fail(L, "integer does not fit lua_Integer"); } lua_pushinteger(L, static_cast(v)); } }; template struct converter>> { static T get(lua_State *L, int i) { - if (lua_type(L, i) != LUA_TNUMBER) fail("number expected"); + if (lua_type(L, i) != LUA_TNUMBER) fail(L, "number expected"); return static_cast(lua_tonumber(L, i)); } static void push(lua_State *L, T v) { lua_pushnumber(L, static_cast(v)); } }; template<> struct converter { static bool get(lua_State *L, int i) { - if (lua_type(L, i) != LUA_TBOOLEAN) fail("boolean expected"); + if (lua_type(L, i) != LUA_TBOOLEAN) fail(L, "boolean expected"); return lua_toboolean(L, i) != 0; } static void push(lua_State *L, bool v) { lua_pushboolean(L, v); } }; template<> struct converter { static std::string get(lua_State *L, int i) { - if (lua_type(L, i) != LUA_TSTRING) fail("string expected"); + if (lua_type(L, i) != LUA_TSTRING) fail(L, "string expected"); size_t n = 0; const char *s = lua_tolstring(L, i, &n); return std::string(s, n); } @@ -503,7 +525,7 @@ namespace bLua { }; template<> struct converter { static std::string_view get(lua_State *L, int i) { - if (lua_type(L, i) != LUA_TSTRING) fail("string expected"); + if (lua_type(L, i) != LUA_TSTRING) fail(L, "string expected"); size_t n = 0; const char *s = lua_tolstring(L, i, &n); return std::string_view(s, n); } @@ -512,7 +534,7 @@ namespace bLua { template<> struct converter { static const char *get(lua_State *L, int i) { if (lua_isnil(L, i)) return nullptr; - if (lua_type(L, i) != LUA_TSTRING) fail("string or nil expected"); + if (lua_type(L, i) != LUA_TSTRING) fail(L, "string or nil expected"); return lua_tostring(L, i); } static void push(lua_State *L, const char *s) { if (s) lua_pushstring(L, s); else lua_pushnil(L); } @@ -557,12 +579,12 @@ namespace bLua { !is_std_vector::value && !is_std_map::value && !is_tuple_like::value && !is_optional::value; template struct converter> { - static std::unique_ptr get(lua_State *, int) { - fail("unique_ptr can only be moved into Lua, not recovered"); + static std::unique_ptr get(lua_State *L, int) { + fail(L, "unique_ptr can only be moved into Lua, not recovered"); return {}; } - static void push(lua_State *, const std::unique_ptr &) { - fail("unique_ptr must be moved into Lua"); + static void push(lua_State *L, const std::unique_ptr &) { + fail(L, "unique_ptr must be moved into Lua"); } }; template void native_to_lua(lua_State *L, std::unique_ptr &&v) { push_unique(L, std::move(v)); } @@ -570,10 +592,10 @@ namespace bLua { static std::shared_ptr get(lua_State *L, int i) { if (lua_isnil(L, i)) return {}; auto ud = test_object(L, i); - if (!ud) fail(std::string("expected shared_ptr-backed ") + state(L).name); - if (!ud->base.alive || !ud->base.ptr) fail("object has been destroyed"); + if (!ud) fail(L, std::string("expected shared_ptr-backed ") + state(L).name); + if (!ud->base.alive || !ud->base.ptr) fail(L, "object has been destroyed"); if (ud->base.extra_kind != hold::shared || !ud->base.extra) - fail("userdata is not shared_ptr-backed"); + fail(L, "userdata is not shared_ptr-backed"); return *static_cast *>(ud->base.extra); } static void push(lua_State *L, const std::shared_ptr &p) { push_shared(L, p); } @@ -593,11 +615,11 @@ namespace bLua { template struct converter> { static std::vector get(lua_State *L, int i) { stack_guard guard(L); ensure_stack(L, 4); i = absindex(L, i); - if (!lua_istable(L, i)) fail("table expected for vector"); + if (!lua_istable(L, i)) fail(L, "table expected for vector"); std::vector result; const size_t n = rawlen(L, i); result.reserve(n); for (size_t k = 1; k <= n; ++k) { const lua_Integer idx = static_cast(k); - conv_scope scope("element", idx > 0 && idx <= std::numeric_limits::max() + conv_scope scope(L, "element", idx > 0 && idx <= std::numeric_limits::max() ? static_cast(idx) : 0); rawgeti_idx(L, i, idx); result.push_back(lua_to_native(L, -1)); lua_pop(L, 1); @@ -620,17 +642,17 @@ namespace bLua { template struct converter> { static std::map get(lua_State *L, int i) { stack_guard guard(L); ensure_stack(L, 4); i = absindex(L, i); - if (!lua_istable(L, i)) fail("table expected for map"); + if (!lua_istable(L, i)) fail(L, "table expected for map"); std::map result; lua_pushnil(L); while (lua_next(L, i)) { // Preserve lua_next's original key even if a converter manipulates its slot. lua_pushvalue(L, -2); K key; V value; - { conv_scope scope("map key", 0); key = lua_to_native(L, -1); } + { conv_scope scope(L, "map key", 0); key = lua_to_native(L, -1); } lua_pop(L, 1); - { conv_scope scope("map value", 0); value = lua_to_native(L, -1); } - if (!result.emplace(std::move(key), std::move(value)).second) fail("duplicate converted map key"); + { conv_scope scope(L, "map value", 0); value = lua_to_native(L, -1); } + if (!result.emplace(std::move(key), std::move(value)).second) fail(L, "duplicate converted map key"); lua_pop(L, 1); } return result; @@ -642,8 +664,8 @@ namespace bLua { lua_createtable(L, 0, table_hint(m.size())); for (const auto &kv : m) { native_to_lua(L, kv.first); - if (lua_isnil(L, -1)) fail("nil map key"); - if (lua_type(L, -1) == LUA_TNUMBER && std::isnan(lua_tonumber(L, -1))) fail("NaN map key"); + if (lua_isnil(L, -1)) fail(L, "nil map key"); + if (lua_type(L, -1) == LUA_TNUMBER && std::isnan(lua_tonumber(L, -1))) fail(L, "NaN map key"); native_to_lua(L, kv.second); lua_rawset(L, -3); } } catch (...) { lua_settop(L, top); throw; } @@ -663,7 +685,7 @@ namespace bLua { : function_traits {}; template Tuple read_args([[maybe_unused]] lua_State *L, [[maybe_unused]] int offset, std::index_sequence) { return Tuple{[&] { - conv_scope scope("argument", offset + static_cast(I)); + conv_scope scope(L, "argument", offset + static_cast(I)); return lua_to_native>(L, offset + static_cast(I)); }()...}; } @@ -690,7 +712,7 @@ namespace bLua { else { return push_result(L, std::apply(invoke, args)); } } template void push_function(lua_State *L, F func) { - if (func == nullptr) fail("null native function"); + if (func == nullptr) fail(L, "null native function"); ensure_stack(L, 2); auto mem = static_cast(lua_newuserdata(L, sizeof(F))); new (mem) F(func); lua_pushcclosure(L, boundary>, 1); @@ -763,7 +785,7 @@ namespace bLua { } lua_pop(L, 1); const char *key = lua_type(L, 2) == LUA_TSTRING ? lua_tostring(L, 2) : "?"; - fail(std::string("no writable property '") + (key ? key : "?") + "'"); + fail(L, std::string("no writable property '") + (key ? key : "?") + "'"); } template int get_property(lua_State *L) { auto member = *static_cast(lua_touserdata(L, lua_upvalueindex(1))); @@ -777,7 +799,7 @@ namespace bLua { inline int dispatch(lua_State *L) { const int n = lua_gettop(L); lua_rawgeti(L, lua_upvalueindex(1), n); - if (!lua_isfunction(L, -1)) fail(std::string("no overload matches argument count ") + std::to_string(n)); + if (!lua_isfunction(L, -1)) fail(L, std::string("no overload matches argument count ") + std::to_string(n)); lua_insert(L, 1); lua_call(L, n, LUA_MULTRET); return lua_gettop(L); } inline void push_traceback(lua_State *L) { @@ -794,7 +816,7 @@ namespace bLua { template auto read_results([[maybe_unused]] lua_State *L, std::index_sequence) { return std::tuple>...>{ [&] { - conv_scope scope("return", static_cast(I) + 1); + conv_scope scope(L, "return", static_cast(I) + 1); return lua_to_native>>( L, -static_cast(sizeof...(I)) + static_cast(I)); }()...}; @@ -806,13 +828,13 @@ namespace bLua { push_traceback(L); const int handler = lua_isfunction(L, 1) ? 1 : 0; globals(L); if (ctx.tables) { - if (ctx.tables->empty()) fail("no tables"); + if (ctx.tables->empty()) fail(L, "no tables"); std::string path; for (const auto &name : *ctx.tables) { rawfield(L, -1, name.c_str()); lua_remove(L, -2); if (!path.empty()) path += '.'; path += name; - if (!lua_istable(L, -1)) fail("no table '" + name + "' in path '" + path + "'"); + if (!lua_istable(L, -1)) fail(L, "no table '" + name + "' in path '" + path + "'"); } } rawfield(L, -1, ctx.name); lua_remove(L, -2); @@ -824,9 +846,9 @@ namespace bLua { if (!path.empty()) path += '.'; path += t; } - fail("no function '" + path + "." + who + "'"); + fail(L, "no function '" + path + "." + who + "'"); } - fail("no function '" + who + "'"); + fail(L, "no function '" + who + "'"); } std::apply([&](const auto &...a) { (native_to_lua(L, a), ...); }, ctx.args); // Only trivial locals cross Lua's error longjmp. Argument / result validation @@ -858,15 +880,15 @@ namespace bLua { internal::stack_guard guard(L); auto &meta = internal::state(L); std::string wanted = name ? name : meta.name; - if (wanted.empty()) internal::fail("empty type name"); + if (wanted.empty()) internal::fail(L, "empty type name"); auto del = deleter ? deleter : &internal::delete_object; if (meta.registered) { if (meta.name != wanted || meta.own != own || meta.deleter != del) - internal::fail("conflicting class registration"); + internal::fail(L, "conflicting class registration"); return; } lua_pushstring(L, wanted.c_str()); lua_rawget(L, LUA_REGISTRYINDEX); - if (!lua_isnil(L, -1)) internal::fail("type name already registered"); + if (!lua_isnil(L, -1)) internal::fail(L, "type name already registered"); lua_pop(L, 1); lua_newtable(L); lua_pushcfunction(L, (internal::boundary>)); lua_setfield(L, -2, "__gc"); @@ -894,9 +916,9 @@ namespace bLua { } // Names are state-local and copied. Changing a live registration is forbidden. template void set_type_name(lua_State *L, const char *name) { - if (!name || !*name) internal::fail("empty type name"); + if (!name || !*name) internal::fail(L, "empty type name"); auto &meta = internal::state(L); - if (meta.registered && meta.name != name) internal::fail("cannot rename registered class"); + if (meta.registered && meta.name != name) internal::fail(L, "cannot rename registered class"); meta.name = name; } template const char *get_type_name(lua_State *L) { return internal::state(L).name.c_str(); } @@ -904,7 +926,7 @@ namespace bLua { static_assert(std::is_base_of_v && !std::is_same_v, "reg_base requires a unique public base"); if (!internal::state(L).registered || !internal::state(L).registered) - internal::fail("register both classes before reg_base"); + internal::fail(L, "register both classes before reg_base"); auto to_base = +[](void *p) -> void * { return static_cast(static_cast(p)); }; @@ -980,7 +1002,7 @@ namespace bLua { constexpr int n = static_cast(std::tuple_size_v); lua_rawgeti(L, -1, n); const bool duplicate = !lua_isnil(L, -1); lua_pop(L, 1); - if (duplicate) internal::fail("duplicate overload arity"); + if (duplicate) internal::fail(L, "duplicate overload arity"); internal::push_function(L, func); lua_rawseti(L, -2, n); }; add(f); (add(fs), ...); @@ -1002,7 +1024,7 @@ namespace bLua { constexpr int n = static_cast(std::tuple_size_v + 1); lua_rawgeti(L, -1, n); const bool duplicate = !lua_isnil(L, -1); lua_pop(L, 1); - if (duplicate) internal::fail("duplicate overload arity"); + if (duplicate) internal::fail(L, "duplicate overload arity"); internal::push_function(L, func); lua_rawseti(L, -2, n); }; add(f); (add(fs), ...); @@ -1026,16 +1048,16 @@ namespace bLua { } } template void reg_constructor(lua_State *L, const char *name = nullptr) { - if (!internal::state(L).registered) internal::fail("register class before constructor"); + if (!internal::state(L).registered) internal::fail(L, "register class before constructor"); internal::stack_guard guard(L); if (name && *name) { lua_pushcfunction(L, (internal::boundary>)); lua_setglobal(L, name); } ensure_class_table(L, internal::state(L).name.c_str()); - if (!lua_getmetatable(L, -1)) internal::fail("missing class table metatable"); + if (!lua_getmetatable(L, -1)) internal::fail(L, "missing class table metatable"); lua_getfield(L, -1, "__call"); - if (!lua_isfunction(L, -1)) internal::fail("missing class table __call"); + if (!lua_isfunction(L, -1)) internal::fail(L, "missing class table __call"); lua_getupvalue(L, -1, 1); constexpr int n = static_cast(sizeof...(A) + 1); lua_rawgeti(L, -1, n); @@ -1072,7 +1094,7 @@ namespace bLua { internal::stack_guard guard(L); internal::push_function(L, getter); internal::rawgetp(L, LUA_REGISTRYINDEX, &internal::getters_key); - if (!lua_istable(L, -1)) internal::fail("class is not registered"); + if (!lua_istable(L, -1)) internal::fail(L, "class is not registered"); lua_pushvalue(L, -2); lua_setfield(L, -2, name); } template void reg_property(lua_State *L, const char *name, @@ -1082,7 +1104,7 @@ namespace bLua { internal::stack_guard guard(L); internal::push_function(L, setter); internal::rawgetp(L, LUA_REGISTRYINDEX, &internal::setters_key); - if (!lua_istable(L, -1)) internal::fail("class is not registered"); + if (!lua_istable(L, -1)) internal::fail(L, "class is not registered"); lua_pushvalue(L, -2); lua_setfield(L, -2, name); } template void reg_enum(lua_State *L, const char *name, std::initializer_list> values) { From 006478097d6a9a14d64f15a076e17d1383febe8a Mon Sep 17 00:00:00 2001 From: esrrhs Date: Tue, 1 Dec 2026 22:24:57 +0800 Subject: [PATCH 3/5] fix: do not longjmp through the C++ boundary with lua_call On MSVC, luaL_error longjmps out of a boundary try block when a field getter/setter or overload is invoked via lua_call, which can abort regressions with 0xC0000409. Catch Lua errors with lua_pcall and rethrow as C++ so the boundary unwinds first. Also log regression steps for diagnosis. --- CHANGELOG.md | 3 ++ bLua.h | 77 +++++++++++++++++++++++++++------------------ test/regression.cpp | 21 +++++++++++-- 3 files changed, 68 insertions(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 598c9d2..79d4e4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,9 @@ change and still need explicit approval. - 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. ### CI follow-up - Permit LuaJIT's foreign unwinder through callback boundaries while still translating typed diff --git a/bLua.h b/bLua.h index 890eab4..aa501c2 100644 --- a/bLua.h +++ b/bLua.h @@ -728,32 +728,49 @@ namespace bLua { push_ptr(L, obj.get(), ownership::owning); obj.release(); return 1; } // parents table layout: { base_mt, base_getters, base_setters, ... } most-derived first. - inline int class_index(lua_State *L) { - auto lookup = [&](int table, bool call_getter) -> bool { - lua_pushvalue(L, 2); - lua_rawget(L, table); - if (call_getter) { - if (!lua_isfunction(L, -1)) { lua_pop(L, 1); return false; } - lua_pushvalue(L, 1); - lua_call(L, 1, 1); - return true; - } - if (!lua_isnil(L, -1)) return true; + // Lua is built as C, so luaL_error longjmps. Never lua_call from inside a + // boundary try-block: catch the error with lua_pcall and rethrow as C++ so + // the boundary can convert it after unwinding (MSVC 0xC0000409 otherwise). + inline void raise_lua_error(lua_State *L) { + if (lua_type(L, -1) == LUA_TSTRING) { + std::string msg = lua_tostring(L, -1) ? lua_tostring(L, -1) : "Lua error"; lua_pop(L, 1); - return false; - }; - if (lookup(lua_upvalueindex(1), false)) return 1; - if (lookup(lua_upvalueindex(2), true)) return 1; + fail(L, msg); + } + lua_pop(L, 1); + fail(L, "Lua error (non-string error object)"); + } + inline void pcall_checked(lua_State *L, int nargs, int nresults) { + if (lua_pcall(L, nargs, nresults, 0) != LUA_OK) raise_lua_error(L); + } + inline bool index_method(lua_State *L, int table) { + lua_pushvalue(L, 2); + lua_rawget(L, table); + if (!lua_isnil(L, -1)) return true; + lua_pop(L, 1); + return false; + } + inline bool index_getter(lua_State *L, int table) { + lua_pushvalue(L, 2); + lua_rawget(L, table); + if (!lua_isfunction(L, -1)) { lua_pop(L, 1); return false; } + lua_pushvalue(L, 1); + pcall_checked(L, 1, 1); + return true; + } + inline int class_index(lua_State *L) { + if (index_method(L, lua_upvalueindex(1))) return 1; + if (index_getter(L, lua_upvalueindex(2))) return 1; rawgetp(L, lua_upvalueindex(1), &parents_key); if (lua_istable(L, -1)) { const size_t n = rawlen(L, -1); for (size_t i = 1; i + 2 <= n; i += 3) { rawgeti_idx(L, -1, static_cast(i)); - const bool have = lookup(lua_gettop(L), false); + const bool have = index_method(L, lua_gettop(L)); lua_remove(L, have ? -2 : -1); if (have) { lua_remove(L, -2); return 1; } rawgeti_idx(L, -1, static_cast(i + 1)); - const bool got = lookup(lua_gettop(L), true); + const bool got = index_getter(L, lua_gettop(L)); lua_remove(L, got ? -2 : -1); if (got) { lua_remove(L, -2); return 1; } } @@ -762,23 +779,23 @@ namespace bLua { lua_pushnil(L); return 1; } + inline bool newindex_setter(lua_State *L, int table) { + lua_pushvalue(L, 2); + lua_rawget(L, table); + if (!lua_isfunction(L, -1)) { lua_pop(L, 1); return false; } + lua_pushvalue(L, 1); + lua_pushvalue(L, 3); + pcall_checked(L, 2, 0); + return true; + } inline int class_newindex(lua_State *L) { - auto lookup = [&](int table) -> bool { - lua_pushvalue(L, 2); - lua_rawget(L, table); - if (!lua_isfunction(L, -1)) { lua_pop(L, 1); return false; } - lua_pushvalue(L, 1); - lua_pushvalue(L, 3); - lua_call(L, 2, 0); - return true; - }; - if (lookup(lua_upvalueindex(1))) return 0; + if (newindex_setter(L, lua_upvalueindex(1))) return 0; rawgetp(L, lua_upvalueindex(2), &parents_key); if (lua_istable(L, -1)) { const size_t n = rawlen(L, -1); for (size_t i = 3; i <= n; i += 3) { rawgeti_idx(L, -1, static_cast(i)); - const bool got = lookup(lua_gettop(L)); + const bool got = newindex_setter(L, lua_gettop(L)); lua_pop(L, 1); if (got) { lua_pop(L, 1); return 0; } } @@ -800,7 +817,7 @@ namespace bLua { const int n = lua_gettop(L); lua_rawgeti(L, lua_upvalueindex(1), n); if (!lua_isfunction(L, -1)) fail(L, std::string("no overload matches argument count ") + std::to_string(n)); - lua_insert(L, 1); lua_call(L, n, LUA_MULTRET); return lua_gettop(L); + lua_insert(L, 1); pcall_checked(L, n, LUA_MULTRET); return lua_gettop(L); } inline void push_traceback(lua_State *L) { globals(L); rawfield(L, -1, "debug"); lua_remove(L, -2); @@ -854,7 +871,7 @@ namespace bLua { // Only trivial locals cross Lua's error longjmp. Argument / result validation // uses C++ exceptions, not luaL_check*; user function errors stay in lua_pcall. if (lua_pcall(L, static_cast(std::tuple_size_v), static_cast(std::tuple_size_v), handler)) - return lua_error(L); + raise_lua_error(L); auto values = read_results(L, std::make_index_sequence>{}); ctx.rets = std::move(values); return 0; diff --git a/test/regression.cpp b/test/regression.cpp index ffba458..0570aa2 100644 --- a/test/regression.cpp +++ b/test/regression.cpp @@ -411,10 +411,25 @@ void test_dx() { script(L, "derived=nil; base=nil; o=nil; collectgarbage('collect'); collectgarbage('collect')"); } +void step(const char *name) { + std::fprintf(stderr, "[regression] %s\n", name); + std::fflush(stderr); +} int main() { try { - test_states(false); test_states(true); test_ownership(); test_errors(); test_containers_overloads(); test_dx(); - std::puts("All lifetime/error/container regressions passed"); return 0; - } catch (const std::exception &e) { std::fprintf(stderr,"%s\n",e.what()); return 1; } + step("states"); test_states(false); test_states(true); + step("ownership"); test_ownership(); + step("errors"); test_errors(); + step("containers"); test_containers_overloads(); + step("dx"); test_dx(); + step("done"); + std::puts("All lifetime/error/container regressions passed"); + std::fflush(stdout); std::fflush(stderr); + return 0; + } catch (const std::exception &e) { + std::fprintf(stderr,"%s\n",e.what()); std::fflush(stderr); return 1; + } catch (...) { + std::fprintf(stderr,"unknown exception in regressions\n"); std::fflush(stderr); return 1; + } } From 5b86c5165e7d457dcb7174a5c8bae27fe275050e Mon Sep 17 00:00:00 2001 From: esrrhs Date: Tue, 1 Dec 2026 22:40:30 +0800 Subject: [PATCH 4/5] fix: avoid LUA_OK so Lua 5.1 still compiles pcall_checked now treats a non-zero lua_pcall result as failure, matching other protected-call sites. Retry apt-get in Linux CI after a transient mirror 503 on liblua5.2. --- .github/workflows/c-cpp.yml | 21 +++++++++++++++------ CHANGELOG.md | 2 ++ bLua.h | 3 ++- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/.github/workflows/c-cpp.yml b/.github/workflows/c-cpp.yml index a0c075b..37173fd 100644 --- a/.github/workflows/c-cpp.yml +++ b/.github/workflows/c-cpp.yml @@ -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: @@ -49,8 +52,11 @@ jobs: - name: Install LuaJIT run: | - sudo apt-get update - sudo apt-get install -y libluajit-5.1-dev pkg-config + for attempt in 1 2 3 4 5; do + sudo apt-get update && sudo apt-get install -y libluajit-5.1-dev pkg-config && break + if [ "$attempt" = 5 ]; then exit 1; fi + sleep $((attempt * 15)) + done - name: Configure CMake run: | @@ -134,8 +140,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 }} \ diff --git a/CHANGELOG.md b/CHANGELOG.md index 79d4e4e..b239d6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,8 @@ change and still need explicit approval. - 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 diff --git a/bLua.h b/bLua.h index aa501c2..7ada910 100644 --- a/bLua.h +++ b/bLua.h @@ -741,7 +741,8 @@ namespace bLua { fail(L, "Lua error (non-string error object)"); } inline void pcall_checked(lua_State *L, int nargs, int nresults) { - if (lua_pcall(L, nargs, nresults, 0) != LUA_OK) raise_lua_error(L); + // Lua 5.1 has no LUA_OK; success is 0 on every supported version. + if (lua_pcall(L, nargs, nresults, 0)) raise_lua_error(L); } inline bool index_method(lua_State *L, int table) { lua_pushvalue(L, 2); From 38e2d89c73750c58e34bc635e7914ed379ec1505 Mon Sep 17 00:00:00 2001 From: esrrhs Date: Tue, 1 Dec 2026 22:54:47 +0800 Subject: [PATCH 5/5] ci: build pinned shared LuaJIT instead of apt packages Ubuntu universe mirrors were returning 503 for libluajit-5.1-dev even after retries. Keep testing the shared library so the foreign-unwinder path stays covered. --- .github/workflows/c-cpp.yml | 26 ++++++++++++++++---------- .gitignore | 3 +++ CHANGELOG.md | 3 +++ 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/.github/workflows/c-cpp.yml b/.github/workflows/c-cpp.yml index 37173fd..7e89fee 100644 --- a/.github/workflows/c-cpp.yml +++ b/.github/workflows/c-cpp.yml @@ -50,27 +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: | - for attempt in 1 2 3 4 5; do - sudo apt-get update && sudo apt-get install -y libluajit-5.1-dev pkg-config && break - if [ "$attempt" = 5 ]; then exit 1; fi - sleep $((attempt * 15)) - done + 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 diff --git a/.gitignore b/.gitignore index 152ab8f..c320531 100644 --- a/.gitignore +++ b/.gitignore @@ -49,3 +49,6 @@ Testing/ # 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/ diff --git a/CHANGELOG.md b/CHANGELOG.md index b239d6c..4d7da2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,9 @@ change and still need explicit approval. ### 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. +- 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.