1
0
Fork 0
mirror of https://github.com/OpenMW/openmw.git synced 2025-01-30 09:15:38 +00:00

Function LuaUtil::toString

This commit is contained in:
Petr Mikheev 2021-08-31 09:37:27 +02:00
parent 18f51e1026
commit 33d4d88447
4 changed files with 23 additions and 0 deletions

View file

@ -77,6 +77,14 @@ return {
EXPECT_EQ(LuaUtil::call(script1["get"]).get<int>(), 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:");

View file

@ -1,6 +1,7 @@
#include "gmock/gmock.h"
#include <gtest/gtest.h>
#include <components/lua/luastate.hpp>
#include <components/lua/utilpackage.hpp>
#include "testing_util.hpp"
@ -45,6 +46,7 @@ namespace
EXPECT_FLOAT_EQ(lua.safe_script("return v.y").get<float>(), 12);
EXPECT_FLOAT_EQ(lua.safe_script("return v.z").get<float>(), 13);
EXPECT_EQ(lua.safe_script("return tostring(v)").get<std::string>(), "(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<float>(), 5);
EXPECT_FLOAT_EQ(lua.safe_script("return util.vector3(4, 0, 3):length2()").get<float>(), 25);
EXPECT_FALSE(lua.safe_script("return util.vector3(1, 2, 3) == util.vector3(1, 3, 2)").get<bool>());

View file

@ -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<std::string>() + "\"";
else
return call(sol::state_view(obj.lua_state())["tostring"], obj);
}
}

View file

@ -103,6 +103,9 @@ namespace LuaUtil
return getFieldOrNil(table.as<sol::table>()[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