fixed some bugs
[luabind.git] / doc / docs.html
blob66ddacc00c70079bfe33a736b49d4f666ea8a337
1 <?xml version="1.0" encoding="utf-8" ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
4 <head>
5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6 <meta name="generator" content="Docutils 0.3.1: http://docutils.sourceforge.net/" />
7 <title>luabind</title>
8 <link rel="stylesheet" href="style.css" type="text/css" />
9 </head>
10 <body>
11 <div class="document" id="luabind">
12 <h1 class="title">luabind</h1>
13 <p>Note: This library is currently in public beta phase. This documentation
14 should be considered beta as well. Please report any grammatical
15 corrections/spelling corrections.</p>
16 <div class="contents topic" id="contents">
17 <p class="topic-title"><a name="contents">Contents</a></p>
18 <ul class="auto-toc simple">
19 <li><a class="reference" href="#introduction" id="id1" name="id1">1   Introduction</a></li>
20 <li><a class="reference" href="#features" id="id2" name="id2">2   Features</a></li>
21 <li><a class="reference" href="#portability" id="id3" name="id3">3   Portability</a></li>
22 <li><a class="reference" href="#building-luabind" id="id4" name="id4">4   Building luabind</a></li>
23 <li><a class="reference" href="#basic-usage" id="id5" name="id5">5   Basic usage</a><ul class="auto-toc">
24 <li><a class="reference" href="#hello-world" id="id6" name="id6">5.1   Hello world</a></li>
25 </ul>
26 </li>
27 <li><a class="reference" href="#scopes" id="id7" name="id7">6   Scopes</a></li>
28 <li><a class="reference" href="#binding-functions-to-lua" id="id8" name="id8">7   Binding functions to lua</a><ul class="auto-toc">
29 <li><a class="reference" href="#overloaded-functions" id="id9" name="id9">7.1   Overloaded functions</a></li>
30 <li><a class="reference" href="#signature-matching" id="id10" name="id10">7.2   Signature matching</a></li>
31 <li><a class="reference" href="#calling-lua-functions" id="id11" name="id11">7.3   Calling lua functions</a></li>
32 <li><a class="reference" href="#using-lua-threads" id="id12" name="id12">7.4   Using lua threads</a></li>
33 </ul>
34 </li>
35 <li><a class="reference" href="#binding-classes-to-lua" id="id13" name="id13">8   Binding classes to lua</a><ul class="auto-toc">
36 <li><a class="reference" href="#properties" id="id14" name="id14">8.1   Properties</a></li>
37 <li><a class="reference" href="#enums" id="id15" name="id15">8.2   Enums</a></li>
38 <li><a class="reference" href="#operators" id="id16" name="id16">8.3   Operators</a></li>
39 <li><a class="reference" href="#nested-scopes-and-static-functions" id="id17" name="id17">8.4   Nested scopes and static functions</a></li>
40 <li><a class="reference" href="#derived-classes" id="id18" name="id18">8.5   Derived classes</a></li>
41 <li><a class="reference" href="#smart-pointers" id="id19" name="id19">8.6   Smart pointers</a></li>
42 </ul>
43 </li>
44 <li><a class="reference" href="#object" id="id20" name="id20">9   Object</a><ul class="auto-toc">
45 <li><a class="reference" href="#iterators" id="id21" name="id21">9.1   Iterators</a></li>
46 <li><a class="reference" href="#related-functions" id="id22" name="id22">9.2   Related functions</a></li>
47 <li><a class="reference" href="#functor" id="id23" name="id23">9.3   Functor</a></li>
48 </ul>
49 </li>
50 <li><a class="reference" href="#defining-classes-in-lua" id="id24" name="id24">10   Defining classes in lua</a><ul class="auto-toc">
51 <li><a class="reference" href="#deriving-in-lua" id="id25" name="id25">10.1   Deriving in lua</a></li>
52 <li><a class="reference" href="#overloading-operators" id="id26" name="id26">10.2   Overloading operators</a></li>
53 <li><a class="reference" href="#finalizers" id="id27" name="id27">10.3   Finalizers</a></li>
54 </ul>
55 </li>
56 <li><a class="reference" href="#exceptions" id="id28" name="id28">11   Exceptions</a></li>
57 <li><a class="reference" href="#policies" id="id29" name="id29">12   Policies</a><ul class="auto-toc">
58 <li><a class="reference" href="#copy" id="id30" name="id30">12.1   Copy</a></li>
59 <li><a class="reference" href="#adopt" id="id31" name="id31">12.2   Adopt</a></li>
60 <li><a class="reference" href="#dependency" id="id32" name="id32">12.3   Dependency</a></li>
61 <li><a class="reference" href="#return-reference-to" id="id33" name="id33">12.4   Return reference to</a></li>
62 <li><a class="reference" href="#out-value" id="id34" name="id34">12.5   Out value</a></li>
63 <li><a class="reference" href="#pure-out-value" id="id35" name="id35">12.6   Pure out value</a></li>
64 <li><a class="reference" href="#discard-result" id="id36" name="id36">12.7   Discard result</a></li>
65 <li><a class="reference" href="#return-stl-iterator" id="id37" name="id37">12.8   Return STL iterator</a></li>
66 <li><a class="reference" href="#yield" id="id38" name="id38">12.9   Yield</a></li>
67 </ul>
68 </li>
69 <li><a class="reference" href="#splitting-up-the-registration" id="id39" name="id39">13   Splitting up the registration</a></li>
70 <li><a class="reference" href="#configuration" id="id40" name="id40">14   Configuration</a></li>
71 <li><a class="reference" href="#implementation-notes" id="id41" name="id41">15   Implementation notes</a></li>
72 <li><a class="reference" href="#error-messages" id="id42" name="id42">16   Error messages</a></li>
73 <li><a class="reference" href="#faq" id="id43" name="id43">17   FAQ</a></li>
74 <li><a class="reference" href="#known-issues" id="id44" name="id44">18   Known issues</a></li>
75 <li><a class="reference" href="#acknowledgments" id="id45" name="id45">19   Acknowledgments</a></li>
76 </ul>
77 </div>
78 <div class="section" id="introduction">
79 <h1><a class="toc-backref" href="#id1" name="introduction">1   Introduction</a></h1>
80 <p>Luabind is a library that helps you create bindings between C++ and lua. It has
81 the ability to expose functions and classes, written in C++, to lua. It will
82 also supply the functionality to define classes in lua and let them derive from
83 other lua classes or C++ classes. Lua classes can override virtual functions
84 from their C++ base classes. It is written towards lua 5.0, and does not work
85 with lua 4.</p>
86 <p>It is implemented utilizing template meta programming. That means that you
87 don't need an extra preprocess pass to compile your project (it is done by the
88 compiler). It also means you don't (usually) have to know the exact signatureof
89 each function you register, since the library will generate code depending on
90 the compile-time type of the function (which includes the signature). The main
91 drawback of this approach is that the compilation time will increase for the
92 file that does the registration, it is therefore recommended that you register
93 everything in the same cpp-file.</p>
94 <p>luabind is released under the terms of the <a class="reference" href="http://www.opensource.org/licenses/mit-license.php">MIT license</a>.</p>
95 <p>We are very interested in hearing about projects that use luabind, please let
96 us know about your project.</p>
97 </div>
98 <div class="section" id="features">
99 <h1><a class="toc-backref" href="#id2" name="features">2   Features</a></h1>
100 <p>Luabind supports:</p>
101 <blockquote>
102 <ul class="simple">
103 <li>Overloaded free functions</li>
104 <li>C++ classes in lua</li>
105 <li>Overloaded member functions</li>
106 <li>Operators</li>
107 <li>Properties</li>
108 <li>Enums</li>
109 <li>Lua functions in C++</li>
110 <li>Lua classes in C++</li>
111 <li>Lua classes (single inheritance)</li>
112 <li>Derives from lua or C++ classes</li>
113 <li>O verride virtual functions from C++ classes</li>
114 <li>Implicit casts between registered types</li>
115 <li>Best match signature matching</li>
116 <li>Return value policies and parameter policies</li>
117 </ul>
118 </blockquote>
119 </div>
120 <div class="section" id="portability">
121 <h1><a class="toc-backref" href="#id3" name="portability">3   Portability</a></h1>
122 <p>Luabind has been tested to work on the following compilers:</p>
123 <blockquote>
124 <ul class="simple">
125 <li>Visual Studio 7.1</li>
126 <li>Visual Studio 7.0</li>
127 <li>Visual Studio 6.0 (sp 5)</li>
128 <li>Intel C++ 6.0 (Windows)</li>
129 <li>GCC 2.95.3 (cygwin)</li>
130 <li>GCC 3.0.4 (Debian/Linux)</li>
131 <li>GCC 3.1 (SunOS 5.8)</li>
132 <li>GCC 3.2 (cygwin)</li>
133 <li>GCC 3.3.1 (cygwin)</li>
134 </ul>
135 </blockquote>
136 <p>It has been confirmed not to work with:</p>
137 <blockquote>
138 <ul class="simple">
139 <li>GCC 2.95.2 (SunOS 5.8)</li>
140 </ul>
141 </blockquote>
142 <p>Metrowerks 8.3 (Windows) compiles but fails the const-test. This
143 means that const member functions are treated as non-const member
144 functions.</p>
145 <p>If you have tried luabind with a compiler not listed here, let us know
146 your result with it.</p>
147 </div>
148 <div class="section" id="building-luabind">
149 <h1><a class="toc-backref" href="#id4" name="building-luabind">4   Building luabind</a></h1>
150 <p>To keep down the compilation-time luabind is built as a library. This means you
151 have to either build it and lika against it, or include its source files in
152 your project. You also have to make sure the luabind directory is somewhere in
153 your compiler's include path. It requires <a class="reference" href="http://www.boost.org">Boost</a> 1.31.0 to be installed (only
154 boost headers). It also requires that lua is installed.</p>
155 <p>The official way of building luabind is with <a class="reference" href="http://www.boost.org/tools/build/v2/index_v2.html">Boost.Build V2</a>. To properly build
156 luabind with Boost.Build you need to set two environment variables:</p>
157 <dl>
158 <dt>BOOST_ROOT</dt>
159 <dd>Point this to your Boost installation.</dd>
160 <dt>LUA_PATH</dt>
161 <dd>Point this to your lua directory. The build system will assume that the
162 include and library files are located in <tt class="literal"><span class="pre">$(LUA_PATH)/include/</span></tt> and
163 <tt class="literal"><span class="pre">$(LUA_PATH)/lib/.</span></tt></dd>
164 </dl>
165 <p>For backward compatibility, there is also a makefile in the root-directory that
166 will build the library and the test program. If you are using a UNIX-system (or
167 cygwin) they will make it easy to build luabind as a static library. If you are
168 using Visual Studio it may be easier to include the files in the src directory
169 in your project.</p>
170 <p>When building luabind you have several options that may streamline the library
171 to better suit your needs. It is extremely important that your application has
172 the same settings as the library was built with. The available options are
173 found in the <a class="reference" href="#configuration">Configuration</a> section.</p>
174 <p>If you want to change the settings to differ from the default, it's recommended
175 that you define the settings on the commandline of all your files (in the
176 project settings in visual studio).</p>
177 </div>
178 <div class="section" id="basic-usage">
179 <h1><a class="toc-backref" href="#id5" name="basic-usage">5   Basic usage</a></h1>
180 <p>To use luabind, you must include <tt class="literal"><span class="pre">lua.h</span></tt> and luabind's main header file:</p>
181 <pre class="literal-block">
182 extern &quot;C&quot;
184 #include &quot;lua.h&quot;
187 #include &lt;luabind/luabind.hpp&gt;
188 </pre>
189 <p>This includes support for both registering classes and functions. If you just
190 want to have support for functions or classes you can include
191 <tt class="literal"><span class="pre">luabind/function.hpp</span></tt> and <tt class="literal"><span class="pre">luabind/class.hpp</span></tt> separately:</p>
192 <pre class="literal-block">
193 #include &lt;luabind/function.hpp&gt;
194 #include &lt;luabind/class.hpp&gt;
195 </pre>
196 <p>The first thing you need to do is to call <tt class="literal"><span class="pre">luabind::open(lua_State*)</span></tt> which
197 will register the functions to create classes from lua, and initialize some
198 state-global structures used by luabind. If you don't call this function you
199 will hit asserts later in the library. There is no corresponding close function
200 because once a class has been registered in lua, there really isn't any good
201 way to remove it. Partly because any remaining instances of that class relies
202 on the class being there. Everything will be cleaned up when the state is
203 closed though.</p>
204 <!-- Isn't this wrong? Don't we include lua.h using lua_include.hpp ? -->
205 <p>Note that no luabind header will include <tt class="literal"><span class="pre">lua.h</span></tt>, this is up to you. You have
206 to include it before any luabind header is included.</p>
207 <div class="section" id="hello-world">
208 <h2><a class="toc-backref" href="#id6" name="hello-world">5.1   Hello world</a></h2>
209 <pre class="literal-block">
210 #include &lt;iostream&gt;
211 #include &lt;luabind/luabind.hpp&gt;
213 void greet()
215 std::cout &lt;&lt; &quot;hello world!\n&quot;;
218 extern &quot;C&quot; int init(lua_State* L)
220 using namespace luabind;
222 open(L);
224 module(L)
226 def(&quot;greet&quot;, &amp;greet)
229 return 0;
231 </pre>
232 <pre class="literal-block">
233 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
234 &gt; loadlib('hello_world.dll', 'init')()
235 &gt; greet()
236 Hello world!
237 &gt;
238 </pre>
239 </div>
240 </div>
241 <div class="section" id="scopes">
242 <h1><a class="toc-backref" href="#id7" name="scopes">6   Scopes</a></h1>
243 <p>Everything that gets registered in lua is registered in a namespace (lua
244 tables) or in the global scope (called module). All registrations must be
245 surrounded by its scope. To define a module, the <tt class="literal"><span class="pre">luabind::module</span></tt> class is
246 used. It is used like this:</p>
247 <pre class="literal-block">
248 module(L)
250 // declarations
252 </pre>
253 <p>This will register all declared functions or classes in the global namespace in
254 lua. If you want to have a namespace for your module (like the standard
255 libraries) you can give a name to the constructor, like this:</p>
256 <pre class="literal-block">
257 module(L, &quot;my_library&quot;)
259 // declarations
261 </pre>
262 <p>Here all declarations will be put in the my_library table.</p>
263 <p>If you want nested namespaces you can use the <tt class="literal"><span class="pre">luabind::namespace_</span></tt> class. It
264 works exactly as <tt class="literal"><span class="pre">luabind::module</span></tt> except that it doesn't take a lua_State*
265 in it's constructor. An example of its usage could look like this:</p>
266 <pre class="literal-block">
267 module(L, &quot;my_library&quot;)
269 // declarations
271 namespace_(&quot;detail&quot;)
273 // library-private declarations
276 </pre>
277 <p>As you might have figured out, the following declarations are equivalent:</p>
278 <pre class="literal-block">
279 module(L)
281 namespace_(&quot;my_library&quot;)
283 // declarations
287 </pre>
288 <pre class="literal-block">
289 module(L, &quot;my_library&quot;)
291 // declarations
293 </pre>
294 <p>Each declaration must be separated by a comma, like this:</p>
295 <pre class="literal-block">
296 module(L)
298 def(&quot;f&quot;, &amp;f),
299 def(&quot;g&quot;, &amp;g),
300 class_&lt;A&gt;(&quot;A&quot;)
301 .def(constructor&lt;int, int&gt;),
302 def(&quot;h&quot;, &amp;h)
304 </pre>
305 <p>More about the actual declarations in the <a class="reference" href="#binding-functions-to-lua">Binding functions to lua</a> and
306 <a class="reference" href="#binding-classes-to-lua">Binding classes to lua</a> sections.</p>
307 <p>A word of caution, if you are in really bad need for performance, putting your
308 functions in tables will increase the lookup time.</p>
309 </div>
310 <div class="section" id="binding-functions-to-lua">
311 <h1><a class="toc-backref" href="#id8" name="binding-functions-to-lua">7   Binding functions to lua</a></h1>
312 <p>To bind functions to lua you use the function <tt class="literal"><span class="pre">luabind::def()</span></tt>. It has the
313 following synopsis:</p>
314 <pre class="literal-block">
315 template&lt;class F, class policies&gt;
316 void def(const char* name, F f, const Policies&amp;);
317 </pre>
318 <ul class="simple">
319 <li>name is the name the function will have within lua.</li>
320 <li>F is the function pointer you want to register.</li>
321 <li>The Policies parameter is used to describe how parameters and return values
322 are treated by the function, this is an optional parameter. More on this in
323 the <a class="reference" href="#policies">policies</a> section.</li>
324 </ul>
325 <p>An example usage could be if you want to register the function <tt class="literal"><span class="pre">float</span>
326 <span class="pre">std::sin(float)</span></tt>:</p>
327 <pre class="literal-block">
328 module(L)
330 def(&quot;sin&quot;, &amp;std::sin)
332 </pre>
333 <div class="section" id="overloaded-functions">
334 <h2><a class="toc-backref" href="#id9" name="overloaded-functions">7.1   Overloaded functions</a></h2>
335 <p>If you have more than one function with the same name, and want to register
336 them in lua, you have to explicitly give the signature. This is to let C++ know
337 which function you refer to. For example, if you have two functions, <tt class="literal"><span class="pre">int</span>
338 <span class="pre">f(const</span> <span class="pre">char*)</span></tt> and <tt class="literal"><span class="pre">void</span> <span class="pre">f(int)</span></tt>.</p>
339 <pre class="literal-block">
340 module(L)
342 def(&quot;f&quot;, (int(*)(const char*)) &amp;f),
343 def(&quot;f&quot;, (void(*)(int)) &amp;f)
345 </pre>
346 </div>
347 <div class="section" id="signature-matching">
348 <h2><a class="toc-backref" href="#id10" name="signature-matching">7.2   Signature matching</a></h2>
349 <p>luabind will generate code that checks the lua stack to see if the values there
350 can match your functions' signatures. It will handle implicit typecasts between
351 derived classes, and it will prefer matches with the least number of implicit
352 casts. In a function call, if the function is overloaded and there's no
353 overload that match the parameters better than the other, you have an
354 ambiguity. This will spawn a run-time error, stating that the function call is
355 ambiguous. A simple example of this is to register one function that takes an
356 int and one that takes a float. Since lua don't distinguish between floats and
357 integers, both will always match.</p>
358 <p>Since all overloads are tested, it will always find the best match (not the
359 first match). This also means that it can handle situations where the only
360 difference in the signature is that one member function is const and the other
361 isn't.</p>
362 <div class="sidebar">
363 <p class="sidebar-title">Ownership transfer</p>
364 <p>To correctly handle ownership transfer, create_a() would need an adopt
365 return value policy. More on this in the <a class="reference" href="#policies">Policies</a> section.</p>
366 </div>
367 <p>For example, if the following function and class is registered:</p>
368 <pre class="literal-block">
369 struct A
371 void f();
372 void f() const;
375 const A* create_a();
377 struct B: A {};
378 struct C: B {};
380 void g(A*);
381 void g(B*);
382 </pre>
383 <p>And the following lua code is executed:</p>
384 <pre class="literal-block">
385 a1 = create_a()
386 a1:f() -- the const version is called
388 a2 = A()
389 a2:f() -- the non-const version is called
391 a = A()
392 b = B()
393 c = C()
395 g(a) -- calls g(A*)
396 g(b) -- calls g(B*)
397 g(c) -- calls g(B*)
398 </pre>
399 </div>
400 <div class="section" id="calling-lua-functions">
401 <h2><a class="toc-backref" href="#id11" name="calling-lua-functions">7.3   Calling lua functions</a></h2>
402 <p>To call a lua function, you can either use <tt class="literal"><span class="pre">call_function()</span></tt>,
403 <tt class="literal"><span class="pre">call_member()</span></tt>, an <tt class="literal"><span class="pre">object</span></tt> or <tt class="literal"><span class="pre">functor</span></tt>.</p>
404 <pre class="literal-block">
405 template&lt;class Ret&gt;
406 Ret call_function(lua_State* L, const char* name, ...)
407 </pre>
408 <p>This calls the global function called name. This function can only call global
409 lua functions. The ... represents a variable number of parameters that are sent
410 to the lua function. This function call may throw <tt class="literal"><span class="pre">luabind::error</span></tt> if the
411 function call fails.</p>
412 <p>The return value isn't actually Ret (the template parameter), but a proxy
413 object that will do the function call. This enables you to give policies to the
414 call. You do this with the operator[]. You give the policies within the
415 brackets, like this:</p>
416 <pre class="literal-block">
417 int ret = call_function&lt;int&gt;(
419 , &quot;a_lua_function&quot;
420 , new complex_class()
421 )[ adopt(_1) ];
422 </pre>
423 <pre class="literal-block">
424 template&lt;class Ret&gt;
425 Ret call_member(object&amp;, const char* name, ...)
426 </pre>
427 <p>This treats the given object as an instance of a class. The given name is the
428 name of a member function to call. The ... represents a variable number of
429 parameters given to the function. This function may throw <tt class="literal"><span class="pre">luabind::error</span></tt> if
430 the function call fails.</p>
431 <p>You can give policies to a member function call the same way as you do with
432 <tt class="literal"><span class="pre">call_function</span></tt>.</p>
433 </div>
434 <div class="section" id="using-lua-threads">
435 <h2><a class="toc-backref" href="#id12" name="using-lua-threads">7.4   Using lua threads</a></h2>
436 <p>To start a lua thread, you have to call <tt class="literal"><span class="pre">lua_resume()</span></tt>, this means that you
437 cannot use the previous function <tt class="literal"><span class="pre">call_function()</span></tt> to start a thread. You have
438 to use</p>
439 <pre class="literal-block">
440 template&lt;class Ret&gt;
441 Ret resume_function(lua_State* L, const char* name, ...)
442 </pre>
443 <p>and</p>
444 <pre class="literal-block">
445 template&lt;class Ret&gt;
446 Ret resume(lua_State* L, ...)
447 </pre>
448 <p>The first time you start the thread, you have to give it a function to execute. i.e. you
449 have to use <tt class="literal"><span class="pre">resume_function</span></tt>, when the lua function yeilds, it will return the first
450 value passed in to <tt class="literal"><span class="pre">lua_yield()</span></tt>. When you want to continue the execution, you just call
451 <tt class="literal"><span class="pre">resume()</span></tt> on your <tt class="literal"><span class="pre">lua_State</span></tt>, since it's already executing a function, you don't pass
452 it one. The parameters to <tt class="literal"><span class="pre">resume()</span></tt> will be returned by <tt class="literal"><span class="pre">yield()</span></tt> on the lua side.</p>
453 <p>For yielding C++-functions (without the support of passing data back and forth between the
454 lua side and the c++ side), you can use the <a class="reference" href="#yield">Yield</a> policy.</p>
455 </div>
456 </div>
457 <div class="section" id="binding-classes-to-lua">
458 <h1><a class="toc-backref" href="#id13" name="binding-classes-to-lua">8   Binding classes to lua</a></h1>
459 <p>To register classes you use a class called <tt class="literal"><span class="pre">class_</span></tt>. Its name is supposed to
460 resemble the C++ keyword, to make it look more intuitive. It has an overloaded
461 member function <tt class="literal"><span class="pre">def()</span></tt> that is used to register member functions, operators,
462 constructors, enums and properties on the class. It will return its
463 this-pointer, to let you register more members directly.</p>
464 <p>Let's start with a simple example. Consider the following C++ class:</p>
465 <pre class="literal-block">
466 class testclass
468 public:
469 testclass(const std::string&amp; s): m_string(s) {}
470 void print_string() { std::cout &lt;&lt; m_string &lt;&lt; &quot;\n&quot;; }
472 private:
473 std::string m_string;
475 </pre>
476 <p>To register it with a lua environment, write as follows (assuming you are using
477 namespace luabind):</p>
478 <pre class="literal-block">
479 module(L)
481 class_&lt;testclass&gt;(&quot;testclass&quot;)
482 .def(constructor&lt;const std::string&amp;&gt;())
483 .def(&quot;print_string&quot;, &amp;testclass::print_string)
485 </pre>
486 <p>This will register the class with the name testclass and constructor that takes
487 a string as argument and one member function with the name <tt class="literal"><span class="pre">print_string</span></tt>.</p>
488 <pre class="literal-block">
489 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
490 &gt; a = testclass('a string')
491 &gt; a:print_string()
492 a string
493 </pre>
494 <p>It is also possible to register free functions as member functions. The
495 requirement on the function is that it takes a pointer, const pointer,
496 reference or const reference to the class type as the first parameter. The rest
497 of the parameters are the ones that are visible in lua, while the object
498 pointer is given as the first parameter. If we have the following C++ code:</p>
499 <pre class="literal-block">
500 struct A
502 int a;
505 int plus(A* o, int v) { return o-&gt;a + v; }
506 </pre>
507 <p>You can register <tt class="literal"><span class="pre">plus()</span></tt> as if it was a member function of A like this:</p>
508 <pre class="literal-block">
509 class_&lt;A&gt;(&quot;A&quot;)
510 .def(&quot;plus&quot;, &amp;plus)
511 </pre>
512 <p><tt class="literal"><span class="pre">plus()</span></tt> can now be called as a member function on A with one parameter, int.
513 If the object pointer parameter is const, the function will act as if it was a
514 const member function (it can be called on const objects).</p>
515 <div class="section" id="properties">
516 <h2><a class="toc-backref" href="#id14" name="properties">8.1   Properties</a></h2>
517 <p>To register a global data member with a class is easily done. Consider the
518 following class:</p>
519 <pre class="literal-block">
520 struct A
522 int a;
524 </pre>
525 <p>This class is registered like this:</p>
526 <pre class="literal-block">
527 module(L)
529 class_&lt;A&gt;(&quot;A&quot;)
530 .def_readwrite(&quot;a&quot;, &amp;A::a)
532 </pre>
533 <p>This gives read and write access to the member variable <tt class="literal"><span class="pre">A::a</span></tt>. It is also
534 possible to register attributes with read-only access:</p>
535 <pre class="literal-block">
536 module(L)
538 class_&lt;A&gt;(&quot;A&quot;)
539 .def_readonly(&quot;a&quot;, &amp;A::a)
541 </pre>
542 <p>You can also register getter and setter functions and make them look as if they
543 were a public data member. Consider the following class:</p>
544 <pre class="literal-block">
545 class A
547 public:
548 void set_a(int x) { a = x; }
549 int get_a() const { return a; }
551 private:
552 int a;
554 </pre>
555 <p>It can be registered as if it had a public data member a like this:</p>
556 <pre class="literal-block">
557 class_&lt;A&gt;(&quot;A&quot;)
558 .property(&quot;a&quot;, &amp;A::get_a, &amp;A::set_a)
559 </pre>
560 <p>This way the <tt class="literal"><span class="pre">get_a()</span></tt> and <tt class="literal"><span class="pre">set_a()</span></tt> functions will be called instead of
561 just writing to the data member. If you want to make it read only you can just
562 omit the last parameter.</p>
563 </div>
564 <div class="section" id="enums">
565 <h2><a class="toc-backref" href="#id15" name="enums">8.2   Enums</a></h2>
566 <p>If your class contains enumerated constants (enums), you can register them as
567 well to make them available in lua. Note that they will not be type safe, all
568 enums are integers in lua, and all functions that takes an enum, will accept
569 any integer. You register them like this:</p>
570 <pre class="literal-block">
571 module(L)
573 class_&lt;A&gt;(&quot;A&quot;)
574 .enum_(&quot;constants&quot;)
576 value(&quot;my_enum&quot;, 4),
577 value(&quot;my_2nd_enum&quot;, 7),
578 value(&quot;another_enum&quot;, 6)
581 </pre>
582 <p>In lua they are accessed like any data member, except that they are read-only
583 and reached on the class itself rather than on an instance of the class.</p>
584 <pre class="literal-block">
585 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
586 &gt; print(A.my_enum)
588 &gt; print(A.another_enum)
590 </pre>
591 </div>
592 <div class="section" id="operators">
593 <h2><a class="toc-backref" href="#id16" name="operators">8.3   Operators</a></h2>
594 <p>The mechanism for registering operators on your class is pretty simple. You use
595 a global name <tt class="literal"><span class="pre">luabind::self</span></tt> to refer to the class itself and then you just
596 write the operator expression inside the <tt class="literal"><span class="pre">def()</span></tt> call. This class:</p>
597 <pre class="literal-block">
598 struct vec
600 vec operator+(int s);
602 </pre>
603 <p>Is registered like this:</p>
604 <pre class="literal-block">
605 module(L)
607 class_&lt;vec&gt;(&quot;vec&quot;)
608 .def(self + int())
610 </pre>
611 <p>This will work regardless if your plus operator is defined inside your class or
612 as a free function.</p>
613 <p>If you operator is const (or, when defined as a free function, takes a const
614 reference to the class itself) you have to use <tt class="literal"><span class="pre">const_self</span></tt> instead of
615 <tt class="literal"><span class="pre">self</span></tt>. Like this:</p>
616 <pre class="literal-block">
617 module(L)
619 class_&lt;vec&gt;(&quot;vec&quot;)
620 .def(const_self + int())
622 </pre>
623 <p>The operators supported are those available in lua:</p>
624 <blockquote>
625 <ul class="simple">
626 <li>+</li>
627 <li>-</li>
628 <li>*</li>
629 <li>/</li>
630 </ul>
631 <!-- more -->
632 </blockquote>
633 <p>This means, no in-place operators. The equality operator (==) has a little
634 hatch, it will not be called if the references are equal. This means that the
635 == operator has to do pretty much what's it's expected to do.</p>
636 <p>In the above example the other operand type is instantiated by writing
637 <tt class="literal"><span class="pre">int()</span></tt>. If the operand type is a complex type that cannot easily be
638 instantiated you can wrap the type in a class called <tt class="literal"><span class="pre">other&lt;&gt;</span></tt>. For example:</p>
639 <p>To register this class, we don't want to instantiate a string just to register
640 the operator.</p>
641 <pre class="literal-block">
642 struct vec
644 vec operator+(std::string);
646 </pre>
647 <p>Instead we use the other <tt class="literal"><span class="pre">wrapper</span></tt> like this:</p>
648 <pre class="literal-block">
649 module(L)
651 class_&lt;vec&gt;(&quot;vec&quot;)
652 .def(self + other&lt;std::string&gt;())
654 </pre>
655 <p>To register an application operator:</p>
656 <pre class="literal-block">
657 module(L)
659 class_&lt;vec&gt;(&quot;vec&quot;)
660 .def( self(int()) )
662 </pre>
663 <p>There's one special operator. In lua it's called <tt class="literal"><span class="pre">__tostring</span></tt>, it's not
664 really an operator. It is used for converting objects to strings in a standard
665 way in lua. If you register this functionality, you will be able to use the lua
666 standard function <tt class="literal"><span class="pre">tostring()</span></tt> for converting you object to a string.</p>
667 <p>To implement this operator in C++ you should supply an <tt class="literal"><span class="pre">operator&lt;&lt;</span></tt> for
668 ostream. Like this example:</p>
669 <pre class="literal-block">
670 class number {};
671 std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, number&amp;);
675 module(L)
677 class_&lt;number&gt;(&quot;number&quot;)
678 .def(tostring(self))
680 </pre>
681 </div>
682 <div class="section" id="nested-scopes-and-static-functions">
683 <h2><a class="toc-backref" href="#id17" name="nested-scopes-and-static-functions">8.4   Nested scopes and static functions</a></h2>
684 <p>It is possible to add nested scopes to a class. This is useful when you need
685 to wrap a nested class, or a static function.</p>
686 <pre class="literal-block">
687 class_&lt;foo&gt;(&quot;foo&quot;)
688 .def(constructor&lt;&gt;()
690 .static_
692 class_&lt;inner&gt;(&quot;nested&quot;),
693 def(&quot;f&quot;, &amp;f)
695 </pre>
696 <p>It's also possible to add namespaces to classes using the same syntax.</p>
697 </div>
698 <div class="section" id="derived-classes">
699 <h2><a class="toc-backref" href="#id18" name="derived-classes">8.5   Derived classes</a></h2>
700 <p>If you want to register classes that derives from other classes, you can
701 specify a template parameter <tt class="literal"><span class="pre">bases&lt;&gt;</span></tt> to the <tt class="literal"><span class="pre">class_</span></tt> instantiation. The
702 following hierarchy:</p>
703 <pre class="literal-block">
704 struct A {};
705 struct B : A {};
706 </pre>
707 <p>Would be registered like this:</p>
708 <pre class="literal-block">
709 module(L)
711 class_&lt;A&gt;(&quot;A&quot;),
712 class_&lt;B, A&gt;(&quot;B&quot;)
714 </pre>
715 <p>If you have multiple inheritance you can specify more than one base. If B would
716 also derive from a class C, it would be registered like this:</p>
717 <pre class="literal-block">
718 module(L)
720 class_&lt;B, bases&lt;A, C&gt; &gt;(&quot;B&quot;)
722 </pre>
723 <p>Note that you can omit <tt class="literal"><span class="pre">bases&lt;&gt;</span></tt> when using single inheritance.</p>
724 <div class="note">
725 <p class="admonition-title">Note</p>
726 If you don't specify that classes derive from each other, luabind will not
727 be able to implicitly cast pointers between the types.</div>
728 </div>
729 <div class="section" id="smart-pointers">
730 <h2><a class="toc-backref" href="#id19" name="smart-pointers">8.6   Smart pointers</a></h2>
731 <p>When you register a class you can tell luabind that all instances of that class
732 should be held by some kind of smart pointer (boost::shared_ptr for instance).
733 You do this by giving the holder type as an extra template parameter to
734 the``class_``your constructing, like this:</p>
735 <pre class="literal-block">
736 module(L)
738 class_&lt;A, boost::shared_ptr&lt;A&gt; &gt;(&quot;A&quot;)
740 </pre>
741 <p>You also have to supply two functions for your smart pointer. One that returns
742 the type of const version of the smart pointer type (boost::shared_ptr&lt;const A&gt;
743 in this case). And one function that extracts the raw pointer from the smart
744 pointer. The first function is needed because luabind has to allow the
745 non-const -&gt; conversion when passing values from lua to C++. The second
746 function is needed when lua calls member functions on held types, the this
747 pointer must be a raw pointer, it is also needed to allow the smart_pointer -&gt;
748 raw_pointer conversion from lua to C++. They look like this:</p>
749 <pre class="literal-block">
750 namespace luabind {
752 template&lt;class T&gt;
753 T* get_pointer(boost::shared_ptr&lt;T&gt;&amp; p)
755 return p.get();
758 template&lt;class A&gt;
759 boost::shared_ptr&lt;const A&gt;*
760 get_const_holder(boost::shared_ptr&lt;A&gt;*)
762 return 0;
765 </pre>
766 <p>The conversion that works are (given that B is a base class of A):</p>
767 <table border class="table">
768 <colgroup>
769 <col width="49%" />
770 <col width="51%" />
771 </colgroup>
772 <thead valign="bottom">
773 <tr><th colspan="2">From lua to C++</th>
774 </tr>
775 </thead>
776 <tbody valign="top">
777 <tr><td>holder_type&lt;A&gt;</td>
778 <td>A*</td>
779 </tr>
780 <tr><td>holder_type&lt;A&gt;</td>
781 <td>A*</td>
782 </tr>
783 <tr><td>holder_type&lt;A&gt;</td>
784 <td>const A*</td>
785 </tr>
786 <tr><td>holder_type&lt;A&gt;</td>
787 <td>const B*</td>
788 </tr>
789 <tr><td>holder_type&lt;A&gt;</td>
790 <td>holder_type&lt;A&gt;</td>
791 </tr>
792 <tr><td>holder_type&lt;A&gt;</td>
793 <td>holder_type&lt;const A&gt;</td>
794 </tr>
795 <tr><td>holder_type&lt;const A&gt;</td>
796 <td>const A*</td>
797 </tr>
798 <tr><td>holder_type&lt;const A&gt;</td>
799 <td>const B*</td>
800 </tr>
801 <tr><td>holder_type&lt;const A&gt;</td>
802 <td>holder_type&lt;const A&gt;</td>
803 </tr>
804 </tbody>
805 </table>
806 <table border class="table">
807 <colgroup>
808 <col width="56%" />
809 <col width="44%" />
810 </colgroup>
811 <thead valign="bottom">
812 <tr><th colspan="2">From C++ to lua</th>
813 </tr>
814 </thead>
815 <tbody valign="top">
816 <tr><td>holder_type&lt;A&gt;</td>
817 <td>holder_type&lt;A&gt;</td>
818 </tr>
819 <tr><td>holder_type&lt;const A&gt;</td>
820 <td>holder_type&lt;const A&gt;</td>
821 </tr>
822 <tr><td>const holder_type&lt;A&gt;&amp;</td>
823 <td>holder_type&lt;A&gt;</td>
824 </tr>
825 <tr><td>const holder_type&lt;const A&gt;&amp;</td>
826 <td>holder_type&lt;const A&gt;</td>
827 </tr>
828 </tbody>
829 </table>
830 <p>When using a holder type, it can be useful to know if the pointer is valid. For
831 example when using std::auto_ptr, the holder will be invalidated when passed as
832 a parameter to a function. For this purpose there is a member of all object
833 instances in luabind: <tt class="literal"><span class="pre">__ok</span></tt>.</p>
834 <pre class="literal-block">
835 struct test {};
836 void f(std::auto_ptr&lt;test&gt;);
838 module(L)
840 class_&lt;test&gt;(&quot;test&quot;)
841 .def(constructor&lt;&gt;()),
843 def(&quot;f&quot;, &amp;f)
845 </pre>
846 <pre class="literal-block">
847 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
848 &gt; a = test()
849 &gt; f(a)
850 &gt; print a.__ok
851 false
852 </pre>
853 </div>
854 </div>
855 <div class="section" id="object">
856 <h1><a class="toc-backref" href="#id20" name="object">9   Object</a></h1>
857 <p>Since functions have to be able to take lua values (of variable type) we need a
858 wrapper around them. This wrapper is called <tt class="literal"><span class="pre">luabind::object</span></tt>. If the
859 function you register takes an object, it will match any lua value. To use it,
860 you need to include <tt class="literal"><span class="pre">luabind/object.hpp</span></tt>. The object class has the following
861 synopsis:</p>
862 <pre class="literal-block">
863 class object
865 public:
866 class iterator;
867 class raw_iterator;
868 class array_iterator;
870 template&lt;class T&gt;
871 object(lua_State*, const T&amp; value);
872 object(const object&amp;);
873 object(lua_State*);
874 object();
876 ~object();
878 iterator begin() const;
879 iterator end() const;
880 raw_iterator raw_begin() const;
881 raw_iterator raw_end() const;
882 array_iterator abegin() const;
883 array_iterator aend() const;
885 void set();
886 lua_State* lua_state() const;
887 void pushvalue() const;
888 bool is_valid() const;
889 operator safe_bool_type() const;
891 template&lt;class Key&gt;
892 &lt;implementation-defined&gt; operator[](const Key&amp;);
894 template&lt;class Key&gt;
895 object at(const Key&amp;) const;
897 template&lt;class Key&gt;
898 object raw_at(const Key&amp;) const;
900 template&lt;class T&gt;
901 object&amp; operator=(const T&amp;);
902 object&amp; operator=(const object&amp;);
904 template&lt;class T&gt;
905 bool operator==(const T&amp;) const;
906 bool operator==(const object&amp;) const;
907 bool operator&lt;(const object&amp;) const;
908 bool operator&lt;=(const object&amp;) const;
909 bool operator&gt;(const object&amp;) const;
910 bool operator&gt;=(const object&amp;) const;
911 bool operator!=(const object&amp;) const;
913 void swap(object&amp;);
914 int type() const;
916 &lt;implementation-defined&gt; operator()();
918 template&lt;class A0&gt;
919 &lt;implementation-defined&gt; operator()(const A0&amp; a0);
921 template&lt;class A0, class A1&gt;
922 &lt;implementation-defined&gt; operator()(const A0&amp; a0, const A1&amp; a1);
924 /* ... */
927 </pre>
928 <p>When you have a lua object, you can assign it a new value with the assignment
929 operator (=). When you do this, the <tt class="literal"><span class="pre">default_policy</span></tt> will be used to make the
930 conversion from C++ value to lua. If your <tt class="literal"><span class="pre">luabind::object</span></tt> is a table you
931 can access its members through the operator[] or the iterators. The value
932 returned from the operator[] is a proxy object that can be used both for
933 reading and writing values into the table (using operator=). Note that it is
934 impossible to know if a lua value is indexable or not (lua_gettable doesn't
935 fail, it succeeds or crashes). This means that if you're trying to index
936 something that cannot be indexed, you're on your own. Lua will call its
937 <tt class="literal"><span class="pre">panic()</span></tt> function (you can define your own panic function using
938 lua_setpanicf). The <tt class="literal"><span class="pre">at()</span></tt> and <tt class="literal"><span class="pre">raw_at()</span></tt> functions returns the value at
939 the given table position (like operator[] but only for reading).</p>
940 <p>The ordinary <tt class="literal"><span class="pre">object::iterator</span></tt> uses lua_gettable to extract the values from
941 the table, the standard way that will invoke metamethods if any. The
942 <tt class="literal"><span class="pre">object::raw_iterator</span></tt> uses lua_rawget and <tt class="literal"><span class="pre">object::array_iterator</span></tt> uses
943 lua_rawgeti. The latter will only iterate over numberical keys starting at 1
944 and continue until the first nil value.</p>
945 <p>The <tt class="literal"><span class="pre">lua_state()</span></tt> function returns the lua state where this object is stored.
946 If you want to manipulate the object with lua functions directly you can push
947 it onto the lua stack by calling <tt class="literal"><span class="pre">pushvalue()</span></tt>. And set the object's value by
948 calling <tt class="literal"><span class="pre">set()</span></tt>, which will pop the top value from the lua stack and assign
949 it to the object.</p>
950 <p>The operator== will call lua_equal() on the operands and return its result.</p>
951 <p>The <tt class="literal"><span class="pre">type()</span></tt> member function will return the lua type of the object. It will
952 return the same values as lua_type().</p>
953 <p>The <tt class="literal"><span class="pre">is_valid()</span></tt> function tells you whether the object has been initialized
954 or not. When created with its default constructor, objects are invalid. To make
955 an object valid, you can assign it a value. If you want to invalidate an object
956 you can simply assign it an invalid object.</p>
957 <!-- So what? implementation detail, leave out of docs
958 isn't really an implicit cast to bool, but an implicit cast
959 to a member pointer, since member pointers don't have any arithmetic operators
960 on them (which can cause hard to find errors). The functionality of the cast
961 operator -->
962 <p>The <tt class="literal"><span class="pre">operator</span> <span class="pre">safe_bool_type()</span></tt> is equivalent to <tt class="literal"><span class="pre">is_valid()</span></tt>. This means
963 that these snippets are equivalent:</p>
964 <pre class="literal-block">
965 object o;
966 // ...
967 if (o)
969 // ...
974 object o;
975 // ...
976 if (o.is_valid())
978 // ...
980 </pre>
981 <p>The application operator will call the value as if it was a function. You can
982 give it any number of parameters (currently the <tt class="literal"><span class="pre">default_policy</span></tt> will be used
983 for the conversion). The returned object refers to the return value (currently
984 only one return value is supported). This operator may throw <tt class="literal"><span class="pre">luabind::error</span></tt>
985 if the function call fails. If you want to specify policies to your function
986 call, you can use index-operator (operator[]) on the function call, and give
987 the policies within the [ and ]. Like this:</p>
988 <pre class="literal-block">
989 my_function_object(
992 , new my_complex_structure(6)
993 ) [ adopt(_3) ];
994 </pre>
995 <p>This tells luabind to make lua adopt the ownership and responsibility for the
996 pointer passed in to the lua-function.</p>
997 <p>It's important that all instances of object have been destructed by the time
998 the lua state is closed. The object will keep a pointer to the lua state and
999 release its lua object in its destructor.</p>
1000 <p>Here's an example of how a function can use a table:</p>
1001 <pre class="literal-block">
1002 void my_function(const object&amp; table)
1004 if (table.type() == LUA_TTABLE)
1006 table[&quot;time&quot;] = std::clock();
1007 table[&quot;name&quot;] = std::rand() &lt; 500 ? &quot;unusual&quot; : &quot;usual&quot;;
1009 std::cout &lt;&lt; object_cast&lt;std::string&gt;(table[5]) &lt;&lt; &quot;\n&quot;;
1012 </pre>
1013 <p>If you take a <tt class="literal"><span class="pre">luabind::object</span></tt> as a parameter to a function, any lua value
1014 will match that parameter. That's why we have to make sure it's a table before
1015 we index into it.</p>
1016 <div class="section" id="iterators">
1017 <h2><a class="toc-backref" href="#id21" name="iterators">9.1   Iterators</a></h2>
1018 <p>The iterators, that are returned by <tt class="literal"><span class="pre">begin()</span> <span class="pre">and</span> <span class="pre">``end()</span></tt> (and their
1019 variants) are (almost) models of the ForwardIterator concept. The exception
1020 is that post increment doesn't exist on them.</p>
1021 <p>They look like this:</p>
1022 <pre class="literal-block">
1023 class object::iterator
1025 iterator();
1026 iterator(const iterator&amp;);
1028 iterator&amp; operator++();
1029 bool operator!=(const iterator&amp;) const;
1030 iterator&amp; operator=(const iterator&amp;);
1032 object key() const;
1034 implementation-defined operator*();
1036 </pre>
1037 <p>The implementation defined return value from the dereference operator is a
1038 proxy object that can be used as if it was an object, it can also be used to
1039 assign the specific table entry with a new value. If you want to assign a value
1040 to an entry pointed to by an iterator, just use the assignment operator on the
1041 dereferenced iterator:</p>
1042 <pre class="literal-block">
1043 *iter = 5;
1044 </pre>
1045 <p>The <tt class="literal"><span class="pre">key()</span></tt> member returns the key used by the iterator when indexing the
1046 associated lua table.</p>
1047 </div>
1048 <div class="section" id="related-functions">
1049 <h2><a class="toc-backref" href="#id22" name="related-functions">9.2   Related functions</a></h2>
1050 <p>There are a couple of functions related to objects and tables.</p>
1051 <pre class="literal-block">
1052 T object_cast&lt;T&gt;(const object&amp;);
1053 T object_cast&lt;T&gt;(const object&amp;, const Policies&amp;);
1055 boost::optional&lt;T&gt;
1056 object_cast_nothrow&lt;T&gt;(const object&amp;);
1058 boost::optional&lt;T&gt;
1059 object_cast_nothrow&lt;T&gt;(const object&amp;, const Policies&amp;);
1060 </pre>
1061 </div>
1062 <div class="section" id="functor">
1063 <h2><a class="toc-backref" href="#id23" name="functor">9.3   Functor</a></h2>
1064 <p>The <tt class="literal"><span class="pre">functor</span></tt> class is similar to object, with the exception that it can only
1065 be used to store functions. If you take it as a parameter, it will only match
1066 functions.</p>
1067 <p>To use it you need to include its header:</p>
1068 <pre class="literal-block">
1069 #include &lt;luabind/functor.hpp&gt;
1070 </pre>
1071 <p>It takes one template parameter, the return value of the lua function it
1072 represents. Currently the functor can have at most one return value (unlike lua
1073 functions). It has the following synopsis:</p>
1074 <pre class="literal-block">
1075 template&lt;class Ret&gt;
1076 class functor
1078 public:
1080 functor(lua_State*, const char* name);
1081 functor(const functor&amp;);
1083 ~functor();
1085 bool is_valid() const;
1086 operator safe_bool_type() const;
1088 lua_State* lua_state() const;
1089 void pushvalue() const;
1091 bool operator==(const functor&lt;Ret&gt;&amp;);
1092 bool operator!=(const functor&lt;Ret&gt;&amp;);
1094 &lt;implementation-defined&gt; operator()() const;
1096 template&lt;class A0&gt;
1097 &lt;implementation-defined&gt; operator()(const A0&amp;) const;
1099 template&lt;class A0, class A1&gt;
1100 &lt;implementation-defined&gt; operator()(const A0&amp;, const A1&amp;) const;
1102 /* ... */
1104 </pre>
1105 <p>The application operator takes any parameters. The parameters are converted
1106 into lua and the function is called. The return value will act as if it was the
1107 type Ret, with the exception that you can use the return value to give policies
1108 to the call. You do this the same way as you do with objects, using the
1109 operator[], and giving the policies inside the brackets.</p>
1110 <p>The <tt class="literal"><span class="pre">is_valid()</span></tt> function works just like the one on object, it tells you if
1111 the functor has been assigned with a valid lua function. The <tt class="literal"><span class="pre">operator</span>
1112 <span class="pre">safe_bool_type()</span></tt> is an alias for this member function and also works just as
1113 the one found in object.</p>
1114 <p>For example, if you have the following lua function:</p>
1115 <pre class="literal-block">
1116 function f(a, b)
1117 return a + b
1119 </pre>
1120 <p>You can expose it to C++ like this:</p>
1121 <pre class="literal-block">
1122 functor&lt;int&gt; f(L, &quot;f&quot;);
1124 std::cout &lt;&lt; f(3, 5) &lt;&lt; &quot;\n&quot;;
1125 </pre>
1126 <p>This will print out the sum of 3 and 5. Note that you can pass any parameters
1127 to the application operator of <tt class="literal"><span class="pre">luabind::functor</span></tt>, this is because lua
1128 doesn't have signatures for its functions. All lua functions take any number of
1129 parameters of any type.</p>
1130 <p>If we have a C++ function that takes a <tt class="literal"><span class="pre">luabind::functor</span></tt> and registers it,
1131 it will accept lua functions passed to it. This enables us to expose APIs that
1132 requires you to register callbacks. For example, if your C++ API looks like
1133 this:</p>
1134 <pre class="literal-block">
1135 void set_callback(void(*)(int, int));
1136 </pre>
1137 <p>And you want to expose it to lua, you have to wrap the call to the lua
1138 function inside a real C++ function, like this:</p>
1139 <pre class="literal-block">
1140 functor&lt;void&gt; lua_callback;
1142 void callback_wrapper(int a, int b)
1144 lua_callback(a, b);
1147 void set_callback_wrapper(const functor&lt;void&gt;&amp; f)
1149 lua_callback = f;
1150 set_callback(&amp;callback_wrapper);
1152 </pre>
1153 <p>And then register <tt class="literal"><span class="pre">set_callback_wrapper</span></tt> instead of registering
1154 <tt class="literal"><span class="pre">set_callback</span></tt>. This will have the effect that when one tries to register the
1155 callback from lua, your <tt class="literal"><span class="pre">set_callback_wrapper</span></tt> will be called instead and
1156 first set the lua functor to the given function. It will then call the real
1157 <tt class="literal"><span class="pre">set_callback</span></tt> with the <tt class="literal"><span class="pre">callback_wrapper</span></tt>. The <tt class="literal"><span class="pre">callback_wrapper</span></tt> will
1158 be called whenever the callback should be called, and it will simply call the
1159 lua function that we registered.</p>
1160 <p>You can also use <tt class="literal"><span class="pre">object_cast</span></tt> to cast an object to a functor.</p>
1161 </div>
1162 </div>
1163 <div class="section" id="defining-classes-in-lua">
1164 <h1><a class="toc-backref" href="#id24" name="defining-classes-in-lua">10   Defining classes in lua</a></h1>
1165 <p>In addition to binding C++ functions and classes with lua, luabind also provide
1166 an OO-system in lua.</p>
1167 <pre class="literal-block">
1168 class 'lua_testclass'
1170 function lua_testclass:__init(name)
1171 self.name = name
1174 function lua_testclass:print()
1175 print(self.name)
1178 a = lua_testclass('example')
1179 a:print()
1180 </pre>
1181 <p>Inheritance can be used between lua-classes:</p>
1182 <pre class="literal-block">
1183 class 'derived' (lua_testclass)
1185 function derived:__init() super('derived name')
1188 function derived:print()
1189 print('Derived:print() -&gt; ')
1190 lua_testclass.print(self)
1192 </pre>
1193 <p>Here the <tt class="literal"><span class="pre">super</span></tt> keyword is used in the constructor to initialize the base
1194 class. The user is required to call <tt class="literal"><span class="pre">super</span></tt> first in the constructor.</p>
1195 <p>As you can see in this example, you can call the base class member functions.
1196 You can find all member functions in the base class, but you will have to give
1197 the this-pointer (<tt class="literal"><span class="pre">self</span></tt>) as first argument.</p>
1198 <div class="section" id="deriving-in-lua">
1199 <h2><a class="toc-backref" href="#id25" name="deriving-in-lua">10.1   Deriving in lua</a></h2>
1200 <p>It is also possible to derive lua classes from C++ classes, and override
1201 virtual functions with lua functions. To do this we have to create a wrapper
1202 class for our C++ base class. This is the class that will hold the lua object
1203 when we instantiate a lua class.</p>
1204 <p>The wrapper class has to provide the same constructors as the base class, with
1205 the addition of one extra parameter: <tt class="literal"><span class="pre">luabind::object</span></tt>. This is the reference
1206 to the lua object that should be held by the wrapper, and should be stored in a
1207 member variable as done in the sample below.</p>
1208 <pre class="literal-block">
1209 class base
1211 public:
1212 base(const char* s)
1213 { std::cout &lt;&lt; s &lt;&lt; &quot;\n&quot;; }
1215 virtual void f(int a)
1216 { std::cout &lt;&lt; &quot;f(&quot; &lt;&lt; a &lt;&lt; &quot;)\n&quot;; }
1219 struct base_wrapper : base
1221 object self;
1222 base_wrapper(object self_, const char* s)
1223 : base(s), self(self_)
1226 virtual void f(int a)
1228 call_member&lt;void&gt;(self, &quot;f&quot;, a);
1231 static void f_static(base* ptr, int a)
1233 return ptr-&gt;base::f(a);
1239 module(L)
1241 class_&lt;base, base_wrapper&gt;(&quot;base&quot;)
1242 .def(constructor&lt;const char*&gt;())
1243 .def(&quot;f&quot;, &amp;base_wrapper::f_static)
1245 </pre>
1246 <p>Note that if you have both base classes and a base class wrapper, you must give
1247 both bases and the base class wrapper type as template parameter to
1248 ´´class_´´. The order in which you specify them is not important.</p>
1249 <p>If we didn't have a class wrapper, it would not be possible to pass a lua class
1250 back to C++. Since the entry points of the virtual functions would still point
1251 to the C++ base class, and not to the functions defined in lua. That's why we
1252 need one function that calls the base class' real function (used if the lua
1253 class doesn't redefine it) and one virtual function that dispatches the call
1254 into luabind, to allow it to select if a lua function should be called, or if
1255 the original function should be called. If you don't intend to derive from a
1256 C++ class, or if it doesn't have any virtual member functions, you can register
1257 it without a class wrapper.</p>
1258 <p>You don't need to have a class wrapper in order to derive from a class, but if
1259 it has virtual functions you may have silent errors.</p>
1260 <!-- Unnecessary? The rule of thumb is:
1261 If your class has virtual functions, create a wrapper type, if it doesn't
1262 don't create a wrapper type. -->
1263 </div>
1264 <div class="section" id="overloading-operators">
1265 <h2><a class="toc-backref" href="#id26" name="overloading-operators">10.2   Overloading operators</a></h2>
1266 <p>You can overload most operators in lua for your classes. You do this by simply
1267 declaring a member function with the same name as an operator (the name of the
1268 metamethods in lua). The operators you can overload are:</p>
1269 <blockquote>
1270 <ul class="simple">
1271 <li>__add</li>
1272 <li>__sub</li>
1273 <li>__mul</li>
1274 <li>__div</li>
1275 <li>__pow</li>
1276 <li>__lt</li>
1277 <li>__le</li>
1278 <li>__eq</li>
1279 <li>__call</li>
1280 <li>__unm</li>
1281 <li>__tostring</li>
1282 </ul>
1283 </blockquote>
1284 <p><tt class="literal"><span class="pre">__tostring</span></tt> isn't really an operator, but it's the metamethod that is called
1285 by the standard library's <tt class="literal"><span class="pre">tostring()</span></tt> function. There's one strange behavior
1286 regarding binary operators. You are not guaranteed that the self pointer you
1287 get actually refers to an instance of your class. This is because lua doesn't
1288 distinguish the two cases where you get the other operand as left hand value or
1289 right hand value. Consider the following examples:</p>
1290 <pre class="literal-block">
1291 class 'my_class'
1293 function my_class:__init(v)
1294 self.val = v
1297 function my_class:__sub(v)
1298 return my_class(self.val - v.val)
1301 function my_class:__tostring()
1302 return self.val
1304 </pre>
1305 <p>This will work well as long as you only subtracts instances of my_class with
1306 each other. But If you want to be able to subtract ordinary numbers from your
1307 class too, you have to manually check the type of both operands, including the
1308 self object.</p>
1309 <pre class="literal-block">
1310 function my_class:__sub(v)
1311 if (type(self) == 'number') then
1312 return my_class(self - v.val)
1314 elseif (type(v) == 'number') then
1315 return my_class(self.val - v)
1317 else
1318 -- assume both operands are instances of my_class
1319 return my_class(self.val - v.val)
1323 </pre>
1324 <p>The reason why <tt class="literal"><span class="pre">__sub</span></tt> is used as an example is because subtraction is not
1325 commutative (the order of the operands matter). That's why luabind cannot
1326 change order of the operands to make the self reference always refer to the
1327 actual class instance.</p>
1328 <p>If you have two different lua classes with an overloaded operator, the operator
1329 of the right hand side type will be called. If the other operand is a C++ class
1330 with the same operator overloaded, it will be prioritized over the lua class'
1331 operator. If none of the C++ overloads matches, the lua class operator will be
1332 called.</p>
1333 </div>
1334 <div class="section" id="finalizers">
1335 <h2><a class="toc-backref" href="#id27" name="finalizers">10.3   Finalizers</a></h2>
1336 <p>If an object needs to perform actions when it's collected we provide a
1337 <tt class="literal"><span class="pre">__finalize</span></tt> function that can be overridden in lua-classes. The
1338 <tt class="literal"><span class="pre">__finalize</span></tt> functions will be called on all classes in the inheritance
1339 chain, starting with the most derived type.</p>
1340 <pre class="literal-block">
1343 function lua_testclass:__finalize()
1344 -- called when the an object is collected
1346 </pre>
1347 </div>
1348 </div>
1349 <div class="section" id="exceptions">
1350 <h1><a class="toc-backref" href="#id28" name="exceptions">11   Exceptions</a></h1>
1351 <p>If any of the functions you register throws an exception when called, that
1352 exception will be caught by luabind and converted to an error string and
1353 <tt class="literal"><span class="pre">lua_error()</span></tt> will be invoked. If the exception is a <tt class="literal"><span class="pre">std::exception</span></tt> or a
1354 <tt class="literal"><span class="pre">const</span> <span class="pre">char*</span></tt> the string that is pushed on the lua stack, as error message,
1355 will be the string returned by <tt class="literal"><span class="pre">std::exception::what()</span></tt> or the string itself
1356 respectively. If the exception is unknown, a generic string saying that the
1357 function threw an exception will be pushed.</p>
1358 <p>Exceptions thrown from user defined functions have to be caught by luabind. If
1359 they weren't they would be thrown through lua itself, which is usually compiled
1360 as C code and doesn't support the stack-unwinding that exceptions imply.</p>
1361 <p>Any function that invokes lua code may throw <tt class="literal"><span class="pre">luabind::error</span></tt>. This exception
1362 means that a lua run-time error occurred. The error message is found on top of
1363 the lua stack. The reason why the exception doesn't contain the error string
1364 itself is because it would then require heap allocation which may fail. If an
1365 exception class throws an exception while it is being thrown itself, the
1366 application will be terminated.</p>
1367 <p>Error's synopsis is:</p>
1368 <pre class="literal-block">
1369 class error : public std::exception
1371 public:
1372 error(lua_State*);
1373 lua_State* state() const throw();
1374 virtual const char* what() const throw();
1376 </pre>
1377 <p>The state function returns a pointer to the lua state in which the error was
1378 thrown. This pointer may be invalid if you catch this exception after the lua
1379 state is destructed. If the lua state is valid you can use it to retrieve the
1380 error message from the top of the lua stack.</p>
1381 <p>An example of where the lua state pointer may point to an invalid state
1382 follows:</p>
1383 <pre class="literal-block">
1384 struct lua_state
1386 lua_state(lua_State* L): m_L(L) {}
1387 ~lua_state() { lua_close(m_L); }
1388 operator lua_State*() { return m_L; }
1389 lua_State* m_L;
1392 int main()
1396 lua_state L = lua_open();
1397 /* ... */
1399 catch(luabind::error&amp; e)
1401 lua_State* L = e.state();
1402 // L will now point to the destructed
1403 // lua state and be invalid
1404 /* ... */
1407 </pre>
1408 <p>There's another exception that luabind may throw: <tt class="literal"><span class="pre">luabind::cast_failed</span></tt>,
1409 this exception is thrown from <tt class="literal"><span class="pre">call_function&lt;&gt;</span></tt>, <tt class="literal"><span class="pre">call_member&lt;&gt;</span></tt> or when
1410 <tt class="literal"><span class="pre">functor&lt;&gt;</span></tt> is invoked. It means that the return value from the lua function
1411 couldn't be converted to a C++ value. It is also thrown from <tt class="literal"><span class="pre">object_cast&lt;&gt;</span></tt>
1412 if the cast cannot be made.</p>
1413 <p>The synopsis for <tt class="literal"><span class="pre">luabind::cast_failed</span></tt> is:</p>
1414 <pre class="literal-block">
1415 class cast_failed : public std::exception
1417 public:
1418 cast_failed(lua_State*);
1419 lua_State* state() const throw();
1420 LUABIND_TYPE_INFO info() const throw();
1421 virtual const char* what() const throw();
1423 </pre>
1424 <p>Again, the state member function returns a pointer to the lua state where the
1425 error occurred. See the example above to see where this pointer may be invalid.</p>
1426 <p>The info member function returns the user defined <tt class="literal"><span class="pre">LUABIND_TYPE_INFO</span></tt>, which
1427 defaults to a <tt class="literal"><span class="pre">const</span> <span class="pre">std::type_info*</span></tt>. This type info describes the type that
1428 we tried to cast a lua value to.</p>
1429 <p>If you have defined <tt class="literal"><span class="pre">LUABIND_NO_EXCEPTIONS</span></tt> none of these exceptions will be
1430 thrown, instead you can set two callback functions that are called instead.
1431 These two functions are only defined if <tt class="literal"><span class="pre">LUABIND_NO_EXCEPTIONS</span></tt> are defined.</p>
1432 <pre class="literal-block">
1433 luabind::set_error_callback(void(*)(lua_State*))
1434 </pre>
1435 <p>The function you set will be called when a runtime-error occur in lua code. You
1436 can find an error message on top of the lua stack. This function is not
1437 expected to return, if it does luabind will call <tt class="literal"><span class="pre">std::terminate()</span></tt>.</p>
1438 <pre class="literal-block">
1439 luabind::set_cast_failed_callback(void(*)(lua_State*, LUABIND_TYPE_INFO))
1440 </pre>
1441 <p>The function you set is called instead of throwing <tt class="literal"><span class="pre">cast_failed</span></tt>. This function
1442 is not expected to return, if it does luabind will call <tt class="literal"><span class="pre">std::terminate()</span></tt>.</p>
1443 </div>
1444 <div class="section" id="policies">
1445 <h1><a class="toc-backref" href="#id29" name="policies">12   Policies</a></h1>
1446 <p>Sometimes it is necessary to control how luabind passes arguments and return
1447 value, to do this we have policies. These are the policies that can be used:</p>
1448 <div class="section" id="copy">
1449 <h2><a class="toc-backref" href="#id30" name="copy">12.1   Copy</a></h2>
1450 <p>This will make a copy of the parameter. This is the default behavior when
1451 passing parameters by-value. Note that this can only be used when passing from
1452 C++ to lua. This policy requires that the parameter type has a copy
1453 constructor.</p>
1454 <p>To use this policy you need to include <tt class="literal"><span class="pre">luabind/copy_policy.hpp</span></tt>.</p>
1455 </div>
1456 <div class="section" id="adopt">
1457 <h2><a class="toc-backref" href="#id31" name="adopt">12.2   Adopt</a></h2>
1458 <p>This will transfer ownership of the parameter.</p>
1459 <p>Consider making a factory function in C++ and exposing it to lua:</p>
1460 <pre class="literal-block">
1461 base* create_base()
1463 return new base();
1468 module(L)
1470 def(&quot;create_base&quot;, create_base)
1472 </pre>
1473 <p>Here we need to make sure lua understands that it should adopt the pointer
1474 returned by the factory-function. This can be done using the adopt-policy.</p>
1475 <pre class="literal-block">
1476 module(L)
1478 def(L, &quot;create_base&quot;, adopt(return_value))
1480 </pre>
1481 <p>To specify multiple policies we just separate them with '+'.</p>
1482 <pre class="literal-block">
1483 base* set_and_get_new(base* ptr)
1485 base_ptrs.push_back(ptr);
1486 return new base();
1489 module(L)
1491 def(&quot;set_and_get_new&quot;, &amp;set_and_get_new,
1492 adopt(return_value) + adopt(_1))
1494 </pre>
1495 <p>When lua adopts a pointer, it will call delete on it. This means that it cannot
1496 adopt pointers allocated with another allocator than new (no malloc for
1497 example).</p>
1498 <p>To use this policy you need to include <tt class="literal"><span class="pre">luabind/adopt_policy.hpp</span></tt>.</p>
1499 </div>
1500 <div class="section" id="dependency">
1501 <h2><a class="toc-backref" href="#id32" name="dependency">12.3   Dependency</a></h2>
1502 <p>The dependency policy is used to create life-time dependencies between values.
1503 Consider the following example:</p>
1504 <pre class="literal-block">
1505 struct A
1507 B member;
1509 const B&amp; get_member()
1511 return member;
1514 </pre>
1515 <p>When wrapping this class, we would do something like:</p>
1516 <pre class="literal-block">
1517 module(L)
1519 class_&lt;A&gt;(&quot;A&quot;)
1520 .def(constructor&lt;&gt;())
1521 .def(&quot;get_member&quot;, &amp;A::get_member)
1523 </pre>
1524 <p>However, since the return value of get_member is a reference to a member of A,
1525 this will create some life-time issues. For example:</p>
1526 <pre class="literal-block">
1527 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1528 a = A()
1529 b = a:get_member() -- b points to a member of a
1530 a = nil
1531 collectgarbage(0) -- since there are no references left to a, it is
1532 -- removed
1533 -- at this point, b is pointing into a removed object
1534 </pre>
1535 <p>When using the dependency-policy, it is possible to tell luabind to tie the
1536 lifetime of one object to another, like this:</p>
1537 <pre class="literal-block">
1538 module(L)
1540 class_&lt;A&gt;(&quot;A&quot;)
1541 .def(constructor&lt;&gt;())
1542 .def(&quot;get_member&quot;, &amp;A::get_member, dependency(result, self))
1544 </pre>
1545 <p>This will create a dependency between the return-value of the function, and the
1546 self-object. This means that the self-object will be kept alive as long as the
1547 result is still alive.</p>
1548 <pre class="literal-block">
1549 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1550 a = A()
1551 b = a:get_member() -- b points to a member of a
1552 a = nil
1553 collectgarbage(0) -- a is dependent on b, so it isn't removed
1554 b = nil
1555 collectgarbage(0) -- all dependencies to a gone, a is removed
1556 </pre>
1557 <p>To use this policy you need to include <tt class="literal"><span class="pre">luabind/dependency_policy.hpp</span></tt>.</p>
1558 </div>
1559 <div class="section" id="return-reference-to">
1560 <h2><a class="toc-backref" href="#id33" name="return-reference-to">12.4   Return reference to</a></h2>
1561 <p>It is very common to return references to arguments or the this-pointer to
1562 allow for chaining in C++.</p>
1563 <pre class="literal-block">
1564 struct A
1566 float val;
1568 A&amp; set(float v)
1570 val = v;
1571 return *this;
1574 </pre>
1575 <p>When luabind generates code for this, it will create a new object for the
1576 return-value, pointing to the self-object. This isn't a problem, but could be a
1577 bit inefficient. When using the return_reference_to-policy we have the ability
1578 to tell luabind that the return-value is already on the lua stack.</p>
1579 <pre class="literal-block">
1580 module(L)
1582 class_&lt;A&gt;(&quot;A&quot;)
1583 .def(constructor&lt;&gt;())
1584 .def(&quot;set&quot;, &amp;A::set, return_reference_to(self))
1586 </pre>
1587 <p>Instead of creating a new object, luabind will just copy the object that is
1588 already on the stack.</p>
1589 <div class="warning">
1590 <p class="admonition-title">Warning</p>
1591 This policy ignores all type information and should be used only it
1592 situations where the parameter type is a perfect match to the
1593 return-type (such as in the example).</div>
1594 <p>To use this policy you need to include <tt class="literal"><span class="pre">luabind/return_reference_to_policy.hpp</span></tt>.</p>
1595 </div>
1596 <div class="section" id="out-value">
1597 <h2><a class="toc-backref" href="#id34" name="out-value">12.5   Out value</a></h2>
1598 <p>This policy makes it possible to wrap functions that take non const references
1599 as its parameters with the intention to write return values to them.</p>
1600 <pre class="literal-block">
1601 void f(float&amp; val) { val = val + 10.f; }
1602 </pre>
1603 <p>or</p>
1604 <pre class="literal-block">
1605 void f(float* val) { *val = *val + 10.f; }
1606 </pre>
1607 <p>Can be wrapped by doing:</p>
1608 <pre class="literal-block">
1609 module(L)
1611 def(&quot;f&quot;, &amp;f, out_value(_1))
1613 </pre>
1614 <p>When invoking this function from lua it will return the value assigned to its
1615 parameter.</p>
1616 <pre class="literal-block">
1617 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1618 &gt; a = f(10)
1619 &gt; print(a)
1621 </pre>
1622 <p>When this policy is used in conjunction with user define types we often need
1623 to do ownership transfers.</p>
1624 <pre class="literal-block">
1625 struct A;
1627 void f1(A*&amp; obj) { obj = new A(); }
1628 void f2(A** obj) { *obj = new A(); }
1629 </pre>
1630 <p>Here we need to make sure luabind takes control over object returned, for
1631 this we use the adopt policy:</p>
1632 <pre class="literal-block">
1633 module(L)
1635 class_&lt;A&gt;(&quot;A&quot;),
1636 def(&quot;f1&quot;, &amp;f1, out_value(_1, adopt(_2)))
1637 def(&quot;f2&quot;, &amp;f2, out_value(_1, adopt(_2)))
1639 </pre>
1640 <p>Here we are using adopt as an internal policy to out_value. The index
1641 specified, _2, means adopt will be used to convert the value back to lua.
1642 Using _1 means the policy will be used when converting from lua to C++.</p>
1643 <p>To use this policy you need to include <tt class="literal"><span class="pre">luabind/out_value_policy.hpp</span></tt>.</p>
1644 </div>
1645 <div class="section" id="pure-out-value">
1646 <h2><a class="toc-backref" href="#id35" name="pure-out-value">12.6   Pure out value</a></h2>
1647 <p>This policy works in exactly the same way as out_value, except that it
1648 replaces the parameters with default-constructed objects.</p>
1649 <pre class="literal-block">
1650 void get(float&amp; x, float&amp; y)
1652 x = 3.f;
1653 y = 4.f;
1658 module(L)
1660 def(&quot;get&quot;, &amp;get,
1661 pure_out_value(_1) + pure_out_value(_2))
1663 </pre>
1664 <pre class="literal-block">
1665 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1666 &gt; x, y = get()
1667 &gt; print(x, y)
1669 </pre>
1670 <p>Like out_value, it is possible to specify an internal policy used then
1671 converting the values back to lua.</p>
1672 <pre class="literal-block">
1673 void get(test_class*&amp; obj)
1675 obj = new test_class();
1680 module(L)
1682 def(&quot;get&quot;, &amp;get, pure_out_value(_1, adopt(_1)))
1684 </pre>
1685 </div>
1686 <div class="section" id="discard-result">
1687 <h2><a class="toc-backref" href="#id36" name="discard-result">12.7   Discard result</a></h2>
1688 <p>This is a very simple policy which makes it possible to throw away
1689 the value returned by a C++ function, instead of converting it to
1690 lua. This example makes sure the this reference never gets converted
1691 to lua.</p>
1692 <pre class="literal-block">
1693 struct simple
1695 simple&amp; set_name(const std::string&amp; n)
1697 name = n;
1698 return *this;
1701 std::string name;
1706 module(L)
1708 class_&lt;simple&gt;(&quot;simple&quot;)
1709 .def(&quot;set_name&quot;, &amp;simple::set_name, discard_result)
1711 </pre>
1712 <p>To use this policy you need to include <tt class="literal"><span class="pre">luabind/discard_result_policy.hpp</span></tt>.</p>
1713 </div>
1714 <div class="section" id="return-stl-iterator">
1715 <h2><a class="toc-backref" href="#id37" name="return-stl-iterator">12.8   Return STL iterator</a></h2>
1716 <p>This policy converts an STL container to a generator function that can be used
1717 in lua to iterate over the container. It works on any container that defines
1718 <tt class="literal"><span class="pre">begin()</span></tt> and <tt class="literal"><span class="pre">end()</span></tt> member functions (they have to return iterators). It
1719 can be used like this:</p>
1720 <pre class="literal-block">
1721 struct A
1723 std::vector&lt;std::string&gt; names;
1727 module(L)
1729 class_&lt;A&gt;(&quot;A&quot;)
1730 .def_readwrite(&quot;names&quot;, &amp;A::names, return_stl_iterator)
1732 </pre>
1733 <p>The lua code to iterate over the container:</p>
1734 <pre class="literal-block">
1735 a = A()
1737 for name in a.names do
1738 print(name)
1740 </pre>
1741 <p>To use this policy you need to include <tt class="literal"><span class="pre">luabind/iterator_policy.hpp</span></tt>.</p>
1742 </div>
1743 <div class="section" id="yield">
1744 <h2><a class="toc-backref" href="#id38" name="yield">12.9   Yield</a></h2>
1745 <p>This policy will cause the function to always yield the current thread when
1746 returning. See the lua manual for restrictions on yield.</p>
1747 </div>
1748 </div>
1749 <div class="section" id="splitting-up-the-registration">
1750 <h1><a class="toc-backref" href="#id39" name="splitting-up-the-registration">13   Splitting up the registration</a></h1>
1751 <p>a.cpp:</p>
1752 <pre class="literal-block">
1753 luabind::scope register_a()
1755 return
1756 class_&lt;a&gt;(&quot;a&quot;)
1757 .def(&quot;f&quot;, &amp;a::f)
1760 </pre>
1761 <p>b.cpp:</p>
1762 <pre class="literal-block">
1763 luabind::scope register_b()
1765 return
1766 class_&lt;b&gt;(&quot;b&quot;)
1767 .def(&quot;g&quot;, &amp;b::g)
1770 </pre>
1771 <p>module_ab.cpp:</p>
1772 <pre class="literal-block">
1773 luabind::scope register_a();
1774 luabind::scope register_b();
1776 void register_module(lua_State* L)
1778 module(&quot;b&quot;, L)
1780 register_a(),
1781 register_b()
1784 </pre>
1785 </div>
1786 <div class="section" id="configuration">
1787 <h1><a class="toc-backref" href="#id40" name="configuration">14   Configuration</a></h1>
1788 <p>There are a number of configuration options available when building luabind.
1789 It is very important that your project has the exact same conmfiguration
1790 options as the ones given when the library was build! The exceptions are the
1791 <tt class="literal"><span class="pre">LUABIND_MAX_ARITY</span></tt> and <tt class="literal"><span class="pre">LUABIND_MAX_BASES</span></tt> which are template-based
1792 options and only matters when you use the library (which means they can
1793 differ from the settings of the library).</p>
1794 <p>The default settings which will be used if no other settings are given
1795 can be found in <tt class="literal"><span class="pre">luabind/config.hpp</span></tt>.</p>
1796 <p>If you want to change the settings of the library, you can modify the
1797 config file. It is included and used by all makefiles. You can change paths
1798 to lua and boost in there as well.</p>
1799 <dl>
1800 <dt>LUABIND_MAX_ARITY</dt>
1801 <dd>Controls the maximum arity of functions that are registered with luabind.
1802 You can't register functions that takes more parameters than the number
1803 this macro is set to. It defaults to 5, so, if your functions have greater
1804 arity you have to redefine it. A high limit will increase compilation time.</dd>
1805 <dt>LUABIND_MAX_BASES</dt>
1806 <dd>Controls the maximum number of classes one class can derive from in
1807 luabind (the number of classes specified within <tt class="literal"><span class="pre">bases&lt;&gt;</span></tt>).
1808 <tt class="literal"><span class="pre">LUABIND_MAX_BASES</span></tt> defaults to 4. A high limit will increase
1809 compilation time.</dd>
1810 <dt>LUABIND_NO_ERROR_CHECKING</dt>
1811 <dd><p class="first">If this macro is defined, all the lua code is expected only to make legal
1812 calls. If illegal function calls are made (e.g. giving parameters that
1813 doesn't match the function signature) they will not be detected by luabind
1814 and the application will probably crash. Error checking could be disabled
1815 when shipping a release build (given that no end-user has access to write
1816 custom lua code). Note that function parameter matching will be done if a
1817 function is overloaded, since otherwise it's impossible to know which one
1818 was called. Functions will still be able to throw exceptions when error
1819 checking is disabled.</p>
1820 <p class="last">If a functions throws an exception it will be caught by luabind and
1821 propagated with <tt class="literal"><span class="pre">lua_error()</span></tt>.</p>
1822 </dd>
1823 <dt>LUABIND_DONT_COPY_STRINGS</dt>
1824 <dd>If this macro is defined, luabind will expect that all strings given to
1825 the <tt class="literal"><span class="pre">def()</span></tt> functions are static constant strings (given as string
1826 constants for example). luabind will not copy the strings if you enable
1827 this setting, but just keep the char pointers.
1828 This may be especially useful for embedded systems or consoles where
1829 heap allocations should be minimized.</dd>
1830 <dt>LUABIND_NO_EXCEPTIONS</dt>
1831 <dd><p class="first">This define will disable all usage of try, catch and throw in luabind.
1832 This will in many cases disable run-time errors, when performing invalid
1833 casts or calling lua functions that fails or returns values that cannot
1834 be converted by the given policy. luabind requires that no function called
1835 directly or indirectly by luabind throws an exception (throwing exceptions
1836 through lua has undefined behavior).</p>
1837 <p class="last">Where exceptions are the only way to get an error report from luabind,
1838 they will be replaced with calls to the callback functions set with
1839 <tt class="literal"><span class="pre">set_error_callback()</span></tt> and <tt class="literal"><span class="pre">set_cast_failed_callback()</span></tt>.</p>
1840 </dd>
1841 <dt>LUA_API</dt>
1842 <dd>If you want to link dynamically against lua, you can set this define to
1843 the import-keyword on your compiler and platform. On windows in devstudio
1844 this should be <tt class="literal"><span class="pre">__declspec(dllimport)</span></tt> if you want to link against lua
1845 as a dll.</dd>
1846 <dt>LUABIND_EXPORT, LUABIND_IMPORT</dt>
1847 <dd>If you want to link against luabind as a dll (in devstudio), you can
1848 define <tt class="literal"><span class="pre">LUABIND_EXPORT</span></tt> to <tt class="literal"><span class="pre">__declspec(dllexport)</span></tt> and
1849 <tt class="literal"><span class="pre">LUABIND_IMPORT</span></tt> to <tt class="literal"><span class="pre">__declspec(dllimport)</span></tt>.
1850 Note that you have to link against lua as a dll aswell, to make it work.</dd>
1851 <dt>LUABIND_TYPE_INFO, LUABIND_TYPE_INFO_EQUAL(i1,i2), LUABIND_TYPEID(t), LUABIND_INVALID_TYPE_INFO</dt>
1852 <dd><p class="first">If you don't want to use the RTTI supplied by C++ you can supply your own
1853 type-info structure with the <tt class="literal"><span class="pre">LUABIND_TYPE_INFO</span></tt> define. Your type-info
1854 structure must be copyable and must be able to compare itself against
1855 other type-info structures. You supply the compare function through the
1856 <tt class="literal"><span class="pre">LUABIND_TYPE_INFO_EQUAL()</span></tt> define. It should compare the two type-info
1857 structures it is given and return true if they represent the same type and
1858 false otherwise. You also have to supply a function to generate your
1859 type-info structure. You do this through the <tt class="literal"><span class="pre">LUABIND_TYPEID()</span></tt> define.
1860 It should return your type-info structure and it takes a type as its
1861 parameter. That is, a compile time parameter.
1862 <tt class="literal"><span class="pre">LUABIND_INVALID_TYPE_INFO</span></tt> macro should be defined to an invalid type.
1863 No other type should be able to produce this type info. To use it you
1864 probably have to make a traits class with specializations for all classes
1865 that you have type-info for. Like this:</p>
1866 <pre class="literal-block">
1867 class A;
1868 class B;
1869 class C;
1871 template&lt;class T&gt; struct typeinfo_trait;
1873 template&lt;&gt; struct typeinfo_trait&lt;A&gt; { enum { type_id = 0 }; };
1874 template&lt;&gt; struct typeinfo_trait&lt;B&gt; { enum { type_id = 1 }; };
1875 template&lt;&gt; struct typeinfo_trait&lt;C&gt; { enum { type_id = 2 }; };
1876 </pre>
1877 <p>If you have set up your own RTTI system like this (by using integers to
1878 identify types) you can have luabind use it with the following defines:</p>
1879 <pre class="literal-block">
1880 #define LUABIND_TYPE_INFO const std::type_info*
1881 #define LUABIND_TYPEID(t) &amp;typeid(t)
1882 #define LUABIND_TYPE_INFO_EQUAL(i1, i2) *i1 == *i2
1883 #define LUABIND_INVALID_TYPE_INFO &amp;typeid(detail::null_type)
1884 </pre>
1885 <p class="last">Currently the type given through <tt class="literal"><span class="pre">LUABIND_TYPE_INFO</span></tt> must be less-than
1886 comparable!</p>
1887 </dd>
1888 <dt>NDEBUG</dt>
1889 <dd>This define will disable all asserts and should be defined in a release
1890 build.</dd>
1891 </dl>
1892 </div>
1893 <div class="section" id="implementation-notes">
1894 <h1><a class="toc-backref" href="#id41" name="implementation-notes">15   Implementation notes</a></h1>
1895 <p>The classes and objects are implemented as user data in lua. To make sure that
1896 the user data really is the internal structure it is supposed to be, we tag
1897 their metatables. A user data who's metatable contains a boolean member named
1898 <tt class="literal"><span class="pre">__luabind_classrep</span></tt> is expected to be a class exported by luabind. A user
1899 data who's metatable contains a boolean member named <tt class="literal"><span class="pre">__luabind_class</span></tt> is
1900 expected to be an instantiation of a luabind class.</p>
1901 <p>This means that if you make your own user data and tags its metatable with the
1902 exact same names, you can very easily fool luabind and crash the application.</p>
1903 <p>In the lua registry, luabind keeps an entry called <tt class="literal"><span class="pre">__luabind_classes</span></tt>. It
1904 should not be removed or overwritten.</p>
1905 <p>In the global table, a variable called <tt class="literal"><span class="pre">super</span></tt> is used every time a
1906 constructor in a lua-class is called. This is to make it easy for that
1907 constructor to call its base class' constructor. So, if you have a global
1908 variable named super it may very well be overwritten. This is probably not the
1909 best solution, and this restriction may very well be removed in the future.</p>
1910 <p>Luabind uses two upvalues for functions that it registers. The first is a
1911 userdata containing a list of overloads for the function, the other is a light
1912 userdata with the value 0x1337, this last value is used to identify functions
1913 registered by luabind. It should be virtually impossible to have such a pointer
1914 as secondary upvalue by pure chance. This means, if you are trying to replace
1915 an existing function with a luabind function, luabind will see that the
1916 secondary upvalue isn't the magic id number and replace it. If it can identify
1917 the function to be a luabind function, it won't replace it, but rather add
1918 another overload to it.</p>
1919 <p>Inside the luabind namespace, there's another namespace called detail. This
1920 namespace contains non-public classes and are not supposed to be used directly.</p>
1921 </div>
1922 <div class="section" id="error-messages">
1923 <h1><a class="toc-backref" href="#id42" name="error-messages">16   Error messages</a></h1>
1924 <ul>
1925 <li><p class="first"><cite>the attribute '&lt;class-name&gt;.&lt;attribute-name&gt;' is read only</cite></p>
1926 <blockquote>
1927 <p>There is no data member named &lt;attribute-name&gt; in the class &lt;class-name&gt;,
1928 or there's no setter-method registered on that property name. See the
1929 properties section.</p>
1930 </blockquote>
1931 </li>
1932 <li><p class="first"><cite>the attribute '&lt;class-name&gt;.&lt;attribute-name&gt;' is of type: (&lt;class-name&gt;)
1933 and does not match (&lt;class_name&gt;)</cite></p>
1934 <blockquote>
1935 <p>This error is generated if you try to assign an attribute with a value
1936 of a type that cannot be converted to the attribute's type.</p>
1937 </blockquote>
1938 </li>
1939 <li><p class="first"><cite>&lt;class-name&gt;() threw an exception, &lt;class-name&gt;:&lt;function-name&gt;() threw an
1940 exception</cite></p>
1941 <blockquote>
1942 <p>The class' constructor or member function threw an unknown exception.
1943 Known exceptions are const char*, std::exception. See the
1944 <a class="reference" href="#exceptions">exceptions</a> section.</p>
1945 </blockquote>
1946 </li>
1947 <li><p class="first"><cite>no overload of '&lt;class-name&gt;:&lt;function-name&gt;' matched the arguments
1948 (&lt;parameter-types&gt;)</cite></p>
1949 </li>
1950 <li><p class="first"><cite>no match for function call '&lt;function-name&gt;' with the parameters
1951 (&lt;parameter-types&gt;)</cite></p>
1952 </li>
1953 <li><p class="first"><cite>no constructor of &lt;class-name&gt; matched the arguments (&lt;parameter-types&gt;)</cite></p>
1954 </li>
1955 <li><p class="first"><cite>no operator &lt;operator-name&gt; matched the arguments (&lt;parameter-types&gt;)</cite></p>
1956 <blockquote>
1957 <p>No function/operator with the given name takes the parameters you gave
1958 it. You have either misspelled the function name, or given it incorrect
1959 parameters. This error is followed by a list of possible candidate
1960 functions to help you figure out what parameter has the wrong type. If
1961 the candidate list is empty there's no function at all with that name.
1962 See the signature matching section.</p>
1963 </blockquote>
1964 </li>
1965 <li><p class="first"><cite>call of overloaded '&lt;class-name&gt;:&lt;function-name&gt;(&lt;parameter-types&gt;)' is
1966 ambiguous</cite></p>
1967 </li>
1968 <li><p class="first"><cite>ambiguous match for function call '&lt;function-name&gt;' with the parameters
1969 (&lt;parameter-types&gt;)</cite></p>
1970 </li>
1971 <li><p class="first"><cite>call of overloaded constructor '&lt;class-name&gt;(&lt;parameter-types&gt;)' is
1972 ambiguous</cite></p>
1973 </li>
1974 <li><p class="first"><cite>call of overloaded operator &lt;operator-name&gt; (&lt;parameter-types&gt;) is
1975 ambiguous</cite></p>
1976 <blockquote>
1977 <p>This means that the function/operator you are trying to call has at least
1978 one other overload that matches the arguments just as good as the first
1979 overload.</p>
1980 </blockquote>
1981 </li>
1982 <li><p class="first"><cite>cannot derive from C++ class '&lt;class-name&gt;'. It does not have a wrapped
1983 type.</cite></p>
1984 <blockquote>
1985 <p>You are trying to derive a lua class from a C++ class that doesn't have a
1986 wrapped type. You have to give your C++ class a wrapped type when you
1987 register it with lua. See the deriving in lua section.</p>
1988 </blockquote>
1989 </li>
1990 <li><p class="first"><cite>derived class must call super on base</cite></p>
1991 </li>
1992 <li><p class="first"><cite>cannot set property '&lt;class-name&gt;.&lt;attribute_name&gt;' because it's read only</cite></p>
1993 <blockquote>
1994 <p>The attribute you are trying to set is registered as read only. If you want
1995 it to be writeable you have to change your class registration and use
1996 def_readwrite() instead of def_readonly(). Alternatively (if your
1997 attribute is a property with getter and setter functions), you have to
1998 give a setter function when declaring your attribute. See the properties section.</p>
1999 </blockquote>
2000 </li>
2001 <li><p class="first"><cite>no static '&lt;enum-name&gt;' in class '&lt;class-name&gt;'</cite></p>
2002 <blockquote>
2003 <p>You will get this error message if you are trying to access an enum that
2004 doesn't exist. Read about how to declare enums.</p>
2005 </blockquote>
2006 </li>
2007 <li><p class="first"><cite>expected base class</cite></p>
2008 <blockquote>
2009 <p>You have written a malformed class definition in lua. The format is: class
2010 '&lt;class-name&gt;' [&lt;base-class&gt;]. If you don't want to derive from a base
2011 class, you have to break the line directly after the class declaration.</p>
2012 </blockquote>
2013 </li>
2014 <li><p class="first"><cite>invalid construct, expected class name</cite></p>
2015 <blockquote>
2016 <p>You have written a malformed class definition in lua. The class function
2017 expects a string as argument. That string is the name of the lua class to
2018 define.</p>
2019 </blockquote>
2020 </li>
2021 </ul>
2022 </div>
2023 <div class="section" id="faq">
2024 <h1><a class="toc-backref" href="#id43" name="faq">17   FAQ</a></h1>
2025 <dl>
2026 <dt>What's up with __cdecl and __stdcall? </dt>
2027 <dd>If you're having problem with functions
2028 that cannot be converted from 'void (__stdcall <em>)(int,int)' to 'void
2029 (__cdecl</em>)(int,int)'. You can change the project settings to make the
2030 compiler generate functions with __cdecl calling conventions. This is
2031 a problem in developer studio.</dd>
2032 <dt>What's wrong with functions taking variable number of arguments?</dt>
2033 <dd>You cannot register a function with ellipses in its signature. Since
2034 ellipses don't preserve type safety, those should be avoided anyway.</dd>
2035 <dt>Internal structure overflow in VC</dt>
2036 <dd>If you, in visual studio, get fatal error C1204: compiler limit :
2037 internal structure overflow. You should try to split that compilation
2038 unit up in smaller ones.</dd>
2039 <dt>What's wrong with precompiled headers in VC?</dt>
2040 <dd>Visual Studio doesn't like anonymous namespaces in its precompiled
2041 headers. If you encounter this problem you can disable precompiled
2042 headers for the compilation unit (cpp-file) that uses luabind.</dd>
2043 <dt>error C1076: compiler limit - internal heap limit reached in VC</dt>
2044 <dd>In visual studio you will probably hit this error. To fix it you have to
2045 increase the internal heap with a command-line option. We managed to
2046 compile the test suit with /Zm300, but you may need a larger heap then
2047 that.</dd>
2048 <dt>error C1055: compiler limit <span class="classifier-delimiter">:</span> <span class="classifier">out of keys in VC</span></dt>
2049 <dd>It seems that this error occurs when too many assert() are used in a
2050 program, or more specifically, the __LINE__ macro. It seems to be fixed by
2051 changing /ZI (Program database for edit and continue) to /Zi
2052 (Program database).</dd>
2053 <dt>How come my executable is huge?</dt>
2054 <dd><p class="first">If you're compiling in debug mode, you will probably have a lot of
2055 debug-info and symbols (luabind consists of a lot of functions). Also,
2056 if built in debug mode, no optimizations were applied, luabind relies on
2057 that the compiler is able to inline functions. If you built in release
2058 mode, try running strip on your executable to remove export-symbols,
2059 this will trim down the size.</p>
2060 <p class="last">Our tests suggests that cygwin's gcc produces much bigger executables
2061 compared to gcc on other platforms and other compilers.</p>
2062 </dd>
2063 </dl>
2064 <!-- HUH?! // check the magic number that identifies luabind's functions -->
2065 <dl>
2066 <dt>Can I register class templates with luabind?</dt>
2067 <dd><p class="first">Yes you can, but you can only register explicit instantiations of the
2068 class. Because there's no lua counterpart to C++ templates. For example,
2069 you can register an explicit instantiation of std::vector&lt;&gt; like this:</p>
2070 <pre class="last literal-block">
2071 module(L)
2073 class_&lt;std::vector&lt;int&gt; &gt;(&quot;vector&quot;)
2074 .def(constructor&lt;int&gt;)
2075 .def(&quot;push_back&quot;, &amp;std::vector&lt;int&gt;::push_back)
2077 </pre>
2078 </dd>
2079 </dl>
2080 <!-- Again, irrelevant to docs: Note that the space between the two > is required by C++. -->
2081 <dl>
2082 <dt>Do I have to register destructors for my classes?</dt>
2083 <dd><p class="first">No, the destructor of a class is always called by luabind when an
2084 object is collected. Note that lua has to own the object to collect it.
2085 If you pass it to C++ and gives up ownership (with adopt policy) it will
2086 no longer be owned by lua, and not collected.</p>
2087 <p class="last">If you have a class hierarchy, you should make the destructor virtual if
2088 you want to be sure that the correct destructor is called (this apply to C++
2089 in general).</p>
2090 </dd>
2091 </dl>
2092 <!-- And again, the above is irrelevant to docs. This isn't a general C++ FAQ. -->
2093 <dl>
2094 <dt>Fatal Error C1063 compiler limit <span class="classifier-delimiter">:</span> <span class="classifier">compiler stack overflow in VC</span></dt>
2095 <dd>VC6.5 chokes on warnings, if you are getting alot of warnings from your
2096 code try suppressing them with a pragma directive, this should solve the
2097 problem.</dd>
2098 <dt>Crashes when linking against luabind as a dll in windows</dt>
2099 <dd>When you build luabind, lua and you project, make sure you link against
2100 the runtime dynamically (as a dll).</dd>
2101 <dt>I cannot register a function with a non-const parameter</dt>
2102 <dd>This is because there is no way to get a reference to a lua value. Have
2103 a look at out_value and pure_out_value policies.</dd>
2104 </dl>
2105 </div>
2106 <div class="section" id="known-issues">
2107 <h1><a class="toc-backref" href="#id44" name="known-issues">18   Known issues</a></h1>
2108 <ul class="simple">
2109 <li>You cannot use strings with extra nulls in them as member names that refers
2110 to C++ members.</li>
2111 <li>If one class registers two functions with the same name and the same
2112 signature, there's currently no error. The last registered function will
2113 be the one that's used.</li>
2114 <li>In vc7, classes can not be called test.</li>
2115 </ul>
2116 <!-- remove? - Visual studio have problems selecting the correct overload of std::swap()
2117 for luabind::object. -->
2118 <ul class="simple">
2119 <li>If you register a function and later rename it, error messages will use the
2120 original function name.</li>
2121 </ul>
2122 </div>
2123 <div class="section" id="acknowledgments">
2124 <h1><a class="toc-backref" href="#id45" name="acknowledgments">19   Acknowledgments</a></h1>
2125 <p>This library was written by Daniel Wallin and Arvid Norberg. © Copyright 2003.
2126 All rights reserved.</p>
2127 <p>This library was inspired by Dave Abrahams' Boost.Python library which can be
2128 found in the <a class="reference" href="http://www.boost.org">boost</a> library.</p>
2129 <p>Evan Wies has contributed with thorough testing and countless bug reports and
2130 feature ideas.</p>
2131 </div>
2132 </div>
2133 </body>
2134 </html>