00001 #ifndef LUAPP_VAR_HPP
00002 #define LUAPP_VAR_HPP
00003
00004 #include "luapp_exception.hpp"
00005 #include <typeinfo>
00006 #include <memory>
00007
00008 namespace lua
00009 {
00010 typedef std::type_info var_type;
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 class var
00026 {
00027 public :
00028
00029
00030 var();
00031
00032
00033
00034
00035 template <class T>
00036 var(const T& mValue) : pValue_(new value<T>(mValue)) {}
00037
00038
00039
00040
00041 var(const var& mVar);
00042
00043 var& operator = (const var& mVar);
00044
00045 bool operator == (const var& mVar) const;
00046
00047 bool operator != (const var& mVar) const;
00048
00049
00050
00051
00052 void swap(var& mVar);
00053
00054
00055
00056
00057
00058
00059
00060 template<class T>
00061 const T& get() const
00062 {
00063 const value<T>* pValue = dynamic_cast<const value<T>*>(pValue_.get());
00064
00065 if (pValue)
00066 return pValue->mT_;
00067
00068 throw lua::exception("var",
00069 "Conversion from "+std::string(pValue ? "type \""+std::string(pValue_->get_type().name())
00070 +"\"" : "empty lua::var")+" to \""+typeid(T).name()+"\" failed."
00071 );
00072 }
00073
00074
00075
00076
00077
00078
00079 bool is_empty() const;
00080
00081
00082
00083
00084
00085 const var_type& get_type() const;
00086
00087
00088
00089
00090
00091 template<class T>
00092 bool is_of_type() const
00093 {
00094 if (pValue_)
00095 {
00096 return pValue_->get_type() == typeid(T);
00097 }
00098 else
00099 {
00100 return typeid(void) == typeid(T);
00101 }
00102 }
00103
00104
00105
00106
00107 std::string to_string() const;
00108
00109 static const var_type& VALUE_NONE;
00110 static const var_type& VALUE_INT;
00111 static const var_type& VALUE_UINT;
00112 static const var_type& VALUE_FLOAT;
00113 static const var_type& VALUE_DOUBLE;
00114 static const var_type& VALUE_BOOL;
00115 static const var_type& VALUE_STRING;
00116 static const var_type& VALUE_POINTER;
00117
00118 private :
00119
00120
00121
00122
00123 class value_base
00124 {
00125 public :
00126
00127 virtual ~value_base() {}
00128 virtual value_base* clone() const = 0;
00129 virtual const var_type& get_type() const = 0;
00130 };
00131
00132 template <class T>
00133 class value : public value_base
00134 {
00135 public :
00136
00137 #ifdef MSVC
00138
00139
00140
00141 #pragma warning( disable : 4396 )
00142 #endif
00143 friend const T& var::get<>() const;
00144
00145 value(const T& mT) : mT_(mT) {}
00146
00147 value_base* clone() const
00148 {
00149 return new value(mT_);
00150 }
00151
00152 const var_type& get_type() const
00153 {
00154 return typeid(T);
00155 }
00156
00157 private :
00158
00159 T mT_;
00160 };
00161
00162
00163
00164
00165 std::unique_ptr<value_base> pValue_;
00166 };
00167 }
00168
00169 #endif