From 33d4d884474d83951445283c58e094cb6043dd3a Mon Sep 17 00:00:00 2001 From: Petr Mikheev Date: Tue, 31 Aug 2021 09:37:27 +0200 Subject: [PATCH] Function LuaUtil::toString --- apps/openmw_test_suite/lua/test_lua.cpp | 8 ++++++++ apps/openmw_test_suite/lua/test_utilpackage.cpp | 2 ++ components/lua/luastate.cpp | 10 ++++++++++ components/lua/luastate.hpp | 3 +++ 4 files changed, 23 insertions(+) diff --git a/apps/openmw_test_suite/lua/test_lua.cpp b/apps/openmw_test_suite/lua/test_lua.cpp index 69a326060c..9405dba4b2 100644 --- a/apps/openmw_test_suite/lua/test_lua.cpp +++ b/apps/openmw_test_suite/lua/test_lua.cpp @@ -77,6 +77,14 @@ return { EXPECT_EQ(LuaUtil::call(script1["get"]).get(), 45); } + TEST_F(LuaStateTest, ToString) + { + EXPECT_EQ(LuaUtil::toString(sol::make_object(mLua.sol(), 3.14)), "3.14"); + EXPECT_EQ(LuaUtil::toString(sol::make_object(mLua.sol(), true)), "true"); + EXPECT_EQ(LuaUtil::toString(sol::nil), "nil"); + EXPECT_EQ(LuaUtil::toString(sol::make_object(mLua.sol(), "something")), "\"something\""); + } + TEST_F(LuaStateTest, ErrorHandling) { EXPECT_ERROR(mLua.runInNewSandbox("invalid.lua"), "[string \"invalid.lua\"]:1:"); diff --git a/apps/openmw_test_suite/lua/test_utilpackage.cpp b/apps/openmw_test_suite/lua/test_utilpackage.cpp index afd9fa2d3c..fb8e48e461 100644 --- a/apps/openmw_test_suite/lua/test_utilpackage.cpp +++ b/apps/openmw_test_suite/lua/test_utilpackage.cpp @@ -1,6 +1,7 @@ #include "gmock/gmock.h" #include +#include #include #include "testing_util.hpp" @@ -45,6 +46,7 @@ namespace EXPECT_FLOAT_EQ(lua.safe_script("return v.y").get(), 12); EXPECT_FLOAT_EQ(lua.safe_script("return v.z").get(), 13); EXPECT_EQ(lua.safe_script("return tostring(v)").get(), "(5, 12, 13)"); + EXPECT_EQ(LuaUtil::toString(lua.safe_script("return v")), "(5, 12, 13)"); EXPECT_FLOAT_EQ(lua.safe_script("return util.vector3(4, 0, 3):length()").get(), 5); EXPECT_FLOAT_EQ(lua.safe_script("return util.vector3(4, 0, 3):length2()").get(), 25); EXPECT_FALSE(lua.safe_script("return util.vector3(1, 2, 3) == util.vector3(1, 3, 2)").get()); diff --git a/components/lua/luastate.cpp b/components/lua/luastate.cpp index 1b52db11ad..fd42aa7fb2 100644 --- a/components/lua/luastate.cpp +++ b/components/lua/luastate.cpp @@ -167,4 +167,14 @@ namespace LuaUtil #endif } + std::string toString(const sol::object& obj) + { + if (obj == sol::nil) + return "nil"; + else if (obj.get_type() == sol::type::string) + return "\"" + obj.as() + "\""; + else + return call(sol::state_view(obj.lua_state())["tostring"], obj); + } + } diff --git a/components/lua/luastate.hpp b/components/lua/luastate.hpp index 6bac1612e7..acaaadea76 100644 --- a/components/lua/luastate.hpp +++ b/components/lua/luastate.hpp @@ -103,6 +103,9 @@ namespace LuaUtil return getFieldOrNil(table.as()[first], str...); } + // String representation of a Lua object. Should be used for debugging/logging purposes only. + std::string toString(const sol::object&); + } #endif // COMPONENTS_LUA_LUASTATE_H