From 70c7f1880d3dd59223aaf6daa41ee00b067eb5b5 Mon Sep 17 00:00:00 2001 From: Petr Mikheev Date: Fri, 6 May 2022 23:11:47 +0200 Subject: [PATCH] [Lua] pairs and ipairs for ObjectList (resolves #6732) --- apps/openmw/mwlua/objectbindings.cpp | 26 ++------------------------ components/lua/luastate.cpp | 9 +++++++++ 2 files changed, 11 insertions(+), 24 deletions(-) diff --git a/apps/openmw/mwlua/objectbindings.cpp b/apps/openmw/mwlua/objectbindings.cpp index 0bf3fc99c5..3cab81c38d 100644 --- a/apps/openmw/mwlua/objectbindings.cpp +++ b/apps/openmw/mwlua/objectbindings.cpp @@ -131,30 +131,8 @@ namespace MWLua else throw std::runtime_error("Index out of range"); }; - if constexpr (std::is_same_v) - { - // GObject and LObject iterators are in separate branches because if they share source code - // there is a collision in sol and only one iterator can be mapped to Lua. - auto iter = sol::make_object(lua, [registry](const GObjectList& l, int64_t i) -> sol::optional> - { - if (i >= 0 && i < static_cast(l.mIds->size())) - return std::make_tuple(i + 1, GObject((*l.mIds)[i], registry)); - else - return sol::nullopt; - }); - listT[sol::meta_function::ipairs] = [iter](const GObjectList& list) { return std::make_tuple(iter, list, 0); }; - } - else - { - auto iter = sol::make_object(lua, [registry](const LObjectList& l, int64_t i) -> sol::optional> - { - if (i >= 0 && i < static_cast(l.mIds->size())) - return std::make_tuple(i + 1, LObject((*l.mIds)[i], registry)); - else - return sol::nullopt; - }); - listT[sol::meta_function::ipairs] = [iter](const LObjectList& list) { return std::make_tuple(iter, list, 0); }; - } + listT[sol::meta_function::pairs] = lua["ipairsForArray"].template get(); + listT[sol::meta_function::ipairs] = lua["ipairsForArray"].template get(); } template diff --git a/components/lua/luastate.cpp b/components/lua/luastate.cpp index 38f3ae889e..ac32f12992 100644 --- a/components/lua/luastate.cpp +++ b/components/lua/luastate.cpp @@ -92,6 +92,15 @@ namespace LuaUtil local nextFn, t, firstKey = ipairs(getmetatable(v).__index) return function(_, k) return nextFn(t, k) end, v, firstKey end + local function nextForArray(array, index) + index = (index or 0) + 1 + if index < #array then + return index, array[index] + end + end + function ipairsForArray(array) + return nextForArray, array, 0 + end getmetatable('').__metatable = false getSafeMetatable = function(v)