#pragma once #include "dtcore/inc/dtstreamjsonoutput.h" #include "dtcore/inc/dtstreamjsoninput.h" #include "dtcore/inc/dtjsonvalue.h" namespace dt { // This class represent the value of an object in the scripting system. // It allows to serialize a native value to a Json form which allows to easily // send it over the network. It also allows to deserialize it back to a native format. class ScriptObject : public Serializable { public: // Default constructor, represents an empty value DT_CORE_DLL_ENTRY ScriptObject(); // Constructor accepting any of serializable types: // - S8, S16, S32, S64, U8, U16, U32, U64 // - bool // - double, float // - String // - ByteBuffer // - Vector, Map, Set // - Serializable template ScriptObject(const T& value, bool isReference = false); // comparison operator DT_CORE_DLL_ENTRY bool operator==(const ScriptObject& rhs) const; // comparison operator DT_CORE_DLL_ENTRY bool operator!=(const ScriptObject& rhs) const; // change the current script object value to the new value specified template void Set(const T& value, bool isReference = false); // get the current script object value back into a native type template bool Get(T* out) const; // returns true, if the script object is empty DT_CORE_DLL_ENTRY bool IsEmpty() const { return m_JsonValue.IsEmpty(); } // returns true, if the script object is a String referring to another variable DT_CORE_DLL_ENTRY bool IsReference() const { return m_IsReference; } // returns the Json representation of the script object value DT_CORE_DLL_ENTRY const JsonValue& GetJsonValue() const { return m_JsonValue; } // change the Json representation of the script object value DT_CORE_DLL_ENTRY void SetJsonValue(const JsonValue& json) { m_JsonValue = json; } // serialize function DT_CORE_DLL_ENTRY virtual void Serialize(U8 version, Stream& stream) override; private: bool m_IsReference; JsonValue m_JsonValue; }; // stringify the script object Json value DT_CORE_DLL_ENTRY String& operator<<(String& out, const ScriptObject& obj); template inline ScriptObject::ScriptObject(const T& value, bool isReference) { Set(value, isReference); } template inline void ScriptObject::Set(const T& value, bool isReference) { m_IsReference = isReference; String jsonStr; StreamJsonOutput sjo(&jsonStr); sjo << value; JsonValue::Parse(jsonStr, &m_JsonValue); } template <> inline void ScriptObject::Set(const JsonValue& value, bool isReference) { SetJsonValue(value); m_IsReference = isReference; } template inline bool ScriptObject::Get(T* out) const { if (IsEmpty()) { return false; } StreamJsonInput sji(m_JsonValue); sji << *out; return sji.HasSucceeded(); } }