Bind an instance method (`calculate`/`reset`) by name WITHOUT triggering any metamethod: first a raw field on the instance, else a raw lookup through a TABLE-valued `__index` — the `setmetatable(state, Class)` class idiom. A `__index` function* is deliberately never invoked (it would run unbounded Lua outside any pcall/fuel guard during binding), so an adversarial metatable cannot execute code her
| 386 | // the instance as `self`; false for a plain closure field (called without self) or |
| 387 | // when nothing was found. |
| 388 | [[nodiscard]] bool pushInstanceMethod(lua_State* L, int inst_idx, const char* name) { |
| 389 | lua_rawgetfield(L, inst_idx, name); |
| 390 | if (!lua_isnil(L, -1)) { |
| 391 | return false; // a plain field on the instance (closure-style) — no self |
| 392 | } |
| 393 | lua_pop(L, 1); |
| 394 | if (lua_getmetatable(L, inst_idx) == 0) { |
| 395 | lua_pushnil(L); |
| 396 | return false; // no metatable |
| 397 | } |
| 398 | // stack: [..., metatable] |
| 399 | bool via_metatable = false; |
| 400 | lua_rawgetfield(L, -1, "__index"); // [..., metatable, __index] |
| 401 | if (lua_istable(L, -1)) { |
| 402 | lua_rawgetfield(L, -1, name); // [..., metatable, __index, method] |
| 403 | via_metatable = lua_isfunction(L, -1); |
| 404 | lua_replace(L, -2); // [..., metatable, method] (drop __index) |
| 405 | } else { |
| 406 | lua_pop(L, 1); // a non-table __index is not a class — ignore it |
| 407 | lua_pushnil(L); // [..., metatable, nil] |
| 408 | } |
| 409 | lua_replace(L, -2); // [..., method-or-nil] (drop metatable) |
| 410 | return via_metatable; |
| 411 | } |
| 412 | |
| 413 | // ---- the live instance --------------------------------------------------- |
| 414 |