1
0
Fork 0
mirror of https://github.com/OpenMW/openmw.git synced 2025-01-16 20:29:57 +00:00

Support multiple arguments in Lua callbacks.

This commit is contained in:
Petr Mikheev 2021-11-21 13:12:35 +01:00
parent 3ea4305a60
commit f9136d4392
3 changed files with 30 additions and 11 deletions

View file

@ -440,4 +440,24 @@ return {
EXPECT_EQ(counter4, 25); EXPECT_EQ(counter4, 25);
} }
TEST_F(LuaScriptsContainerTest, CallbackWrapper)
{
LuaUtil::Callback callback{mLua.sol()["print"], mLua.newTable()};
callback.mHiddenData[LuaUtil::ScriptsContainer::sScriptDebugNameKey] = "some_script.lua";
callback.mHiddenData[LuaUtil::ScriptsContainer::sScriptIdKey] = LuaUtil::ScriptsContainer::ScriptId{nullptr, 0};
testing::internal::CaptureStdout();
callback(1.5);
EXPECT_EQ(internal::GetCapturedStdout(), "1.5\n");
testing::internal::CaptureStdout();
callback(1.5, 2.5);
EXPECT_EQ(internal::GetCapturedStdout(), "1.5\t2.5\n");
testing::internal::CaptureStdout();
callback.mHiddenData[LuaUtil::ScriptsContainer::sScriptIdKey] = sol::nil;
callback(1.5, 2.5);
EXPECT_EQ(internal::GetCapturedStdout(), "Ignored callback to the removed script some_script.lua\n");
}
} }

View file

@ -530,13 +530,4 @@ namespace LuaUtil
updateTimerQueue(mHoursTimersQueue, gameHours); updateTimerQueue(mHoursTimersQueue, gameHours);
} }
void Callback::operator()(sol::object arg) const
{
if (mHiddenData[ScriptsContainer::sScriptIdKey] != sol::nil)
LuaUtil::call(mFunc, std::move(arg));
else
Log(Debug::Debug) << "Ignored callback to the removed script "
<< mHiddenData.get<std::string>(ScriptsContainer::sScriptDebugNameKey);
}
} }

View file

@ -242,7 +242,7 @@ namespace LuaUtil
int64_t mTemporaryCallbackCounter = 0; int64_t mTemporaryCallbackCounter = 0;
}; };
// Wrapper for a single-argument Lua function. // Wrapper for a Lua function.
// Holds information about the script the function belongs to. // Holds information about the script the function belongs to.
// Needed to prevent callback calls if the script was removed. // Needed to prevent callback calls if the script was removed.
struct Callback struct Callback
@ -250,7 +250,15 @@ namespace LuaUtil
sol::function mFunc; sol::function mFunc;
sol::table mHiddenData; // same object as Script::mHiddenData in ScriptsContainer sol::table mHiddenData; // same object as Script::mHiddenData in ScriptsContainer
void operator()(sol::object arg) const; template <typename... Args>
void operator()(Args&&... args) const
{
if (mHiddenData[ScriptsContainer::sScriptIdKey] != sol::nil)
LuaUtil::call(mFunc, std::forward<Args>(args)...);
else
Log(Debug::Debug) << "Ignored callback to the removed script "
<< mHiddenData.get<std::string>(ScriptsContainer::sScriptDebugNameKey);
}
}; };
} }