1usertype<T>
2===========
3*structures and classes from C++ made available to Lua code*
4
5
6.. note::
7
8	``T`` refers to the type being turned into a usertype.
9
10While other frameworks extend lua's syntax or create Data Structure Languages (DSLs) to create classes in Lua, :doc:`Sol<../index>` instead offers the ability to generate easy bindings that pile on performance. You can see a `small starter example here`_. These use metatables and userdata in Lua for their implementation. Usertypes are also `runtime extensible`_.
11
12There are more advanced use cases for how to create and use a usertype, which are all based on how to use its constructor (see below).
13
14enumerations
15------------
16
17.. _meta_function_enum:
18
19.. code-block:: cpp
20	:caption: meta_function enumeration for names
21	:linenos:
22
23	enum class meta_function {
24		construct,
25		index,
26		new_index,
27		mode,
28		call,
29		call_function = call,
30		metatable,
31		to_string,
32		length,
33		unary_minus,
34		addition,
35		subtraction,
36		multiplication,
37		division,
38		modulus,
39		power_of,
40		involution = power_of,
41		concatenation,
42		equal_to,
43		less_than,
44		less_than_or_equal_to,
45		garbage_collect,
46		floor_division,
47		bitwise_left_shift,
48		bitwise_right_shift,
49		bitwise_not,
50		bitwise_and,
51		bitwise_or,
52		bitwise_xor,
53		pairs,
54		ipairs,
55		next,
56		type,
57		type_info,
58	};
59
60	typedef meta_function meta_method;
61
62
63Use this enumeration to specify names in a manner friendlier than memorizing the special lua metamethod names for each of these. Each binds to a specific operation indicated by the descriptive name of the enum. You can read more about `the metamethods in the Lua manual`_ and learn about how they work and are supposed to be implemented there. Each of the names here (except for the ones used as shortcuts to other names like ``meta_function::call_function`` and ``meta_function::involution`` and not including ``construct``, which just maps to the name ``new``) link directly to the Lua name for the operation. ``meta_function::pairs`` is only available in Lua 5.2 and above (does not include LuaJIT or Lua 5.1) and ``meta_function::ipairs`` is only available in Lua 5.2 exactly (disregarding compatibiltiy flags).
64
65members
66-------
67
68.. code-block:: cpp
69	:caption: function: usertype<T> constructor
70	:name: usertype-constructor
71
72	template<typename... Args>
73	usertype<T>(Args&&... args);
74
75
76The constructor of usertype takes a variable number of arguments. It takes an even number of arguments (except in the case where the very first argument is passed as the :ref:`constructor list type<constructor>`). Names can either be strings, :ref:`special meta_function enumerations<meta_function_enum>`, or one of the special indicators for initializers.
77
78
79usertype constructor options
80++++++++++++++++++++++++++++
81
82If you don't specify any constructor options at all and the type is `default_constructible`_, Sol will generate a ``new`` for you. Otherwise, the following are special ways to handle the construction of a usertype:
83
84..  _constructor:
85
86* ``"{name}", constructors<T(), T(arg-1-0), T(arg-2-0, arg-2-1), ...>``
87	- Specify the constructors to be bound under ``name``: list constructors by specifying their function signature with ``class_type(arg0, arg1, ... argN)``
88	- If you pass the ``constructors<...>`` argument first when constructing the usertype, then it will automatically be given a ``"{name}"`` of ``"new"``
89* ``"{name}", constructors<Type-List-0, Type-List-1, ...>``
90	- This syntax is longer and provided for backwards-compatibility: the above argument syntax is shorter and cleaner
91	- ``Type-List-N`` must be a ``sol::types<Args...>``, where ``Args...`` is a list of types that a constructor takes. Supports overloading by default
92	- If you pass the ``constructors<...>`` argument first when constructing the usertype, then it will automatically be given a ``"{name}"`` of ``"new"``
93* ``"{name}", sol::initializers( func1, func2, ... )``
94	- Used to handle *initializer functions* that need to initialize the memory itself (but not actually allocate the memory, since that comes as a userdata block from Lua)
95	- Given one or more functions, provides an overloaded Lua function for creating the specified type
96		+ The function must have the argument signature ``func( T*, Arguments... )`` or ``func( T&, Arguments... )``, where the pointer or reference will point to a place of allocated memory that has an uninitialized ``T``. Note that Lua controls the memory, so performing a ``new`` and setting it to the ``T*`` or ``T&`` is a bad idea: instead, use ``placement new`` to invoke a constructor, or deal with the memory exactly as you see fit
97* ``{anything}, sol::factories( func1, func2, ... )``
98	- Used to indicate that a factory function (e.g., something that produces a ``std::unique_ptr<T, ...>``, ``std::shared_ptr<T>``, ``T``, or similar) will be creating the object type
99	- Given one or more functions, provides an overloaded function for invoking
100		+ The functions can take any form and return anything, since they're just considered to be some plain function and no placement new or otherwise needs to be done. Results from this function will be pushed into Lua according to the same rules as everything else.
101		+ Can be used to stop the generation of a ``.new()`` default constructor since a ``sol::factories`` entry will be recognized as a constructor for the usertype
102		+ If this is not sufficient, see next 2 entries on how to specifically block a constructor
103* ``{anything}, {some_factory_function}``
104	- Essentially binds whatever the function is to name ``{anything}``
105	- When used WITH the ``sol::no_constructor`` option below (e.g. ``"new", sol::no_constructor`` and after that having ``"create", &my_creation_func``), one can remove typical constructor avenues and then only provide specific factory functions. Note that this combination is similar to using the ``sol::factories`` method mentioned earlier in this list. To control the destructor as well, see further below
106* ``sol::call_constructor, {valid constructor / initializer / factory}``
107	- The purpose of this is to enable the syntax ``local v = my_class( 24 )`` and have that call a constructor; it has no other purpose
108	- This is compatible with luabind, kaguya and other Lua library syntaxes and looks similar to C++ syntax, but the general consensus in Programming with Lua and other places is to use a function named ``new``
109	- Note that with the ``sol::call_constructor`` key, a construct type above must be specified. A free function without it will pass in the metatable describing this object as the first argument without that distinction, which can cause strange runtime errors.
110* ``{anything}, sol::no_constructor``
111	- Specifically tells Sol not to create a ``.new()`` if one is not specified and the type is default-constructible
112	- When the key ``{anything}`` is called on the table, it will result in an error. The error might be that the type is not-constructible.
113	- *Use this plus some of the above to allow a factory function for your function type but prevent other types of constructor idioms in Lua*
114
115usertype destructor options
116+++++++++++++++++++++++++++
117
118If you don't specify anything at all and the type is `destructible`_, then a destructor will be bound to the garbage collection metamethod. Otherwise, the following are special ways to handle the destruction of a usertype:
119
120* ``"__gc", sol::destructor( func )`` or ``sol::meta_function::garbage_collect, sol::destructor( func )``
121	- Creates a custom destructor that takes an argument ``T*`` or ``T&`` and expects it to be destructed/destroyed. Note that lua controls the memory and thusly will deallocate the necessary space AFTER this function returns (e.g., do not call ``delete`` as that will attempt to deallocate memory you did not ``new``)
122	- If you just want the default constructor, you can replace the second argument with ``sol::default_destructor``
123	- The usertype will error / throw if you specify a destructor specifically but do not map it to ``sol::meta_function::gc`` or a string equivalent to ``"__gc"``
124
125.. note::
126
127	You MUST specify ``sol::destructor`` around your destruction function, otherwise it will be ignored.
128
129
130.. _automagical-registration:
131
132usertype automatic meta functions
133+++++++++++++++++++++++++++++++++
134
135If you don't specify a ``sol::meta_function`` name (or equivalent string metamethod name) and the type ``T`` supports certain operations, sol2 will generate the following operations provided it can find a good default implementation:
136
137* for ``to_string`` operations where ``std::ostream& operator<<( std::ostream&, const T& )``, ``obj.to_string()``, or ``to_string( const T& )`` (in the namespace) exists on the C++ type
138	- a ``sol::meta_function::to_string`` operator will be generated
139	- writing is done into either
140		+ a ``std::ostringstream`` before the underlying string is serialized into Lua
141		+ directly serializing the return value of ``obj.to_string()`` or ``to_string( const T& )``
142	- order of preference is the ``std::ostream& operator<<``, then the member function ``obj.to_string()``, then the ADL-lookup based ``to_string( const T& )``
143	- if you need to turn this behavior off for a type (for example, to avoid compiler errors for ADL conflicts), specialize ``sol::is_to_stringable<T>`` for your type to be ``std::false_type``, like so:
144
145.. code-block:: cpp
146
147	namespace sol {
148		template <>
149		struct is_to_stringable<my_type> : std::false_type {};
150	}
151
152
153* for call operations where ``operator()( parameters ... )`` exists on the C++ type
154	- a ``sol::meta_function::call`` operator will be generated
155	- the function call operator in C++ must not be overloaded, otherwise sol will be unable to bind it automagically
156	- the function call operator in C++ must not be templated, otherwise sol will be unable to bind it automagically
157	- if it is overloaded or templated, it is your reponsibility to bind it properly
158* for automatic iteration where ``begin()`` and ``end()`` exist on the C++ type
159	- a ``sol::meta_function::pairs`` operator is generated for you
160	- Allows you to iterate using ``for k, v in pairs( obj ) do ... end`` in Lua
161	- **Lua 5.2 and better only: LuaJIT does not allow this, Lua 5.1 does NOT allow this**
162* for cases where ``.size()`` exists on the C++ type
163	- the length operator of Lua (``#my_obj``) operator is generated for you
164* for comparison operations where ``operator <`` and ``operator <=`` exist on the C++ type
165	- These two ``sol::meta_function::less_than(_or_equal_to)`` are generated for you
166	- ``>`` and ``>=`` operators are generated in Lua based on ``<`` and ``<=`` operators
167* for ``operator==``
168	- An equality operator will always be generated, doing pointer comparison if ``operator==`` on the two value types is not supported or doing a reference comparison and a value comparison if ``operator==`` is supported
169* heterogenous operators cannot be supported for equality, as Lua specifically checks if they use the same function to do the comparison: if they do not, then the equality method is not invoked; one way around this would be to write one ``int super_equality_function(lua_State* L) { ... }``, pull out arguments 1 and 2 from the stack for your type, and check all the types and then invoke ``operator==`` yourself after getting the types out of Lua (possibly using :ref:`sol::stack::get<stack-get>` and :ref:`sol::stack::check_get<stack-check-get>`)
170
171
172
173usertype regular function options
174+++++++++++++++++++++++++++++++++
175
176Otherwise, the following is used to specify functions to bind on the specific usertype for ``T``.
177
178* ``"{name}", &free_function``
179	- Binds a free function / static class function / function object (lambda) to ``"{name}"``. If the first argument is ``T*`` or ``T&``, then it will bind it as a member function. If it is not, it will be bound as a "static" function on the lua table
180* ``"{name}", &type::function_name`` or ``"{name}", &type::member_variable``
181	- Binds a typical member function or variable to ``"{name}"``. In the case of a member variable or member function, ``type`` must be ``T`` or a base of ``T``
182* ``"{name}", sol::readonly( &type::member_variable )``
183	- Binds a typical variable to ``"{name}"``. Similar to the above, but the variable will be read-only, meaning an error will be generated if anything attemps to write to this variable
184* ``"{name}", sol::as_function( &type::member_variable )``
185	- Binds a typical variable to ``"{name}"`` *but forces the syntax to be callable like a function*. This produces a getter and a setter accessible by ``obj:name()`` to get and ``obj:name(value)`` to set.
186* ``"{name}", sol::property( getter_func, setter_func )``
187	- Binds a typical variable to ``"{name}"``, but gets and sets using the specified setter and getter functions. Not that if you do not pass a setter function, the variable will be read-only. Also not that if you do not pass a getter function, it will be write-only
188* ``"{name}", sol::var( some_value )`` or ``"{name}", sol::var( std::ref( some_value ) )``
189	- Binds a typical variable to ``"{name}"``, optionally by reference (e.g., refers to the same memory in C++). This is useful for global variables / static class variables and the like
190* ``"{name}", sol::overload( Func1, Func2, ... )``
191	- Creates an oveloaded member function that discriminates on number of arguments and types
192	- Dumping multiple functions out with the same name **does not make an overload**: you must use **this syntax** in order for it to work
193* ``sol::base_classes, sol::bases<Bases...>``
194	- Tells a usertype what its base classes are. You need this to have derived-to-base conversions work properly. See :ref:`inheritance<usertype-inheritance>`
195
196
197runtime functions
198-----------------
199
200You can add functions at runtime **to the whole class** (not to individual objects). Set a name under the metatable name you bound using ``new_usertype`` to an object. For example:
201
202.. literalinclude:: ../../../examples/docs/runtime_extension.cpp
203	:caption: runtime_extension.cpp
204	:name: runtime-extension-example
205	:linenos:
206
207.. note::
208
209	You cannot add functions to an individual object. You can only add functions to the whole class / usertype.
210
211
212overloading
213-----------
214
215Functions set on a usertype support overloading. See :doc:`here<overload>` for an example.
216
217
218.. _usertype-inheritance:
219
220inheritance
221-----------
222
223Sol can adjust pointers from derived classes to base classes at runtime, but it has some caveats based on what you compile with:
224
225If your class has no complicated™ virtual inheritance or multiple inheritance, than you can try to sneak away with a performance boost from not specifying any base classes and doing any casting checks. (What does "complicated™" mean? Ask your compiler's documentation, if you're in that deep.)
226
227For the rest of us safe individuals out there: You must specify the ``sol::base_classes`` tag with the ``sol::bases<Types...>()`` argument, where ``Types...`` are all the base classes of the single type ``T`` that you are making a usertype out of.
228
229Register the base classes explicitly.
230
231.. note::
232
233	Always specify your bases if you plan to retrieve a base class using the Sol abstraction directly and not casting yourself.
234
235.. literalinclude:: ../../../examples/docs/inheritance.cpp
236	:caption: inheritance.cpp
237	:name: inheritance-example
238	:linenos:
239	:emphasize-lines: 23
240
241.. note::
242
243	You must list ALL base classes, including (if there were any) the base classes of A, and the base classes of those base classes, etc. if you want Sol/Lua to handle them automagically.
244
245.. note::
246
247	Sol does not support down-casting from a base class to a derived class at runtime.
248
249.. warning::
250
251	Specify all base class member variables and member functions to avoid current implementation caveats regarding automatic base member lookup. Sol currently attempts to link base class methods and variables with their derived classes with an undocumented, unsupported feature, provided you specify ``sol::bases<...>``. Unfortunately, this can come at the cost of performance, depending on how "far" the base is from the derived class in the bases lookup list. If you do not want to suffer the performance degradation while we iron out the kinks in the implementation (and want it to stay performant forever), please specify all the base methods on the derived class in the method listing you write. In the future, we hope that with reflection we will not have to worry about this.
252
253.. _automagical:
254
255automagical usertypes
256---------------------
257
258Usertypes automatically register special functions, whether or not they're bound using `new_usertype`. You can turn this off by specializing the ``sol::is_automagical<T>`` template trait:
259
260.. code-block:: cpp
261
262	struct my_strange_nonconfirming_type { /* ... */ };
263
264	namespace sol {
265		template <>
266		struct is_automagical<my_strange_nonconforming_type> : std::false_type {};
267	}
268
269inheritance + overloading
270-------------------------
271
272While overloading is supported regardless of inheritance caveats or not, the current version of Sol has a first-match, first-call style of overloading when it comes to inheritance. Put the functions with the most derived arguments first to get the kind of matching you expect or cast inside of an intermediary C++ function and call the function you desire.
273
274compilation speed
275-----------------
276
277.. note::
278
279	MSVC and clang/gcc may need additional compiler flags to handle compiling extensive use of usertypes. See: :ref:`the error documentation<compilation_errors_warnings>` for more details.
280
281performance note
282----------------
283
284.. note::
285
286	Note that performance for member function calls goes down by a fixed overhead if you also bind variables as well as member functions. This is purely a limitation of the Lua implementation and there is, unfortunately, nothing that can be done about it. If you bind only functions and no variables, however, Sol will automatically optimize the Lua runtime and give you the maximum performance possible. *Please consider ease of use and maintenance of code before you make everything into functions.*
287
288.. _destructible: http://en.cppreference.com/w/cpp/types/is_destructible
289.. _default_constructible: http://en.cppreference.com/w/cpp/types/is_constructible
290.. _small starter example here: https://github.com/ThePhD/sol2/blob/develop/examples/usertype_basics.cpp
291.. _runtime extensible: https://github.com/ThePhD/sol2/blob/develop/examples/usertype_advanced.cpp#L81
292.. _the metamethods in the Lua manual: https://www.lua.org/manual/5.3/manual.html#2.4
293