From 8f085e02a107dd8092393935bfa1bba71d2546d2 Mon Sep 17 00:00:00 2001 From: DS Date: Fri, 4 Jun 2021 21:22:33 +0200 Subject: Add metatables to lua vectors (#11039) Add backwards-compatible metatable functions for vectors. --- src/script/common/c_converter.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'src/script/common/c_converter.cpp') diff --git a/src/script/common/c_converter.cpp b/src/script/common/c_converter.cpp index c00401b58..d848b75b8 100644 --- a/src/script/common/c_converter.cpp +++ b/src/script/common/c_converter.cpp @@ -51,6 +51,29 @@ if (value < F1000_MIN || value > F1000_MAX) { \ #define CHECK_POS_TAB(index) CHECK_TYPE(index, "position", LUA_TTABLE) +/** + * A helper which sets (if available) the vector metatable from builtin as metatable + * for the table on top of the stack + */ +static void set_vector_metatable(lua_State *L) +{ + // get vector.metatable + lua_getglobal(L, "vector"); + if (!lua_istable(L, -1)) { + // there is no global vector table + lua_pop(L, 1); + errorstream << "set_vector_metatable in c_converter.cpp: " << + "missing global vector table" << std::endl; + return; + } + lua_getfield(L, -1, "metatable"); + // set the metatable + lua_setmetatable(L, -3); + // pop vector global + lua_pop(L, 1); +} + + void push_float_string(lua_State *L, float value) { std::stringstream ss; @@ -69,6 +92,7 @@ void push_v3f(lua_State *L, v3f p) lua_setfield(L, -2, "y"); lua_pushnumber(L, p.Z); lua_setfield(L, -2, "z"); + set_vector_metatable(L); } void push_v2f(lua_State *L, v2f p) @@ -281,6 +305,7 @@ void push_v3s16(lua_State *L, v3s16 p) lua_setfield(L, -2, "y"); lua_pushinteger(L, p.Z); lua_setfield(L, -2, "z"); + set_vector_metatable(L); } v3s16 read_v3s16(lua_State *L, int index) -- cgit v1.2.3