0ad/source/simulation2/components/ICmpIdentity.cpp
trompetin17 5b8cb7f34b
Support std::optional in FromJSVal
This commit introduces support for std::optional<T> in
Script::FromJSVal. When a JavaScript value is undefined or null, the
resulting optional is set to std::nullopt; otherwise, the value is
converted and wrapped.

This change allows components to cleanly handle optional script values
without needing manual null checks or exception handling in C++.

As a direct application of this feature, the Identity component now uses
std::optional<std::wstring> for the return value of GetCiv(). This
resolves a bug where formation templates (e.g., those inheriting from
template_formation.xml) do not explicitly define a civ. After commit
03f7903fec, the code assumed GetCiv() would always return a valid
string, leading to undefined behavior when it was missing.

With this update:
- GetCiv() returning undefined results in an empty optional.
- The Identity component defaults to an empty civilization string ("")
  when the civ is not defined.
- This avoids crashes or actor parsing errors for civ-less templates and
  improves robustness in script-C++ interaction.

Closes: #8107
Fixes: #8091
2025-06-19 08:52:24 -05:00

52 lines
1.5 KiB
C++

/* Copyright (C) 2025 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
#include "precompiled.h"
#include "ICmpIdentity.h"
#include "simulation2/system/InterfaceScripted.h"
#include "simulation2/scripting/ScriptComponent.h"
#include <optional>
BEGIN_INTERFACE_WRAPPER(Identity)
END_INTERFACE_WRAPPER(Identity)
class CCmpIdentityScripted : public ICmpIdentity
{
public:
DEFAULT_SCRIPT_WRAPPER(IdentityScripted)
std::string GetSelectionGroupName() override
{
return m_Script.Call<std::string>("GetSelectionGroupName");
}
std::wstring GetPhenotype() override
{
return m_Script.Call<std::wstring>("GetPhenotype");
}
std::wstring GetCiv() override
{
std::optional<std::wstring> civ{m_Script.Call<std::optional<std::wstring>>("GetCiv")};
return !civ || !civ.has_value() ? L"" : *civ;
}
};
REGISTER_COMPONENT_SCRIPT_WRAPPER(IdentityScripted)