1usertype<T>
2===========
3structures and classes from C++ made available to Lua code
4----------------------------------------------------------
5
6*Note: ``T`` refers to the type being turned into a usertype.*
7
8While 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. These use metatables and userdata in lua for their implementation. If you need a usertype that is also extensible at runtime and has less compiler crunch to it, try the :doc:`simple version of this after reading these docs<simple_usertype>` Given this C++ class:
9
10.. code-block:: cpp
11	:linenos:
12
13	struct ship {
14		int bullets = 20;
15		int life = 100;
16
17		bool shoot () {
18			if (bullets > 0) {
19				--bullets;
20				// successfully shot
21				return true;
22			}
23			// cannot shoot
24			return false;
25		}
26
27		bool hurt (int by) {
28			life -= by;
29			// have we died?
30			return life < 1;
31		}
32	};
33
34You can bind the it to Lua using the following C++ code:
35
36.. code-block:: cpp
37	:linenos:
38
39	sol::state lua;
40
41	lua.new_usertype<ship>( "ship", // the name of the class, as you want it to be used in lua
42		// List the member functions you wish to bind:
43		// "name_of_item", &class_name::function_or_variable
44		"shoot", &ship::shoot,
45		"hurt", &ship::hurt,
46		// bind variable types, too
47		"life", &ship::bullets
48		// names in lua don't have to be the same as C++,
49		// but it probably helps if they're kept the same,
50		// here we change it just to show its possible
51		"bullet_count", &ship::bullets
52	);
53
54
55Equivalently, you can also write:
56
57.. code-block:: cpp
58	:linenos:
59	:emphasize-lines: 4,12
60
61	sol::state lua;
62
63	// Use constructor directly
64	usertype<ship> shiptype(
65		"shoot", &ship::shoot,
66		"hurt", &ship::hurt,
67		"life", &ship::bullets
68		"bullet_count", &ship::bullets
69	);
70
71	// set usertype explicitly, with the given name
72	lua.set_usertype<ship>( "ship", shiptype );
73
74	// shiptype is now a useless skeleton type, just let it destruct naturally and don't use it again.
75
76
77Note that here, because the C++ class is default-constructible, it will automatically generate a creation function that can be called in lua called "new" that takes no arguments. You can use it like this in lua code:
78
79.. code-block:: lua
80	:linenos:
81
82	fwoosh = ship.new()
83	-- note the ":" that is there: this is mandatory for member function calls
84	-- ":" means "pass self" in Lua
85	local success = fwoosh:shoot()
86	local is_dead = fwoosh:hurt(20)
87	-- check if it works
88	print(is_dead) -- the ship is not dead at this point
89	print(fwoosh.life .. "life left") -- 80 life left
90	print(fwoosh.bullet_count) -- 19
91
92
93There 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).
94
95enumerations
96------------
97
98.. _meta_function_enum:
99
100.. code-block:: cpp
101	:caption: meta_function enumeration for names
102	:linenos:
103
104	enum class meta_function {
105		construct,
106		index,
107		new_index,
108		mode,
109		call,
110		metatable,
111		to_string,
112		length,
113		unary_minus,
114		addition,
115		subtraction,
116		multiplication,
117		division,
118		modulus,
119		power_of,
120		involution = power_of,
121		concatenation,
122		equal_to,
123		less_than,
124		less_than_or_equal_to,
125		garbage_collect,
126		call_function,
127	};
128
129
130Use 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.
131
132members
133-------
134
135.. code-block:: cpp
136	:caption: function: usertype<T> constructor
137	:name: usertype-constructor
138
139	template<typename... Args>
140	usertype<T>(Args&&... args);
141
142
143The 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.
144
145
146usertype constructor options
147++++++++++++++++++++++++++++
148
149If 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:
150
151..  _constructor:
152
153* ``"{name}", constructors<Type-List-0, Type-List-1, ...>``
154	- ``Type-List-N`` must be a ``sol::types<Args...>``, where ``Args...`` is a list of types that a constructor takes. Supports overloading by default
155	- If you pass the ``constructors<...>`` argument first when constructing the usertype, then it will automatically be given a ``"{name}"`` of ``"new"``
156* ``"{name}", sol::initializers( func1, func2, ... )``
157	- 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)
158	- Given one or more functions, provides an overloaded Lua function for creating a the specified type
159		+ 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
160* ``{anything}, sol::factories( func1, func2, ... )``
161	- 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
162	- Given one or more functions, provides an overloaded function for invoking
163		+ 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.
164		+ 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
165		+ If this is not sufficient, see next 2 entries on how to specifically block a constructor
166* ``{anything}, sol::no_constructor``
167	- Specifically tells Sol not to create a ``.new()`` if one is not specified and the type is default-constructible
168	- ``{anything}`` should probably be ``"new"``, which will specifically block its creation and give a proper warning if someone calls ``new`` (otherwise it will just give a nil value error)
169	- *Combine with the next one to only allow a factory function for your function type*
170* ``{anything}, {some_factory_function}``
171	- Essentially binds whatever the function is to name ``{anything}``
172	- When used WITH the ``sol::no_constructor`` option above (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
173* ``sol::call_constructor, {valid constructor / initializer / factory}``
174	- 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
175	- 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``
176	- 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.
177
178usertype destructor options
179+++++++++++++++++++++++++++
180
181If 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:
182
183* ``"__gc", sol::destructor( func )`` or ``sol::meta_function::garbage_collect, sol::destructor( func )``
184	- 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``)
185	- If you just want the default constructor, you can replace the second argument with ``sol::default_destructor``
186	- 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"``
187
188usertype regular function options
189+++++++++++++++++++++++++++++++++
190
191If you don't specify anything at all and the type ``T`` supports ``operator <``, ``operator <=``, or ``operator==`` (``const`` or non-``const`` qualified):
192
193* for ``operator <`` and ``operator <=``
194	- These two ``sol::meta_function::less_than(_or_equal_to)`` are generated for you and overriden in Lua.
195* for ``operator==``
196	- 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
197* 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>`)
198
199Otherwise, the following is used to specify functions to bind on the specific usertype for ``T``.
200
201* ``"{name}", &free_function``
202	- 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
203* ``"{name}", &type::function_name`` or ``"{name}", &type::member_variable``
204	- 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``
205* ``"{name}", sol::readonly( &type::member_variable )``
206	- 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
207* ``"{name}", sol::as_function( &type::member_variable )``
208	- 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.
209* ``"{name}", sol::property( getter_func, setter_func )``
210	- 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
211* ``"{name}", sol::var( some_value )`` or ``"{name}", sol::var( std::ref( some_value ) )``
212	- 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
213* ``"{name}", sol::overloaded( Func1, Func2, ... )``
214	- Creates an oveloaded member function that discriminates on number of arguments and types.
215* ``sol::base_classes, sol::bases<Bases...>``
216	- Tells a usertype what its base classes are. You need this to have derived-to-base conversions work properly. See :ref:`inheritance<usertype-inheritance>`
217
218
219usertype arguments - simple usertype
220++++++++++++++++++++++++++++++++++++
221
222* ``sol::simple``
223	- Only allowed as the first argument to the usertype constructor, must be accompanied by a ``lua_State*``
224	- This tag triggers the :doc:`simple usertype<simple_usertype>` changes / optimizations
225	- Only supported when directly invoking the constructor (e.g. not when calling ``sol::table::new_usertype`` or ``sol::table::new_simple_usertype``)
226	- Should probably not be used directly. Use ``sol::table::new_usertype`` or ``sol::table::new_simple_usertype`` instead
227
228
229
230overloading
231-----------
232
233Functions set on a usertype support overloading. See :doc:`here<overload>` for an example.
234
235
236.. _usertype-inheritance:
237
238inheritance
239-----------
240
241Sol can adjust pointers from derived classes to base classes at runtime, but it has some caveats based on what you compile with:
242
243If 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.)
244
245For 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.
246
247.. note::
248
249	Always specify your bases if you plan to retrieve a base class using the Sol abstraction directly and not casting yourself.
250
251.. code-block:: cpp
252	:linenos:
253
254	struct A {
255		int a = 10;
256		virtual int call() { return 0; }
257	};
258	struct B : A {
259		int b = 11;
260		virtual int call() override { return 20; }
261	};
262
263Then, to register the base classes explicitly:
264
265.. code-block:: cpp
266	:linenos:
267	:emphasize-lines: 5
268
269	sol::state lua;
270
271	lua.new_usertype<B>( "B",
272		"call", &B::call,
273		sol::base_classes, sol::bases<A>()
274	);
275
276.. note::
277
278	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.
279
280.. note::
281
282	Sol does not support down-casting from a base class to a derived class at runtime.
283
284.. warning::
285
286	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::base_classes<...>``. 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.
287
288
289inheritance + overloading
290-------------------------
291
292While 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.
293
294traits
295------
296
297.. code-block:: cpp
298	:caption: usertype_traits<T>
299	:name: usertype-traits
300
301	template<typename T>
302	struct usertype_traits {
303		static const std::string name;
304		static const std::string metatable;
305		static const std::string variable_metatable;
306		static const std::string gc_table;
307	};
308
309
310This trait is used to provide names for the various metatables and global tables used to perform cleanup and lookup. They are automagically generated at runtime. Sol attempts to parse the output of ``__PRETTY_FUCNTION__`` (``g++``/``clang++``) or ``_FUNCDSIG`` (``vc++``) to get the proper type name. If you have a special need you can override the names for your specific type. If you notice a bug in a class name when you don't manually specify it during setting a usertype, feel free to open an issue request or send an e-mail!
311
312
313compilation speed
314-----------------
315
316.. note::
317
318	If you find that compilation times are too long and you're only binding member functions, consider perhaps using :doc:`simple usertypes<simple_usertype>`. This can reduce compile times (but may cost memory size and speed). See the simple usertypes documentation for more details.
319
320
321performance note
322----------------
323
324.. note::
325
326	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.*
327
328
329.. _destructible: http://en.cppreference.com/w/cpp/types/is_destructible
330.. _default_constructible: http://en.cppreference.com/w/cpp/types/is_constructible