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