From 33c19e1a8c8287e34140d5a51308ac9aa713376a Mon Sep 17 00:00:00 2001 From: Peter van Dijk Date: Tue, 17 Mar 2020 16:49:32 +0100 Subject: [PATCH] lua: don't destroy keys during table iteration via https://github.com/ahupowerdns/luawrapper/pull/38 --- ext/luawrapper/include/LuaContext.hpp | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/ext/luawrapper/include/LuaContext.hpp b/ext/luawrapper/include/LuaContext.hpp index b4c9ef15e42c..ffcc45cd0ae4 100644 --- a/ext/luawrapper/include/LuaContext.hpp +++ b/ext/luawrapper/include/LuaContext.hpp @@ -2649,11 +2649,21 @@ struct LuaContext::Reader static auto read(lua_State* state, int index) -> boost::optional { + std::string result; + + // lua_tolstring might convert the variable that would confuse lua_next, so we + // make a copy of the variable. + lua_pushvalue(state, index); + size_t len; - const auto val = lua_tolstring(state, index, &len); - if (val == 0) - return boost::none; - return std::string(val, len); + const auto val = lua_tolstring(state, -1, &len); + + if (val != 0) + result.assign(val, len); + + lua_pop(state, 1); + + return val != 0 ? boost::optional{ std::move(result) } : boost::none; } };