docs.rst 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629
  1. .. include:: version.rst
  2. +++++++++++++++++++
  3. luabind |version|
  4. +++++++++++++++++++
  5. :Author: Daniel Wallin, Arvid Norberg
  6. :Copyright: Copyright Daniel Wallin, Arvid Norberg 2003.
  7. :License: Permission is hereby granted, free of charge, to any person obtaining a
  8. copy of this software and associated documentation files (the "Software"),
  9. to deal in the Software without restriction, including without limitation
  10. the rights to use, copy, modify, merge, publish, distribute, sublicense,
  11. and/or sell copies of the Software, and to permit persons to whom the
  12. Software is furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included
  14. in all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
  16. ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  17. TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  18. PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  19. SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  20. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  21. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
  23. OR OTHER DEALINGS IN THE SOFTWARE.
  24. .. _MIT license: http://www.opensource.org/licenses/mit-license.php
  25. .. _Boost: http://www.boost.org
  26. .. contents::
  27. :depth: 2
  28. :backlinks: none
  29. .. section-numbering::
  30. .. |...| unicode:: U+02026
  31. Introduction
  32. ============
  33. Luabind is a library that helps you create bindings between C++ and Lua. It has
  34. the ability to expose functions and classes, written in C++, to Lua. It will
  35. also supply the functionality to define classes in Lua and let them derive from
  36. other Lua classes or C++ classes. Lua classes can override virtual functions
  37. from their C++ base classes. It is written towards Lua 5.0, and does not work
  38. with Lua 4.
  39. It is implemented utilizing template meta programming. That means that you
  40. don't need an extra preprocess pass to compile your project (it is done by the
  41. compiler). It also means you don't (usually) have to know the exact signature
  42. of each function you register, since the library will generate code depending
  43. on the compile-time type of the function (which includes the signature). The
  44. main drawback of this approach is that the compilation time will increase for
  45. the file that does the registration, it is therefore recommended that you
  46. register everything in the same cpp-file.
  47. Luabind is released under the terms of the `MIT license`_.
  48. We are very interested in hearing about projects that use luabind, please let
  49. us know about your project.
  50. The main channel for help and feedback is the `luabind mailing list`_.
  51. There's also an IRC channel ``#luabind`` on irc.freenode.net.
  52. .. _`luabind mailing list`: https://lists.sourceforge.net/lists/listinfo/luabind-user
  53. Features
  54. ========
  55. Luabind supports:
  56. - Overloaded free functions
  57. - C++ classes in Lua
  58. - Overloaded member functions
  59. - Operators
  60. - Properties
  61. - Enums
  62. - Lua functions in C++
  63. - Lua classes in C++
  64. - Lua classes (single inheritance)
  65. - Derives from Lua or C++ classes
  66. - Override virtual functions from C++ classes
  67. - Implicit casts between registered types
  68. - Best match signature matching
  69. - Return value policies and parameter policies
  70. Portability
  71. ===========
  72. Luabind has been tested to work on the following compilers:
  73. - Visual Studio 7.1
  74. - Intel C++ 6.0 (Windows)
  75. - GCC 2.95.3 (cygwin)
  76. - GCC 3.0.4 (Debian/Linux)
  77. - GCC 3.1 (SunOS 5.8)
  78. - GCC 3.2 (cygwin)
  79. - GCC 3.3.1 (cygwin)
  80. - GCC 3.3 (Apple, MacOS X)
  81. - GCC 4.0 (Apple, MacOS X)
  82. It has been confirmed not to work with:
  83. - GCC 2.95.2 (SunOS 5.8)
  84. Metrowerks 8.3 (Windows) compiles but fails the const-test. This
  85. means that const member functions are treated as non-const member
  86. functions.
  87. If you have tried luabind with a compiler not listed here, let us know
  88. your result with it.
  89. .. include:: building.rst
  90. Basic usage
  91. ===========
  92. To use luabind, you must include ``lua.h`` and luabind's main header file::
  93. extern "C"
  94. {
  95. #include "lua.h"
  96. }
  97. #include <luabind/luabind.hpp>
  98. This includes support for both registering classes and functions. If you just
  99. want to have support for functions or classes you can include
  100. ``luabind/function.hpp`` and ``luabind/class.hpp`` separately::
  101. #include <luabind/function.hpp>
  102. #include <luabind/class.hpp>
  103. The first thing you need to do is to call ``luabind::open(lua_State*)`` which
  104. will register the functions to create classes from Lua, and initialize some
  105. state-global structures used by luabind. If you don't call this function you
  106. will hit asserts later in the library. There is no corresponding close function
  107. because once a class has been registered in Lua, there really isn't any good
  108. way to remove it. Partly because any remaining instances of that class relies
  109. on the class being there. Everything will be cleaned up when the state is
  110. closed though.
  111. .. Isn't this wrong? Don't we include lua.h using lua_include.hpp ?
  112. Luabind's headers will never include ``lua.h`` directly, but through
  113. ``<luabind/lua_include.hpp>``. If you for some reason need to include another
  114. Lua header, you can modify this file.
  115. Hello world
  116. -----------
  117. ::
  118. #include <iostream>
  119. #include <luabind/luabind.hpp>
  120. void greet()
  121. {
  122. std::cout << "hello world!\n";
  123. }
  124. extern "C" int init(lua_State* L)
  125. {
  126. using namespace luabind;
  127. open(L);
  128. module(L)
  129. [
  130. def("greet", &greet)
  131. ];
  132. return 0;
  133. }
  134. ::
  135. Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
  136. > loadlib('hello_world.dll', 'init')()
  137. > greet()
  138. Hello world!
  139. >
  140. Scopes
  141. ======
  142. Everything that gets registered in Lua is registered in a namespace (Lua
  143. tables) or in the global scope (called module). All registrations must be
  144. surrounded by its scope. To define a module, the ``luabind::module`` class is
  145. used. It is used like this::
  146. module(L)
  147. [
  148. // declarations
  149. ];
  150. This will register all declared functions or classes in the global namespace in
  151. Lua. If you want to have a namespace for your module (like the standard
  152. libraries) you can give a name to the constructor, like this::
  153. module(L, "my_library")
  154. [
  155. // declarations
  156. ];
  157. Here all declarations will be put in the my_library table.
  158. If you want nested namespace's you can use the ``luabind::namespace_`` class. It
  159. works exactly as ``luabind::module`` except that it doesn't take a lua_State*
  160. in it's constructor. An example of its usage could look like this::
  161. module(L, "my_library")
  162. [
  163. // declarations
  164. namespace_("detail")
  165. [
  166. // library-private declarations
  167. ]
  168. ];
  169. As you might have figured out, the following declarations are equivalent::
  170. module(L)
  171. [
  172. namespace_("my_library")
  173. [
  174. // declarations
  175. ]
  176. ];
  177. ::
  178. module(L, "my_library")
  179. [
  180. // declarations
  181. ];
  182. Each declaration must be separated by a comma, like this::
  183. module(L)
  184. [
  185. def("f", &f),
  186. def("g", &g),
  187. class_<A>("A")
  188. .def(constructor<int, int>),
  189. def("h", &h)
  190. ];
  191. More about the actual declarations in the `Binding functions to Lua`_ and
  192. `Binding classes to Lua`_ sections.
  193. A word of caution, if you are in really bad need for performance, putting your
  194. functions in tables will increase the lookup time.
  195. Binding functions to Lua
  196. ========================
  197. To bind functions to Lua you use the function ``luabind::def()``. It has the
  198. following synopsis::
  199. template<class F, class policies>
  200. void def(const char* name, F f, const Policies&);
  201. - name is the name the function will have within Lua.
  202. - F is the function pointer you want to register.
  203. - The Policies parameter is used to describe how parameters and return values
  204. are treated by the function, this is an optional parameter. More on this in
  205. the `policies`_ section.
  206. An example usage could be if you want to register the function ``float
  207. std::sin(float)``::
  208. module(L)
  209. [
  210. def("sin", &std::sin)
  211. ];
  212. Overloaded functions
  213. --------------------
  214. If you have more than one function with the same name, and want to register
  215. them in Lua, you have to explicitly give the signature. This is to let C++ know
  216. which function you refer to. For example, if you have two functions, ``int
  217. f(const char*)`` and ``void f(int)``. ::
  218. module(L)
  219. [
  220. def("f", (int(*)(const char*)) &f),
  221. def("f", (void(*)(int)) &f)
  222. ];
  223. Signature matching
  224. ------------------
  225. luabind will generate code that checks the Lua stack to see if the values there
  226. can match your functions' signatures. It will handle implicit typecasts between
  227. derived classes, and it will prefer matches with the least number of implicit
  228. casts. In a function call, if the function is overloaded and there's no
  229. overload that match the parameters better than the other, you have an
  230. ambiguity. This will spawn a run-time error, stating that the function call is
  231. ambiguous. A simple example of this is to register one function that takes an
  232. int and one that takes a float. Since Lua doesn't distinguish between floats and
  233. integers, both will always match.
  234. Since all overloads are tested, it will always find the best match (not the
  235. first match). This also means that it can handle situations where the only
  236. difference in the signature is that one member function is const and the other
  237. isn't.
  238. .. sidebar:: Ownership transfer
  239. To correctly handle ownership transfer, create_a() would need an adopt
  240. return value policy. More on this in the `Policies`_ section.
  241. For example, if the following function and class is registered:
  242. ::
  243. struct A
  244. {
  245. void f();
  246. void f() const;
  247. };
  248. const A* create_a();
  249. struct B: A {};
  250. struct C: B {};
  251. void g(A*);
  252. void g(B*);
  253. And the following Lua code is executed::
  254. a1 = create_a()
  255. a1:f() -- the const version is called
  256. a2 = A()
  257. a2:f() -- the non-const version is called
  258. a = A()
  259. b = B()
  260. c = C()
  261. g(a) -- calls g(A*)
  262. g(b) -- calls g(B*)
  263. g(c) -- calls g(B*)
  264. Calling Lua functions
  265. ---------------------
  266. To call a Lua function, you can either use ``call_function()`` or
  267. an ``object``.
  268. ::
  269. template<class Ret>
  270. Ret call_function(lua_State* L, const char* name, ...)
  271. template<class Ret>
  272. Ret call_function(object const& obj, ...)
  273. There are two overloads of the ``call_function`` function, one that calls
  274. a function given its name, and one that takes an object that should be a Lua
  275. value that can be called as a function.
  276. The overload that takes a name can only call global Lua functions. The ...
  277. represents a variable number of parameters that are sent to the Lua
  278. function. This function call may throw ``luabind::error`` if the function
  279. call fails.
  280. The return value isn't actually Ret (the template parameter), but a proxy
  281. object that will do the function call. This enables you to give policies to the
  282. call. You do this with the operator[]. You give the policies within the
  283. brackets, like this::
  284. int ret = call_function<int>(
  285. L
  286. , "a_lua_function"
  287. , new complex_class()
  288. )[ adopt(_1) ];
  289. If you want to pass a parameter as a reference, you have to wrap it with the
  290. `Boost.Ref`__.
  291. __ http://www.boost.org/doc/html/ref.html
  292. Like this::
  293. int ret = call_function(L, "fun", boost::ref(val));
  294. If you want to use a custom error handler for the function call, see
  295. ``set_pcall_callback`` under `pcall errorfunc`_.
  296. Using Lua threads
  297. -----------------
  298. To start a Lua thread, you have to call ``lua_resume()``, this means that you
  299. cannot use the previous function ``call_function()`` to start a thread. You have
  300. to use
  301. ::
  302. template<class Ret>
  303. Ret resume_function(lua_State* L, const char* name, ...)
  304. template<class Ret>
  305. Ret resume_function(object const& obj, ...)
  306. and
  307. ::
  308. template<class Ret>
  309. Ret resume(lua_State* L, ...)
  310. The first time you start the thread, you have to give it a function to execute. i.e. you
  311. have to use ``resume_function``, when the Lua function yields, it will return the first
  312. value passed in to ``lua_yield()``. When you want to continue the execution, you just call
  313. ``resume()`` on your ``lua_State``, since it's already executing a function, you don't pass
  314. it one. The parameters to ``resume()`` will be returned by ``yield()`` on the Lua side.
  315. For yielding C++-functions (without the support of passing data back and forth between the
  316. Lua side and the c++ side), you can use the yield_ policy.
  317. With the overload of ``resume_function`` that takes an object_, it is important that the
  318. object was constructed with the thread as its ``lua_State*``. Like this:
  319. .. parsed-literal::
  320. lua_State* thread = lua_newthread(L);
  321. object fun = get_global(**thread**)["my_thread_fun"];
  322. resume_function(fun);
  323. Binding classes to Lua
  324. ======================
  325. To register classes you use a class called ``class_``. Its name is supposed to
  326. resemble the C++ keyword, to make it look more intuitive. It has an overloaded
  327. member function ``def()`` that is used to register member functions, operators,
  328. constructors, enums and properties on the class. It will return its
  329. this-pointer, to let you register more members directly.
  330. Let's start with a simple example. Consider the following C++ class::
  331. class testclass
  332. {
  333. public:
  334. testclass(const std::string& s): m_string(s) {}
  335. void print_string() { std::cout << m_string << "\n"; }
  336. private:
  337. std::string m_string;
  338. };
  339. To register it with a Lua environment, write as follows (assuming you are using
  340. namespace luabind)::
  341. module(L)
  342. [
  343. class_<testclass>("testclass")
  344. .def(constructor<const std::string&>())
  345. .def("print_string", &testclass::print_string)
  346. ];
  347. This will register the class with the name testclass and constructor that takes
  348. a string as argument and one member function with the name ``print_string``.
  349. ::
  350. Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
  351. > a = testclass('a string')
  352. > a:print_string()
  353. a string
  354. It is also possible to register free functions as member functions. The
  355. requirement on the function is that it takes a pointer, const pointer,
  356. reference or const reference to the class type as the first parameter. The rest
  357. of the parameters are the ones that are visible in Lua, while the object
  358. pointer is given as the first parameter. If we have the following C++ code::
  359. struct A
  360. {
  361. int a;
  362. };
  363. int plus(A* o, int v) { return o->a + v; }
  364. You can register ``plus()`` as if it was a member function of A like this::
  365. class_<A>("A")
  366. .def("plus", &plus)
  367. ``plus()`` can now be called as a member function on A with one parameter, int.
  368. If the object pointer parameter is const, the function will act as if it was a
  369. const member function (it can be called on const objects).
  370. Overloaded member functions
  371. ---------------------------
  372. When binding more than one overloads of a member function, or just binding
  373. one overload of an overloaded member function, you have to disambiguate
  374. the member function pointer you pass to ``def``. To do this, you can use an
  375. ordinary C-style cast, to cast it to the right overload. To do this, you have
  376. to know how to express member function types in C++, here's a short tutorial
  377. (for more info, refer to your favorite book on C++).
  378. The syntax for member function pointer follows:
  379. .. parsed-literal::
  380. *return-value* (*class-name*::\*)(*arg1-type*, *arg2-type*, *...*)
  381. Here's an example illlustrating this::
  382. struct A
  383. {
  384. void f(int);
  385. void f(int, int);
  386. };
  387. ::
  388. class_<A>()
  389. .def("f", (void(A::*)(int))&A::f)
  390. This selects the first overload of the function ``f`` to bind. The second
  391. overload is not bound.
  392. Properties
  393. ----------
  394. To register a global data member with a class is easily done. Consider the
  395. following class::
  396. struct A
  397. {
  398. int a;
  399. };
  400. This class is registered like this::
  401. module(L)
  402. [
  403. class_<A>("A")
  404. .def_readwrite("a", &A::a)
  405. ];
  406. This gives read and write access to the member variable ``A::a``. It is also
  407. possible to register attributes with read-only access::
  408. module(L)
  409. [
  410. class_<A>("A")
  411. .def_readonly("a", &A::a)
  412. ];
  413. When binding members that are a non-primitive type, the auto generated getter
  414. function will return a reference to it. This is to allow chained .-operators.
  415. For example, when having a struct containing another struct. Like this::
  416. struct A { int m; };
  417. struct B { A a; };
  418. When binding ``B`` to lua, the following expression code should work::
  419. b = B()
  420. b.a.m = 1
  421. assert(b.a.m == 1)
  422. This requires the first lookup (on ``a``) to return a reference to ``A``, and
  423. not a copy. In that case, luabind will automatically use the dependency policy
  424. to make the return value dependent on the object in which it is stored. So, if
  425. the returned reference lives longer than all references to the object (b in
  426. this case) it will keep the object alive, to avoid being a dangling pointer.
  427. You can also register getter and setter functions and make them look as if they
  428. were a public data member. Consider the following class::
  429. class A
  430. {
  431. public:
  432. void set_a(int x) { a = x; }
  433. int get_a() const { return a; }
  434. private:
  435. int a;
  436. };
  437. It can be registered as if it had a public data member a like this::
  438. class_<A>("A")
  439. .property("a", &A::get_a, &A::set_a)
  440. This way the ``get_a()`` and ``set_a()`` functions will be called instead of
  441. just writing to the data member. If you want to make it read only you can just
  442. omit the last parameter. Please note that the get function **has to be
  443. const**, otherwise it won't compile. This seems to be a common source of errors.
  444. Enums
  445. -----
  446. If your class contains enumerated constants (enums), you can register them as
  447. well to make them available in Lua. Note that they will not be type safe, all
  448. enums are integers in Lua, and all functions that takes an enum, will accept
  449. any integer. You register them like this::
  450. module(L)
  451. [
  452. class_<A>("A")
  453. .enum_("constants")
  454. [
  455. value("my_enum", 4),
  456. value("my_2nd_enum", 7),
  457. value("another_enum", 6)
  458. ]
  459. ];
  460. In Lua they are accessed like any data member, except that they are read-only
  461. and reached on the class itself rather than on an instance of the class.
  462. ::
  463. Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
  464. > print(A.my_enum)
  465. 4
  466. > print(A.another_enum)
  467. 6
  468. Operators
  469. ---------
  470. To bind operators you have to include ``<luabind/operator.hpp>``.
  471. The mechanism for registering operators on your class is pretty simple. You use
  472. a global name ``luabind::self`` to refer to the class itself and then you just
  473. write the operator expression inside the ``def()`` call. This class::
  474. struct vec
  475. {
  476. vec operator+(int s);
  477. };
  478. Is registered like this:
  479. .. parsed-literal::
  480. module(L)
  481. [
  482. class_<vec>("vec")
  483. .def(**self + int()**)
  484. ];
  485. This will work regardless if your plus operator is defined inside your class or
  486. as a free function.
  487. If your operator is const (or, when defined as a free function, takes a const
  488. reference to the class itself) you have to use ``const_self`` instead of
  489. ``self``. Like this:
  490. .. parsed-literal::
  491. module(L)
  492. [
  493. class_<vec>("vec")
  494. .def(**const_self** + int())
  495. ];
  496. The operators supported are those available in Lua:
  497. .. parsed-literal::
  498. + - \* / == < <=
  499. This means, no in-place operators. The equality operator (``==``) has a little
  500. hitch; it will not be called if the references are equal. This means that the
  501. ``==`` operator has to do pretty much what's it's expected to do.
  502. Lua does not support operators such as ``!=``, ``>`` or ``>=``. That's why you
  503. can only register the operators listed above. When you invoke one of the
  504. mentioned operators, lua will define it in terms of one of the available
  505. operators.
  506. In the above example the other operand type is instantiated by writing
  507. ``int()``. If the operand type is a complex type that cannot easily be
  508. instantiated you can wrap the type in a class called ``other<>``. For example:
  509. To register this class, we don't want to instantiate a string just to register
  510. the operator.
  511. ::
  512. struct vec
  513. {
  514. vec operator+(std::string);
  515. };
  516. Instead we use the ``other<>`` wrapper like this:
  517. .. parsed-literal::
  518. module(L)
  519. [
  520. class_<vec>("vec")
  521. .def(self + **other<std::string>()**)
  522. ];
  523. To register an application (function call-) operator:
  524. .. parsed-literal::
  525. module(L)
  526. [
  527. class_<vec>("vec")
  528. .def( **self(int())** )
  529. ];
  530. There's one special operator. In Lua it's called ``__tostring``, it's not
  531. really an operator. It is used for converting objects to strings in a standard
  532. way in Lua. If you register this functionality, you will be able to use the lua
  533. standard function ``tostring()`` for converting your object to a string.
  534. To implement this operator in C++ you should supply an ``operator<<`` for
  535. std::ostream. Like this example:
  536. .. parsed-literal::
  537. class number {};
  538. std::ostream& operator<<(std::ostream&, number&);
  539. ...
  540. module(L)
  541. [
  542. class_<number>("number")
  543. .def(**tostring(self)**)
  544. ];
  545. Nested scopes and static functions
  546. ----------------------------------
  547. It is possible to add nested scopes to a class. This is useful when you need
  548. to wrap a nested class, or a static function.
  549. .. parsed-literal::
  550. class_<foo>("foo")
  551. .def(constructor<>())
  552. **.scope
  553. [
  554. class_<inner>("nested"),
  555. def("f", &f)
  556. ]**;
  557. In this example, ``f`` will behave like a static member function of the class
  558. ``foo``, and the class ``nested`` will behave like a nested class of ``foo``.
  559. It's also possible to add namespaces to classes using the same syntax.
  560. Derived classes
  561. ---------------
  562. If you want to register classes that derives from other classes, you can
  563. specify a template parameter ``bases<>`` to the ``class_`` instantiation. The
  564. following hierarchy::
  565. struct A {};
  566. struct B : A {};
  567. Would be registered like this::
  568. module(L)
  569. [
  570. class_<A>("A"),
  571. class_<B, A>("B")
  572. ];
  573. If you have multiple inheritance you can specify more than one base. If B would
  574. also derive from a class C, it would be registered like this::
  575. module(L)
  576. [
  577. class_<B, bases<A, C> >("B")
  578. ];
  579. Note that you can omit ``bases<>`` when using single inheritance.
  580. .. note::
  581. If you don't specify that classes derive from each other, luabind will not
  582. be able to implicitly cast pointers between the types.
  583. Smart pointers
  584. --------------
  585. When registering a class you can tell luabind to hold all instances
  586. explicitly created in Lua in a specific smart pointer type, rather than
  587. the default raw pointer. This is done by passing an additional template
  588. parameter to ``class_``:
  589. .. parsed-literal::
  590. class_<X, **P**>(|...|)
  591. Where the requirements of ``P`` are:
  592. ======================== =======================================
  593. Expression Returns
  594. ======================== =======================================
  595. ``P(raw)``
  596. ``get_pointer(p)`` Convertible to ``X*``
  597. ======================== =======================================
  598. where:
  599. * ``raw`` is of type ``X*``
  600. * ``p`` is an instance of ``P``
  601. ``get_pointer()`` overloads are provided for the smart pointers in
  602. Boost, and ``std::auto_ptr<>``. Should you need to provide your own
  603. overload, note that it is called unqualified and is expected to be found
  604. by *argument dependent lookup*. Thus it should be defined in the same
  605. namespace as the pointer type it operates on.
  606. For example:
  607. .. parsed-literal::
  608. class_<X, **boost::scoped_ptr<X>** >("X")
  609. .def(constructor<>())
  610. Will cause luabind to hold any instance created on the Lua side in a
  611. ``boost::scoped_ptr<X>``. Note that this doesn't mean **all** instances
  612. will be held by a ``boost::scoped_ptr<X>``. If, for example, you
  613. register a function::
  614. std::auto_ptr<X> make_X();
  615. the instance returned by that will be held in ``std::auto_ptr<X>``. This
  616. is handled automatically for all smart pointers that implement a
  617. ``get_pointer()`` overload.
  618. .. important::
  619. ``get_const_holder()`` has been removed. Automatic conversions
  620. between ``smart_ptr<X>`` and ``smart_ptr<X const>`` no longer work.
  621. .. important::
  622. ``__ok`` has been removed. Similar functionality can be implemented
  623. for specific pointer types by doing something along the lines of:
  624. .. parsed-literal::
  625. bool is_non_null(std::auto_ptr<X> const& p)
  626. {
  627. return p.get();
  628. }
  629. |...|
  630. def("is_non_null", &is_non_null)
  631. When registering a hierarchy of classes, where all instances are to be held
  632. by a smart pointer, all the classes should have the baseclass' holder type.
  633. Like this:
  634. .. parsed-literal::
  635. module(L)
  636. [
  637. class_<base, boost::shared_ptr<base> >("base")
  638. .def(constructor<>()),
  639. class_<derived, base, **boost::shared_ptr<base>** >("derived")
  640. .def(constructor<>())
  641. ];
  642. Internally, luabind will do the necessary conversions on the raw pointers, which
  643. are first extracted from the holder type.
  644. Splitting class registrations
  645. -----------------------------
  646. In some situations it may be desirable to split a registration of a class
  647. across different compilation units. Partly to save rebuild time when changing
  648. in one part of the binding, and in some cases compiler limits may force you
  649. to split it. To do this is very simple. Consider the following sample code::
  650. void register_part1(class_<X>& x)
  651. {
  652. x.def(/*...*/);
  653. }
  654. void register_part2(class_<X>& x)
  655. {
  656. x.def(/*...*/);
  657. }
  658. void register_(lua_State* L)
  659. {
  660. class_<X> x("x");
  661. register_part1(x);
  662. register_part2(x);
  663. module(L) [ x ];
  664. }
  665. Here, the class ``X`` is registered in two steps. The two functions
  666. ``register_part1`` and ``register_part2`` may be put in separate compilation
  667. units.
  668. To separate the module registration and the classes to be registered, see
  669. `Splitting up the registration`_.
  670. Adding converters for user defined types
  671. ========================================
  672. It is possible to get luabind to handle user defined types like it does
  673. the built in types by specializing ``luabind::default_converter<>``:
  674. ::
  675. struct int_wrapper
  676. {
  677. int_wrapper(int value)
  678. : value(value)
  679. {}
  680. int value;
  681. };
  682. namespace luabind
  683. {
  684. template <>
  685. struct default_converter<X>
  686. : native_converter_base<X>
  687. {
  688. static int compute_score(lua_State* L, int index)
  689. {
  690. return lua_type(L, index) == LUA_TNUMBER ? 0 : -1;
  691. }
  692. X from(lua_State* L, int index)
  693. {
  694. return X(lua_tonumber(L, index));
  695. }
  696. void to(lua_State* L, X const& x)
  697. {
  698. lua_pushnumber(L, x.value);
  699. }
  700. };
  701. template <>
  702. struct default_converter<X const&>
  703. : default_converter<X>
  704. {};
  705. }
  706. Note that ``default_converter<>`` is instantiated for the actual argument and
  707. return types of the bound functions. In the above example, we add a
  708. specialization for ``X const&`` that simply forwards to the ``X`` converter.
  709. This lets us export functions which accept ``X`` by const reference.
  710. ``native_converter_base<>`` should be used as the base class for the
  711. specialized converters. It simplifies the converter interface, and
  712. provides a mean for backward compatibility since the underlying
  713. interface is in flux.
  714. Binding function objects with explicit signatures
  715. =================================================
  716. Using ``luabind::tag_function<>`` it is possible to export function objects
  717. from which luabind can't automatically deduce a signature. This can be used to
  718. slightly alter the signature of a bound function, or even to bind stateful
  719. function objects.
  720. Synopsis:
  721. .. parsed-literal::
  722. template <class Signature, class F>
  723. *implementation-defined* tag_function(F f);
  724. Where ``Signature`` is a function type describing the signature of ``F``.
  725. It can be used like this::
  726. int f(int x);
  727. // alter the signature so that the return value is ignored
  728. def("f", tag_function<void(int)>(f));
  729. struct plus
  730. {
  731. plus(int x)
  732. : x(x)
  733. {}
  734. int operator()(int y) const
  735. {
  736. return x + y;
  737. }
  738. };
  739. // bind a stateful function object
  740. def("plus3", tag_function<int(int)>(plus(3)));
  741. Object
  742. ======
  743. Since functions have to be able to take Lua values (of variable type) we need a
  744. wrapper around them. This wrapper is called ``luabind::object``. If the
  745. function you register takes an object, it will match any Lua value. To use it,
  746. you need to include ``<luabind/object.hpp>``.
  747. .. topic:: Synopsis
  748. .. parsed-literal::
  749. class object
  750. {
  751. public:
  752. template<class T>
  753. object(lua_State\*, T const& value);
  754. object(from_stack const&);
  755. object(object const&);
  756. object();
  757. ~object();
  758. lua_State\* interpreter() const;
  759. void push() const;
  760. bool is_valid() const;
  761. operator *safe_bool_type* () const;
  762. template<class Key>
  763. *implementation-defined* operator[](Key const&);
  764. template<class T>
  765. object& operator=(T const&);
  766. object& operator=(object const&);
  767. bool operator==(object const&) const;
  768. bool operator<(object const&) const;
  769. bool operator<=(object const&) const;
  770. bool operator>(object const&) const;
  771. bool operator>=(object const&) const;
  772. bool operator!=(object const&) const;
  773. template <class T>
  774. *implementation-defined* operator[](T const& key) const
  775. void swap(object&);
  776. *implementation-defined* operator()();
  777. template<class A0>
  778. *implementation-defined* operator()(A0 const& a0);
  779. template<class A0, class A1>
  780. *implementation-defined* operator()(A0 const& a0, A1 const& a1);
  781. /\* ... \*/
  782. };
  783. When you have a Lua object, you can assign it a new value with the assignment
  784. operator (=). When you do this, the ``default_policy`` will be used to make the
  785. conversion from C++ value to Lua. If your ``luabind::object`` is a table you
  786. can access its members through the operator[] or the Iterators_. The value
  787. returned from the operator[] is a proxy object that can be used both for
  788. reading and writing values into the table (using operator=).
  789. Note that it is impossible to know if a Lua value is indexable or not
  790. (``lua_gettable`` doesn't fail, it succeeds or crashes). This means that if
  791. you're trying to index something that cannot be indexed, you're on your own.
  792. Lua will call its ``panic()`` function. See `lua panic`_.
  793. There are also free functions that can be used for indexing the table, see
  794. `Related functions`_.
  795. The constructor that takes a ``from_stack`` object is used when you want to
  796. initialize the object with a value from the lua stack. The ``from_stack``
  797. type has the following constructor::
  798. from_stack(lua_State* L, int index);
  799. The index is an ordinary lua stack index, negative values are indexed from the
  800. top of the stack. You use it like this::
  801. object o(from_stack(L, -1));
  802. This will create the object ``o`` and copy the value from the top of the lua stack.
  803. The ``interpreter()`` function returns the Lua state where this object is stored.
  804. If you want to manipulate the object with Lua functions directly you can push
  805. it onto the Lua stack by calling ``push()``.
  806. The operator== will call lua_equal() on the operands and return its result.
  807. The ``is_valid()`` function tells you whether the object has been initialized
  808. or not. When created with its default constructor, objects are invalid. To make
  809. an object valid, you can assign it a value. If you want to invalidate an object
  810. you can simply assign it an invalid object.
  811. The ``operator safe_bool_type()`` is equivalent to ``is_valid()``. This means
  812. that these snippets are equivalent::
  813. object o;
  814. // ...
  815. if (o)
  816. {
  817. // ...
  818. }
  819. ...
  820. object o;
  821. // ...
  822. if (o.is_valid())
  823. {
  824. // ...
  825. }
  826. The application operator will call the value as if it was a function. You can
  827. give it any number of parameters (currently the ``default_policy`` will be used
  828. for the conversion). The returned object refers to the return value (currently
  829. only one return value is supported). This operator may throw ``luabind::error``
  830. if the function call fails. If you want to specify policies to your function
  831. call, you can use index-operator (operator[]) on the function call, and give
  832. the policies within the [ and ]. Like this::
  833. my_function_object(
  834. 2
  835. , 8
  836. , new my_complex_structure(6)
  837. ) [ adopt(_3) ];
  838. This tells luabind to make Lua adopt the ownership and responsibility for the
  839. pointer passed in to the lua-function.
  840. It's important that all instances of object have been destructed by the time
  841. the Lua state is closed. The object will keep a pointer to the lua state and
  842. release its Lua object in its destructor.
  843. Here's an example of how a function can use a table::
  844. void my_function(object const& table)
  845. {
  846. if (type(table) == LUA_TTABLE)
  847. {
  848. table["time"] = std::clock();
  849. table["name"] = std::rand() < 500 ? "unusual" : "usual";
  850. std::cout << object_cast<std::string>(table[5]) << "\n";
  851. }
  852. }
  853. If you take a ``luabind::object`` as a parameter to a function, any Lua value
  854. will match that parameter. That's why we have to make sure it's a table before
  855. we index into it.
  856. ::
  857. std::ostream& operator<<(std::ostream&, object const&);
  858. There's a stream operator that makes it possible to print objects or use
  859. ``boost::lexical_cast`` to convert it to a string. This will use lua's string
  860. conversion function. So if you convert a C++ object with a ``tostring``
  861. operator, the stream operator for that type will be used.
  862. Iterators
  863. ---------
  864. There are two kinds of iterators. The normal iterator that will use the metamethod
  865. of the object (if there is any) when the value is retrieved. This iterator is simply
  866. called ``luabind::iterator``. The other iterator is called ``luabind::raw_iterator``
  867. and will bypass the metamethod and give the true contents of the table. They have
  868. identical interfaces, which implements the ForwardIterator_ concept. Apart from
  869. the members of standard iterators, they have the following members and constructors:
  870. .. _ForwardIterator: http://www.sgi.com/tech/stl/ForwardIterator.html
  871. .. parsed-literal::
  872. class iterator
  873. {
  874. iterator();
  875. iterator(object const&);
  876. object key() const;
  877. *standard iterator members*
  878. };
  879. The constructor that takes a ``luabind::object`` is actually a template that can be
  880. used with object. Passing an object as the parameter to the iterator will
  881. construct the iterator to refer to the first element in the object.
  882. The default constructor will initialize the iterator to the one-past-end
  883. iterator. This is used to test for the end of the sequence.
  884. The value type of the iterator is an implementation defined proxy type which
  885. supports the same operations as ``luabind::object``. Which means that in most
  886. cases you can just treat it as an ordinary object. The difference is that any
  887. assignments to this proxy will result in the value being inserted at the
  888. iterators position, in the table.
  889. The ``key()`` member returns the key used by the iterator when indexing the
  890. associated Lua table.
  891. An example using iterators::
  892. for (iterator i(globals(L)["a"]), end; i != end; ++i)
  893. {
  894. *i = 1;
  895. }
  896. The iterator named ``end`` will be constructed using the default constructor
  897. and hence refer to the end of the sequence. This example will simply iterate
  898. over the entries in the global table ``a`` and set all its values to 1.
  899. Related functions
  900. -----------------
  901. There are a couple of functions related to objects and tables.
  902. ::
  903. int type(object const&);
  904. This function will return the lua type index of the given object.
  905. i.e. ``LUA_TNIL``, ``LUA_TNUMBER`` etc.
  906. ::
  907. template<class T, class K>
  908. void settable(object const& o, K const& key, T const& value);
  909. template<class K>
  910. object gettable(object const& o, K const& key);
  911. template<class T, class K>
  912. void rawset(object const& o, K const& key, T const& value);
  913. template<class K>
  914. object rawget(object const& o, K const& key);
  915. These functions are used for indexing into tables. ``settable`` and ``gettable``
  916. translates into calls to ``lua_settable`` and ``lua_gettable`` respectively. Which
  917. means that you could just as well use the index operator of the object.
  918. ``rawset`` and ``rawget`` will translate into calls to ``lua_rawset`` and
  919. ``lua_rawget`` respectively. So they will bypass any metamethod and give you the
  920. true value of the table entry.
  921. ::
  922. template<class T>
  923. T object_cast<T>(object const&);
  924. template<class T, class Policies>
  925. T object_cast<T>(object const&, Policies);
  926. template<class T>
  927. boost::optional<T> object_cast_nothrow<T>(object const&);
  928. template<class T, class Policies>
  929. boost::optional<T> object_cast_nothrow<T>(object const&, Policies);
  930. The ``object_cast`` function casts the value of an object to a C++ value.
  931. You can supply a policy to handle the conversion from lua to C++. If the cast
  932. cannot be made a ``cast_failed`` exception will be thrown. If you have
  933. defined LUABIND_NO_ERROR_CHECKING (see `Build options`_) no checking will occur,
  934. and if the cast is invalid the application may very well crash. The nothrow
  935. versions will return an uninitialized ``boost::optional<T>`` object, to
  936. indicate that the cast could not be performed.
  937. The function signatures of all of the above functions are really templates
  938. for the object parameter, but the intention is that you should only pass
  939. objects in there, that's why it's left out of the documentation.
  940. ::
  941. object globals(lua_State*);
  942. object registry(lua_State*);
  943. These functions return the global environment table and the registry table respectively.
  944. ::
  945. object newtable(lua_State*);
  946. This function creates a new table and returns it as an object.
  947. ::
  948. object getmetatable(object const& obj);
  949. void setmetatable(object const& obj, object const& metatable);
  950. These functions get and set the metatable of a Lua object.
  951. ::
  952. lua_CFunction tocfunction(object const& value);
  953. template <class T> T* touserdata(object const& value)
  954. These extract values from the object at a lower level than ``object_cast()``.
  955. ::
  956. object getupvalue(object const& function, int index);
  957. void setupvalue(object const& function, int index, object const& value);
  958. These get and set the upvalues of ``function``.
  959. Assigning nil
  960. -------------
  961. To set a table entry to ``nil``, you can use ``luabind::nil``. It will avoid
  962. having to take the detour by first assigning ``nil`` to an object and then
  963. assign that to the table entry. It will simply result in a ``lua_pushnil()``
  964. call, instead of copying an object.
  965. Example::
  966. using luabind;
  967. object table = newtable(L);
  968. table["foo"] = "bar";
  969. // now, clear the "foo"-field
  970. table["foo"] = nil;
  971. Defining classes in Lua
  972. =======================
  973. In addition to binding C++ functions and classes with Lua, luabind also provide
  974. an OO-system in Lua. ::
  975. class 'lua_testclass'
  976. function lua_testclass:__init(name)
  977. self.name = name
  978. end
  979. function lua_testclass:print()
  980. print(self.name)
  981. end
  982. a = lua_testclass('example')
  983. a:print()
  984. Inheritance can be used between lua-classes::
  985. class 'derived' (lua_testclass)
  986. function derived:__init()
  987. lua_testclass.__init(self, 'derived name')
  988. end
  989. function derived:print()
  990. print('Derived:print() -> ')
  991. lua_testclass.print(self)
  992. end
  993. The base class is initialized explicitly by calling its ``__init()``
  994. function.
  995. As you can see in this example, you can call the base class member functions.
  996. You can find all member functions in the base class, but you will have to give
  997. the this-pointer (``self``) as first argument.
  998. Deriving in lua
  999. ---------------
  1000. It is also possible to derive Lua classes from C++ classes, and override
  1001. virtual functions with Lua functions. To do this we have to create a wrapper
  1002. class for our C++ base class. This is the class that will hold the Lua object
  1003. when we instantiate a Lua class.
  1004. ::
  1005. class base
  1006. {
  1007. public:
  1008. base(const char* s)
  1009. { std::cout << s << "\n"; }
  1010. virtual void f(int a)
  1011. { std::cout << "f(" << a << ")\n"; }
  1012. };
  1013. struct base_wrapper : base, luabind::wrap_base
  1014. {
  1015. base_wrapper(const char* s)
  1016. : base(s)
  1017. {}
  1018. virtual void f(int a)
  1019. {
  1020. call<void>("f", a);
  1021. }
  1022. static void default_f(base* ptr, int a)
  1023. {
  1024. return ptr->base::f(a);
  1025. }
  1026. };
  1027. ...
  1028. module(L)
  1029. [
  1030. class_<base, base_wrapper>("base")
  1031. .def(constructor<const char*>())
  1032. .def("f", &base::f, &base_wrapper::default_f)
  1033. ];
  1034. .. Important::
  1035. Since MSVC6.5 doesn't support explicit template parameters
  1036. to member functions, instead of using the member function ``call()``
  1037. you call a free function ``call_member()`` and pass the this-pointer
  1038. as first parameter.
  1039. Note that if you have both base classes and a base class wrapper, you must give
  1040. both bases and the base class wrapper type as template parameter to
  1041. ``class_`` (as done in the example above). The order in which you specify
  1042. them is not important. You must also register both the static version and the
  1043. virtual version of the function from the wrapper, this is necessary in order
  1044. to allow luabind to use both dynamic and static dispatch when calling the function.
  1045. .. Important::
  1046. It is extremely important that the signatures of the static (default) function
  1047. is identical to the virtual function. The fact that one of them is a free
  1048. function and the other a member function doesn't matter, but the parameters
  1049. as seen from lua must match. It would not have worked if the static function
  1050. took a ``base_wrapper*`` as its first argument, since the virtual function
  1051. takes a ``base*`` as its first argument (its this pointer). There's currently
  1052. no check in luabind to make sure the signatures match.
  1053. If we didn't have a class wrapper, it would not be possible to pass a Lua class
  1054. back to C++. Since the entry points of the virtual functions would still point
  1055. to the C++ base class, and not to the functions defined in Lua. That's why we
  1056. need one function that calls the base class' real function (used if the lua
  1057. class doesn't redefine it) and one virtual function that dispatches the call
  1058. into luabind, to allow it to select if a Lua function should be called, or if
  1059. the original function should be called. If you don't intend to derive from a
  1060. C++ class, or if it doesn't have any virtual member functions, you can register
  1061. it without a class wrapper.
  1062. You don't need to have a class wrapper in order to derive from a class, but if
  1063. it has virtual functions you may have silent errors.
  1064. .. Unnecessary? The rule of thumb is:
  1065. If your class has virtual functions, create a wrapper type, if it doesn't
  1066. don't create a wrapper type.
  1067. The wrappers must derive from ``luabind::wrap_base``, it contains a Lua reference
  1068. that will hold the Lua instance of the object to make it possible to dispatch
  1069. virtual function calls into Lua. This is done through an overloaded member function::
  1070. template<class Ret>
  1071. Ret call(char const* name, ...)
  1072. Its used in a similar way as ``call_function``, with the exception that it doesn't
  1073. take a ``lua_State`` pointer, and the name is a member function in the Lua class.
  1074. .. warning::
  1075. The current implementation of ``call_member`` is not able to distinguish const
  1076. member functions from non-const. If you have a situation where you have an overloaded
  1077. virtual function where the only difference in their signatures is their constness, the
  1078. wrong overload will be called by ``call_member``. This is rarely the case though.
  1079. Object identity
  1080. ~~~~~~~~~~~~~~~
  1081. When a pointer or reference to a registered class with a wrapper is passed
  1082. to Lua, luabind will query for it's dynamic type. If the dynamic type
  1083. inherits from ``wrap_base``, object identity is preserved.
  1084. ::
  1085. struct A { .. };
  1086. struct A_wrap : A, wrap_base { .. };
  1087. A* f(A* ptr) { return ptr; }
  1088. module(L)
  1089. [
  1090. class_<A, A_wrap>("A"),
  1091. def("f", &f)
  1092. ];
  1093. ::
  1094. > class 'B' (A)
  1095. > x = B()
  1096. > assert(x == f(x)) -- object identity is preserved when object is
  1097. -- passed through C++
  1098. This functionality relies on RTTI being enabled (that ``LUABIND_NO_RTTI`` is
  1099. not defined).
  1100. Overloading operators
  1101. ---------------------
  1102. You can overload most operators in Lua for your classes. You do this by simply
  1103. declaring a member function with the same name as an operator (the name of the
  1104. metamethods in Lua). The operators you can overload are:
  1105. - ``__add``
  1106. - ``__sub``
  1107. - ``__mul``
  1108. - ``__div``
  1109. - ``__pow``
  1110. - ``__lt``
  1111. - ``__le``
  1112. - ``__eq``
  1113. - ``__call``
  1114. - ``__unm``
  1115. - ``__tostring``
  1116. - ``__len``
  1117. ``__tostring`` isn't really an operator, but it's the metamethod that is called
  1118. by the standard library's ``tostring()`` function. There's one strange behavior
  1119. regarding binary operators. You are not guaranteed that the self pointer you
  1120. get actually refers to an instance of your class. This is because Lua doesn't
  1121. distinguish the two cases where you get the other operand as left hand value or
  1122. right hand value. Consider the following examples::
  1123. class 'my_class'
  1124. function my_class:__init(v)
  1125. self.val = v
  1126. end
  1127. function my_class:__sub(v)
  1128. return my_class(self.val - v.val)
  1129. end
  1130. function my_class:__tostring()
  1131. return self.val
  1132. end
  1133. This will work well as long as you only subtracts instances of my_class with
  1134. each other. But If you want to be able to subtract ordinary numbers from your
  1135. class too, you have to manually check the type of both operands, including the
  1136. self object. ::
  1137. function my_class:__sub(v)
  1138. if (type(self) == 'number') then
  1139. return my_class(self - v.val)
  1140. elseif (type(v) == 'number') then
  1141. return my_class(self.val - v)
  1142. else
  1143. -- assume both operands are instances of my_class
  1144. return my_class(self.val - v.val)
  1145. end
  1146. end
  1147. The reason why ``__sub`` is used as an example is because subtraction is not
  1148. commutative (the order of the operands matters). That's why luabind cannot
  1149. change order of the operands to make the self reference always refer to the
  1150. actual class instance.
  1151. If you have two different Lua classes with an overloaded operator, the operator
  1152. of the right hand side type will be called. If the other operand is a C++ class
  1153. with the same operator overloaded, it will be prioritized over the Lua class'
  1154. operator. If none of the C++ overloads matches, the Lua class operator will be
  1155. called.
  1156. Finalizers
  1157. ----------
  1158. If an object needs to perform actions when it's collected we provide a
  1159. ``__finalize`` function that can be overridden in lua-classes. The
  1160. ``__finalize`` functions will be called on all classes in the inheritance
  1161. chain, starting with the most derived type. ::
  1162. ...
  1163. function lua_testclass:__finalize()
  1164. -- called when the an object is collected
  1165. end
  1166. Slicing
  1167. -------
  1168. If your lua C++ classes don't have wrappers (see `Deriving in lua`_) and
  1169. you derive from them in lua, they may be sliced. Meaning, if an object
  1170. is passed into C++ as a pointer to its base class, the lua part will be
  1171. separated from the C++ base part. This means that if you call virtual
  1172. functions on that C++ object, they will not be dispatched to the lua
  1173. class. It also means that if you adopt the object, the lua part will be
  1174. garbage collected.
  1175. ::
  1176. +--------------------+
  1177. | C++ object | <- ownership of this part is transferred
  1178. | | to c++ when adopted
  1179. +--------------------+
  1180. | lua class instance | <- this part is garbage collected when
  1181. | and lua members | instance is adopted, since it cannot
  1182. +--------------------+ be held by c++.
  1183. The problem can be illustrated by this example::
  1184. struct A {};
  1185. A* filter_a(A* a) { return a; }
  1186. void adopt_a(A* a) { delete a; }
  1187. ::
  1188. using namespace luabind;
  1189. module(L)
  1190. [
  1191. class_<A>("A"),
  1192. def("filter_a", &filter_a),
  1193. def("adopt_a", &adopt_a, adopt(_1))
  1194. ]
  1195. In lua::
  1196. a = A()
  1197. b = filter_a(a)
  1198. adopt_a(b)
  1199. In this example, lua cannot know that ``b`` actually is the same object as
  1200. ``a``, and it will therefore consider the object to be owned by the C++ side.
  1201. When the ``b`` pointer then is adopted, a runtime error will be raised because
  1202. an object not owned by lua is being adopted to C++.
  1203. If you have a wrapper for your class, none of this will happen, see
  1204. `Object identity`_.
  1205. Exceptions
  1206. ==========
  1207. If any of the functions you register throws an exception when called, that
  1208. exception will be caught by luabind and converted to an error string and
  1209. ``lua_error()`` will be invoked. If the exception is a ``std::exception`` or a
  1210. ``const char*`` the string that is pushed on the Lua stack, as error message,
  1211. will be the string returned by ``std::exception::what()`` or the string itself
  1212. respectively. If the exception is unknown, a generic string saying that the
  1213. function threw an exception will be pushed.
  1214. If you have an exception type that isn't derived from
  1215. ``std::exception``, or you wish to change the error message from the
  1216. default result of ``what()``, it is possible to register custom
  1217. exception handlers::
  1218. struct my_exception
  1219. {};
  1220. void translate_my_exception(lua_State* L, my_exception const&)
  1221. {
  1222. lua_pushstring(L, "my_exception");
  1223. }
  1224. luabind::register_exception_handler<my_exception>(&translate_my_exception);
  1225. ``translate_my_exception()`` will be called by luabind whenever a
  1226. ``my_exception`` is caught. ``lua_error()`` will be called after the
  1227. handler function returns, so it is expected that the function will push
  1228. an error string on the stack.
  1229. Any function that invokes Lua code may throw ``luabind::error``. This exception
  1230. means that a Lua run-time error occurred. The error message is found on top of
  1231. the Lua stack. The reason why the exception doesn't contain the error string
  1232. itself is because it would then require heap allocation which may fail. If an
  1233. exception class throws an exception while it is being thrown itself, the
  1234. application will be terminated.
  1235. Error's synopsis is::
  1236. class error : public std::exception
  1237. {
  1238. public:
  1239. error(lua_State*);
  1240. lua_State* state() const throw();
  1241. virtual const char* what() const throw();
  1242. };
  1243. The state function returns a pointer to the Lua state in which the error was
  1244. thrown. This pointer may be invalid if you catch this exception after the lua
  1245. state is destructed. If the Lua state is valid you can use it to retrieve the
  1246. error message from the top of the Lua stack.
  1247. An example of where the Lua state pointer may point to an invalid state
  1248. follows::
  1249. struct lua_state
  1250. {
  1251. lua_state(lua_State* L): m_L(L) {}
  1252. ~lua_state() { lua_close(m_L); }
  1253. operator lua_State*() { return m_L; }
  1254. lua_State* m_L;
  1255. };
  1256. int main()
  1257. {
  1258. try
  1259. {
  1260. lua_state L = lua_open();
  1261. /* ... */
  1262. }
  1263. catch(luabind::error& e)
  1264. {
  1265. lua_State* L = e.state();
  1266. // L will now point to the destructed
  1267. // Lua state and be invalid
  1268. /* ... */
  1269. }
  1270. }
  1271. There's another exception that luabind may throw: ``luabind::cast_failed``,
  1272. this exception is thrown from ``call_function<>`` or ``call_member<>``. It
  1273. means that the return value from the Lua function couldn't be converted to
  1274. a C++ value. It is also thrown from ``object_cast<>`` if the cast cannot
  1275. be made.
  1276. The synopsis for ``luabind::cast_failed`` is::
  1277. class cast_failed : public std::exception
  1278. {
  1279. public:
  1280. cast_failed(lua_State*);
  1281. lua_State* state() const throw();
  1282. LUABIND_TYPE_INFO info() const throw();
  1283. virtual const char* what() const throw();
  1284. };
  1285. Again, the state member function returns a pointer to the Lua state where the
  1286. error occurred. See the example above to see where this pointer may be invalid.
  1287. The info member function returns the user defined ``LUABIND_TYPE_INFO``, which
  1288. defaults to a ``const std::type_info*``. This type info describes the type that
  1289. we tried to cast a Lua value to.
  1290. If you have defined ``LUABIND_NO_EXCEPTIONS`` none of these exceptions will be
  1291. thrown, instead you can set two callback functions that are called instead.
  1292. These two functions are only defined if ``LUABIND_NO_EXCEPTIONS`` are defined.
  1293. ::
  1294. luabind::set_error_callback(void(*)(lua_State*))
  1295. The function you set will be called when a runtime-error occur in Lua code. You
  1296. can find an error message on top of the Lua stack. This function is not
  1297. expected to return, if it does luabind will call ``std::terminate()``.
  1298. ::
  1299. luabind::set_cast_failed_callback(void(*)(lua_State*, LUABIND_TYPE_INFO))
  1300. The function you set is called instead of throwing ``cast_failed``. This function
  1301. is not expected to return, if it does luabind will call ``std::terminate()``.
  1302. Policies
  1303. ========
  1304. Sometimes it is necessary to control how luabind passes arguments and return
  1305. value, to do this we have policies. All policies use an index to associate
  1306. them with an argument in the function signature. These indices are ``result``
  1307. and ``_N`` (where ``N >= 1``). When dealing with member functions ``_1`` refers
  1308. to the ``this`` pointer.
  1309. .. contents:: Policies currently implemented
  1310. :local:
  1311. :depth: 1
  1312. .. include:: adopt.rst
  1313. .. include:: dependency.rst
  1314. .. include:: out_value.rst
  1315. .. include:: pure_out_value.rst
  1316. .. include:: return_reference_to.rst
  1317. .. include:: copy.rst
  1318. .. include:: discard_result.rst
  1319. .. include:: return_stl_iterator.rst
  1320. .. include:: raw.rst
  1321. .. include:: yield.rst
  1322. .. old policies section
  1323. ===================================================
  1324. Copy
  1325. ----
  1326. This will make a copy of the parameter. This is the default behavior when
  1327. passing parameters by-value. Note that this can only be used when passing from
  1328. C++ to Lua. This policy requires that the parameter type has a copy
  1329. constructor.
  1330. To use this policy you need to include ``luabind/copy_policy.hpp``.
  1331. Adopt
  1332. -----
  1333. This will transfer ownership of the parameter.
  1334. Consider making a factory function in C++ and exposing it to lua::
  1335. base* create_base()
  1336. {
  1337. return new base();
  1338. }
  1339. ...
  1340. module(L)
  1341. [
  1342. def("create_base", create_base)
  1343. ];
  1344. Here we need to make sure Lua understands that it should adopt the pointer
  1345. returned by the factory-function. This can be done using the adopt-policy.
  1346. ::
  1347. module(L)
  1348. [
  1349. def(L, "create_base", adopt(return_value))
  1350. ];
  1351. To specify multiple policies we just separate them with '+'.
  1352. ::
  1353. base* set_and_get_new(base* ptr)
  1354. {
  1355. base_ptrs.push_back(ptr);
  1356. return new base();
  1357. }
  1358. module(L)
  1359. [
  1360. def("set_and_get_new", &set_and_get_new,
  1361. adopt(return_value) + adopt(_1))
  1362. ];
  1363. When Lua adopts a pointer, it will call delete on it. This means that it cannot
  1364. adopt pointers allocated with another allocator than new (no malloc for
  1365. example).
  1366. To use this policy you need to include ``luabind/adopt_policy.hpp``.
  1367. Dependency
  1368. ----------
  1369. The dependency policy is used to create life-time dependencies between values.
  1370. Consider the following example::
  1371. struct A
  1372. {
  1373. B member;
  1374. const B& get_member()
  1375. {
  1376. return member;
  1377. }
  1378. };
  1379. When wrapping this class, we would do something like::
  1380. module(L)
  1381. [
  1382. class_<A>("A")
  1383. .def(constructor<>())
  1384. .def("get_member", &A::get_member)
  1385. ];
  1386. However, since the return value of get_member is a reference to a member of A,
  1387. this will create some life-time issues. For example::
  1388. Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
  1389. a = A()
  1390. b = a:get_member() -- b points to a member of a
  1391. a = nil
  1392. collectgarbage(0) -- since there are no references left to a, it is
  1393. -- removed
  1394. -- at this point, b is pointing into a removed object
  1395. When using the dependency-policy, it is possible to tell luabind to tie the
  1396. lifetime of one object to another, like this::
  1397. module(L)
  1398. [
  1399. class_<A>("A")
  1400. .def(constructor<>())
  1401. .def("get_member", &A::get_member, dependency(result, _1))
  1402. ];
  1403. This will create a dependency between the return-value of the function, and the
  1404. self-object. This means that the self-object will be kept alive as long as the
  1405. result is still alive. ::
  1406. Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
  1407. a = A()
  1408. b = a:get_member() -- b points to a member of a
  1409. a = nil
  1410. collectgarbage(0) -- a is dependent on b, so it isn't removed
  1411. b = nil
  1412. collectgarbage(0) -- all dependencies to a gone, a is removed
  1413. To use this policy you need to include ``luabind/dependency_policy.hpp``.
  1414. Return reference to
  1415. -------------------
  1416. It is very common to return references to arguments or the this-pointer to
  1417. allow for chaining in C++.
  1418. ::
  1419. struct A
  1420. {
  1421. float val;
  1422. A& set(float v)
  1423. {
  1424. val = v;
  1425. return *this;
  1426. }
  1427. };
  1428. When luabind generates code for this, it will create a new object for the
  1429. return-value, pointing to the self-object. This isn't a problem, but could be a
  1430. bit inefficient. When using the return_reference_to-policy we have the ability
  1431. to tell luabind that the return-value is already on the Lua stack.
  1432. ::
  1433. module(L)
  1434. [
  1435. class_<A>("A")
  1436. .def(constructor<>())
  1437. .def("set", &A::set, return_reference_to(_1))
  1438. ];
  1439. Instead of creating a new object, luabind will just copy the object that is
  1440. already on the stack.
  1441. .. warning::
  1442. This policy ignores all type information and should be used only it
  1443. situations where the parameter type is a perfect match to the
  1444. return-type (such as in the example).
  1445. To use this policy you need to include ``luabind/return_reference_to_policy.hpp``.
  1446. Out value
  1447. ---------
  1448. This policy makes it possible to wrap functions that take non const references
  1449. as its parameters with the intention to write return values to them.
  1450. ::
  1451. void f(float& val) { val = val + 10.f; }
  1452. or
  1453. ::
  1454. void f(float* val) { *val = *val + 10.f; }
  1455. Can be wrapped by doing::
  1456. module(L)
  1457. [
  1458. def("f", &f, out_value(_1))
  1459. ];
  1460. When invoking this function from Lua it will return the value assigned to its
  1461. parameter.
  1462. ::
  1463. Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
  1464. > a = f(10)
  1465. > print(a)
  1466. 20
  1467. When this policy is used in conjunction with user define types we often need
  1468. to do ownership transfers.
  1469. ::
  1470. struct A;
  1471. void f1(A*& obj) { obj = new A(); }
  1472. void f2(A** obj) { *obj = new A(); }
  1473. Here we need to make sure luabind takes control over object returned, for
  1474. this we use the adopt policy::
  1475. module(L)
  1476. [
  1477. class_<A>("A"),
  1478. def("f1", &f1, out_value(_1, adopt(_2)))
  1479. def("f2", &f2, out_value(_1, adopt(_2)))
  1480. ];
  1481. Here we are using adopt as an internal policy to out_value. The index
  1482. specified, _2, means adopt will be used to convert the value back to Lua.
  1483. Using _1 means the policy will be used when converting from Lua to C++.
  1484. To use this policy you need to include ``luabind/out_value_policy.hpp``.
  1485. Pure out value
  1486. --------------
  1487. This policy works in exactly the same way as out_value, except that it
  1488. replaces the parameters with default-constructed objects.
  1489. ::
  1490. void get(float& x, float& y)
  1491. {
  1492. x = 3.f;
  1493. y = 4.f;
  1494. }
  1495. ...
  1496. module(L)
  1497. [
  1498. def("get", &get,
  1499. pure_out_value(_1) + pure_out_value(_2))
  1500. ];
  1501. ::
  1502. Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
  1503. > x, y = get()
  1504. > print(x, y)
  1505. 3 5
  1506. Like out_value, it is possible to specify an internal policy used then
  1507. converting the values back to Lua.
  1508. ::
  1509. void get(test_class*& obj)
  1510. {
  1511. obj = new test_class();
  1512. }
  1513. ...
  1514. module(L)
  1515. [
  1516. def("get", &get, pure_out_value(_1, adopt(_1)))
  1517. ];
  1518. Discard result
  1519. --------------
  1520. This is a very simple policy which makes it possible to throw away
  1521. the value returned by a C++ function, instead of converting it to
  1522. Lua. This example makes sure the this reference never gets converted
  1523. to Lua.
  1524. ::
  1525. struct simple
  1526. {
  1527. simple& set_name(const std::string& n)
  1528. {
  1529. name = n;
  1530. return *this;
  1531. }
  1532. std::string name;
  1533. };
  1534. ...
  1535. module(L)
  1536. [
  1537. class_<simple>("simple")
  1538. .def("set_name", &simple::set_name, discard_result)
  1539. ];
  1540. To use this policy you need to include ``luabind/discard_result_policy.hpp``.
  1541. Return STL iterator
  1542. -------------------
  1543. This policy converts an STL container to a generator function that can be used
  1544. in Lua to iterate over the container. It works on any container that defines
  1545. ``begin()`` and ``end()`` member functions (they have to return iterators). It
  1546. can be used like this::
  1547. struct A
  1548. {
  1549. std::vector<std::string> names;
  1550. };
  1551. module(L)
  1552. [
  1553. class_<A>("A")
  1554. .def_readwrite("names", &A::names, return_stl_iterator)
  1555. ];
  1556. The Lua code to iterate over the container::
  1557. a = A()
  1558. for name in a.names do
  1559. print(name)
  1560. end
  1561. To use this policy you need to include ``luabind/iterator_policy.hpp``.
  1562. Yield
  1563. -----
  1564. This policy will cause the function to always yield the current thread when
  1565. returning. See the Lua manual for restrictions on yield.
  1566. Splitting up the registration
  1567. =============================
  1568. It is possible to split up a module registration into several
  1569. translation units without making each registration dependent
  1570. on the module it's being registered in.
  1571. ``a.cpp``::
  1572. luabind::scope register_a()
  1573. {
  1574. return
  1575. class_<a>("a")
  1576. .def("f", &a::f)
  1577. ;
  1578. }
  1579. ``b.cpp``::
  1580. luabind::scope register_b()
  1581. {
  1582. return
  1583. class_<b>("b")
  1584. .def("g", &b::g)
  1585. ;
  1586. }
  1587. ``module_ab.cpp``::
  1588. luabind::scope register_a();
  1589. luabind::scope register_b();
  1590. void register_module(lua_State* L)
  1591. {
  1592. module("b", L)
  1593. [
  1594. register_a(),
  1595. register_b()
  1596. ];
  1597. }
  1598. Error Handling
  1599. ==============
  1600. pcall errorfunc
  1601. ---------------
  1602. As mentioned in the `Lua documentation`_, it is possible to pass an
  1603. error handler function to ``lua_pcall()``. Luabind makes use of
  1604. ``lua_pcall()`` internally when calling member functions and free functions.
  1605. It is possible to set the error handler function that Luabind will use
  1606. globally::
  1607. typedef int(*pcall_callback_fun)(lua_State*);
  1608. void set_pcall_callback(pcall_callback_fun fn);
  1609. This is primarily useful for adding more information to the error message
  1610. returned by a failed protected call. For more information on how to use the
  1611. pcall_callback function, see ``errfunc`` under the
  1612. `pcall section of the lua manual`_.
  1613. For more information on how to retrieve debugging information from lua, see
  1614. `the debug section of the lua manual`_.
  1615. The message returned by the ``pcall_callback`` is accessable as the top lua
  1616. value on the stack. For example, if you would like to access it as a luabind
  1617. object, you could do like this::
  1618. catch(error& e)
  1619. {
  1620. object error_msg(from_stack(e.state(), -1));
  1621. std::cout << error_msg << std::endl;
  1622. }
  1623. .. _Lua documentation: http://www.lua.org/manual/5.0/manual.html
  1624. .. _`pcall section of the lua manual`: http://www.lua.org/manual/5.0/manual.html#3.15
  1625. .. _`the debug section of the lua manual`: http://www.lua.org/manual/5.0/manual.html#4
  1626. file and line numbers
  1627. ---------------------
  1628. If you want to add file name and line number to the error messages generated
  1629. by luabind you can define your own `pcall errorfunc`_. You may want to modify
  1630. this callback to better suit your needs, but the basic functionality could be
  1631. implemented like this::
  1632. int add_file_and_line(lua_State* L)
  1633. {
  1634. lua_Debug d;
  1635. lua_getstack(L, 1, &d);
  1636. lua_getinfo(L, "Sln", &d);
  1637. std::string err = lua_tostring(L, -1);
  1638. lua_pop(L, 1);
  1639. std::stringstream msg;
  1640. msg << d.short_src << ":" << d.currentline;
  1641. if (d.name != 0)
  1642. {
  1643. msg << "(" << d.namewhat << " " << d.name << ")";
  1644. }
  1645. msg << " " << err;
  1646. lua_pushstring(L, msg.str().c_str());
  1647. return 1;
  1648. }
  1649. For more information about what kind of information you can add to the error
  1650. message, see `the debug section of the lua manual`_.
  1651. Note that the callback set by ``set_pcall_callback()`` will only be used when
  1652. luabind executes lua code. Anytime when you call ``lua_pcall`` yourself, you
  1653. have to supply your function if you want error messages translated.
  1654. lua panic
  1655. ---------
  1656. When lua encounters a fatal error caused by a bug from the C/C++ side, it will
  1657. call its internal panic function. This can happen, for example, when you call
  1658. ``lua_gettable`` on a value that isn't a table. If you do the same thing from
  1659. within lua, it will of course just fail with an error message.
  1660. The default panic function will ``exit()`` the application. If you want to
  1661. handle this case without terminating your application, you can define your own
  1662. panic function using ``lua_atpanic``. The best way to continue from the panic
  1663. function is to make sure lua is compiled as C++ and throw an exception from
  1664. the panic function. Throwing an exception instead of using ``setjmp`` and
  1665. ``longjmp`` will make sure the stack is correctly unwound.
  1666. When the panic function is called, the lua state is invalid, and the only
  1667. allowed operation on it is to close it.
  1668. For more information, see the `lua manual section 3.19`_.
  1669. .. _`lua manual section 3.19`: http://www.lua.org/manual/5.0/manual.html#3.19
  1670. structured exceptions (MSVC)
  1671. ----------------------------
  1672. Since lua is generally built as a C library, any callbacks called from lua
  1673. cannot under any circumstance throw an exception. Because of that, luabind has
  1674. to catch all exceptions and translate them into proper lua errors (by calling
  1675. ``lua_error()``). This means we have a ``catch(...) {}`` in there.
  1676. In Visual Studio, ``catch (...)`` will not only catch C++ exceptions, it will
  1677. also catch structured exceptions, such as segmentation fault. This means that if
  1678. your function, that gets called from luabind, makes an invalid memory
  1679. adressing, you won't notice it. All that will happen is that lua will return
  1680. an error message saying "unknown exception".
  1681. To remedy this, you can create your own *exception translator*::
  1682. void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*)
  1683. { throw; }
  1684. #ifdef _MSC_VER
  1685. ::_set_se_translator(straight_to_debugger);
  1686. #endif
  1687. This will make structured exceptions, like segmentation fault, to actually get
  1688. caught by the debugger.
  1689. Error messages
  1690. --------------
  1691. These are the error messages that can be generated by luabind, with a more
  1692. in-depth explanation.
  1693. - .. parsed-literal::
  1694. the attribute '*class-name.attribute-name*' is read only
  1695. There is no data member named *attribute-name* in the class *class-name*,
  1696. or there's no setter-function registered on that property name. See the
  1697. Properties_ section.
  1698. - .. parsed-literal::
  1699. the attribute '*class-name.attribute-name*' is of type: (*class-name*) and does not match (*class_name*)
  1700. This error is generated if you try to assign an attribute with a value
  1701. of a type that cannot be converted to the attributes type.
  1702. - .. parsed-literal::
  1703. *class-name()* threw an exception, *class-name:function-name()* threw an exception
  1704. The class' constructor or member function threw an unknown exception.
  1705. Known exceptions are const char*, std::exception. See the
  1706. `exceptions`_ section.
  1707. - .. parsed-literal::
  1708. no overload of '*class-name:function-name*' matched the arguments (*parameter-types*)
  1709. no match for function call '*function-name*' with the parameters (*parameter-types*)
  1710. no constructor of *class-name* matched the arguments (*parameter-types*)
  1711. no operator *operator-name* matched the arguments (*parameter-types*)
  1712. No function/operator with the given name takes the parameters you gave
  1713. it. You have either misspelled the function name, or given it incorrect
  1714. parameters. This error is followed by a list of possible candidate
  1715. functions to help you figure out what parameter has the wrong type. If
  1716. the candidate list is empty there's no function at all with that name.
  1717. See the signature matching section.
  1718. - .. parsed-literal::
  1719. call of overloaded '*class-name:function-name*(*parameter-types*)' is ambiguous
  1720. ambiguous match for function call '*function-name*' with the parameters (*parameter-types*)
  1721. call of overloaded constructor '*class-name*(*parameter-types*)' is ambiguous
  1722. call of overloaded operator *operator-name* (*parameter-types*) is ambiguous
  1723. This means that the function/operator you are trying to call has at least
  1724. one other overload that matches the arguments just as good as the first
  1725. overload.
  1726. - .. parsed-literal::
  1727. cannot derive from C++ class '*class-name*'. It does not have a wrapped type.
  1728. Build options
  1729. =============
  1730. There are a number of configuration options available when building luabind.
  1731. It is very important that your project has the exact same configuration
  1732. options as the ones given when the library was build! The exceptions are the
  1733. ``LUABIND_MAX_ARITY`` and ``LUABIND_MAX_BASES`` which are template-based
  1734. options and only matters when you use the library (which means they can
  1735. differ from the settings of the library).
  1736. The default settings which will be used if no other settings are given
  1737. can be found in ``luabind/config.hpp``.
  1738. If you want to change the settings of the library, you can modify the
  1739. config file. It is included and used by all makefiles. You can change paths
  1740. to Lua and boost in there as well.
  1741. LUABIND_MAX_ARITY
  1742. Controls the maximum arity of functions that are registered with luabind.
  1743. You can't register functions that takes more parameters than the number
  1744. this macro is set to. It defaults to 5, so, if your functions have greater
  1745. arity you have to redefine it. A high limit will increase compilation time.
  1746. LUABIND_MAX_BASES
  1747. Controls the maximum number of classes one class can derive from in
  1748. luabind (the number of classes specified within ``bases<>``).
  1749. ``LUABIND_MAX_BASES`` defaults to 4. A high limit will increase
  1750. compilation time.
  1751. LUABIND_NO_ERROR_CHECKING
  1752. If this macro is defined, all the Lua code is expected only to make legal
  1753. calls. If illegal function calls are made (e.g. giving parameters that
  1754. doesn't match the function signature) they will not be detected by luabind
  1755. and the application will probably crash. Error checking could be disabled
  1756. when shipping a release build (given that no end-user has access to write
  1757. custom Lua code). Note that function parameter matching will be done if a
  1758. function is overloaded, since otherwise it's impossible to know which one
  1759. was called. Functions will still be able to throw exceptions when error
  1760. checking is disabled.
  1761. If a function throws an exception it will be caught by luabind and
  1762. propagated with ``lua_error()``.
  1763. LUABIND_NO_EXCEPTIONS
  1764. This define will disable all usage of try, catch and throw in luabind.
  1765. This will in many cases disable run-time errors, when performing invalid
  1766. casts or calling Lua functions that fails or returns values that cannot
  1767. be converted by the given policy. luabind requires that no function called
  1768. directly or indirectly by luabind throws an exception (throwing exceptions
  1769. through Lua has undefined behavior).
  1770. Where exceptions are the only way to get an error report from luabind,
  1771. they will be replaced with calls to the callback functions set with
  1772. ``set_error_callback()`` and ``set_cast_failed_callback()``.
  1773. LUA_API
  1774. If you want to link dynamically against Lua, you can set this define to
  1775. the import-keyword on your compiler and platform. On Windows in Visual Studio
  1776. this should be ``__declspec(dllimport)`` if you want to link against Lua
  1777. as a dll.
  1778. LUABIND_DYNAMIC_LINK
  1779. Must be defined if you intend to link against the luabind shared
  1780. library.
  1781. LUABIND_NO_RTTI
  1782. You can define this if you don't want luabind to use ``dynamic_cast<>``.
  1783. It will disable `Object identity`_.
  1784. NDEBUG
  1785. This define will disable all asserts and should be defined in a release
  1786. build.
  1787. Implementation notes
  1788. ====================
  1789. The classes and objects are implemented as user data in Lua. To make sure that
  1790. the user data really is the internal structure it is supposed to be, we tag
  1791. their metatables. A user data who's metatable contains a boolean member named
  1792. ``__luabind_classrep`` is expected to be a class exported by luabind. A user
  1793. data who's metatable contains a boolean member named ``__luabind_class`` is
  1794. expected to be an instantiation of a luabind class.
  1795. This means that if you make your own user data and tags its metatable with the
  1796. exact same names, you can very easily fool luabind and crash the application.
  1797. In the Lua registry, luabind keeps an entry called ``__luabind_classes``. It
  1798. should not be removed or overwritten.
  1799. In the global table, a variable called ``super`` is used every time a
  1800. constructor in a lua-class is called. This is to make it easy for that
  1801. constructor to call its base class' constructor. So, if you have a global
  1802. variable named super it may be overwritten. This is probably not the best
  1803. solution, and this restriction may be removed in the future.
  1804. .. note:: Deprecated
  1805. ``super()`` has been deprecated since version 0.8 in favor of directly
  1806. invoking the base class' ``__init()`` function::
  1807. function Derived:__init()
  1808. Base.__init(self)
  1809. end
  1810. Luabind uses two upvalues for functions that it registers. The first is a
  1811. userdata containing a list of overloads for the function, the other is a light
  1812. userdata with the value 0x1337, this last value is used to identify functions
  1813. registered by luabind. It should be virtually impossible to have such a pointer
  1814. as secondary upvalue by pure chance. This means, if you are trying to replace
  1815. an existing function with a luabind function, luabind will see that the
  1816. secondary upvalue isn't the magic id number and replace it. If it can identify
  1817. the function to be a luabind function, it won't replace it, but rather add
  1818. another overload to it.
  1819. Inside the luabind namespace, there's another namespace called detail. This
  1820. namespace contains non-public classes and are not supposed to be used directly.
  1821. FAQ
  1822. ===
  1823. What's up with __cdecl and __stdcall?
  1824. If you're having problem with functions
  1825. that cannot be converted from ``void (__stdcall *)(int,int)`` to
  1826. ``void (__cdecl*)(int,int)``. You can change the project settings to make the
  1827. compiler generate functions with __cdecl calling conventions. This is
  1828. a problem in developer studio.
  1829. What's wrong with functions taking variable number of arguments?
  1830. You cannot register a function with ellipses in its signature. Since
  1831. ellipses don't preserve type safety, those should be avoided anyway.
  1832. Internal structure overflow in VC
  1833. If you, in visual studio, get fatal error C1204: compiler limit :
  1834. internal structure overflow. You should try to split that compilation
  1835. unit up in smaller ones. See `Splitting up the registration`_ and
  1836. `Splitting class registrations`_.
  1837. What's wrong with precompiled headers in VC?
  1838. Visual Studio doesn't like anonymous namespaces in its precompiled
  1839. headers. If you encounter this problem you can disable precompiled
  1840. headers for the compilation unit (cpp-file) that uses luabind.
  1841. error C1076: compiler limit - internal heap limit reached in VC
  1842. In visual studio you will probably hit this error. To fix it you have to
  1843. increase the internal heap with a command-line option. We managed to
  1844. compile the test suit with /Zm300, but you may need a larger heap then
  1845. that.
  1846. error C1055: compiler limit \: out of keys in VC
  1847. It seems that this error occurs when too many assert() are used in a
  1848. program, or more specifically, the __LINE__ macro. It seems to be fixed by
  1849. changing /ZI (Program database for edit and continue) to /Zi
  1850. (Program database).
  1851. How come my executable is huge?
  1852. If you're compiling in debug mode, you will probably have a lot of
  1853. debug-info and symbols (luabind consists of a lot of functions). Also,
  1854. if built in debug mode, no optimizations were applied, luabind relies on
  1855. that the compiler is able to inline functions. If you built in release
  1856. mode, try running strip on your executable to remove export-symbols,
  1857. this will trim down the size.
  1858. Our tests suggests that cygwin's gcc produces much bigger executables
  1859. compared to gcc on other platforms and other compilers.
  1860. .. HUH?! // check the magic number that identifies luabind's functions
  1861. Can I register class templates with luabind?
  1862. Yes you can, but you can only register explicit instantiations of the
  1863. class. Because there's no Lua counterpart to C++ templates. For example,
  1864. you can register an explicit instantiation of std::vector<> like this::
  1865. module(L)
  1866. [
  1867. class_<std::vector<int> >("vector")
  1868. .def(constructor<int>)
  1869. .def("push_back", &std::vector<int>::push_back)
  1870. ];
  1871. .. Again, irrelevant to docs: Note that the space between the two > is required by C++.
  1872. Do I have to register destructors for my classes?
  1873. No, the destructor of a class is always called by luabind when an
  1874. object is collected. Note that Lua has to own the object to collect it.
  1875. If you pass it to C++ and gives up ownership (with adopt policy) it will
  1876. no longer be owned by Lua, and not collected.
  1877. If you have a class hierarchy, you should make the destructor virtual if
  1878. you want to be sure that the correct destructor is called (this apply to C++
  1879. in general).
  1880. .. And again, the above is irrelevant to docs. This isn't a general C++ FAQ. But it saves us support questions.
  1881. Fatal Error C1063 compiler limit \: compiler stack overflow in VC
  1882. VC6.5 chokes on warnings, if you are getting alot of warnings from your
  1883. code try suppressing them with a pragma directive, this should solve the
  1884. problem.
  1885. Crashes when linking against luabind as a dll in Windows
  1886. When you build luabind, Lua and you project, make sure you link against
  1887. the runtime dynamically (as a dll).
  1888. I cannot register a function with a non-const parameter
  1889. This is because there is no way to get a reference to a Lua value. Have
  1890. a look at out_value_ and pure_out_value_ policies.
  1891. Known issues
  1892. ============
  1893. - You cannot use strings with extra nulls in them as member names that refers
  1894. to C++ members.
  1895. - If one class registers two functions with the same name and the same
  1896. signature, there's currently no error. The last registered function will
  1897. be the one that's used.
  1898. - In VC7, classes can not be called test.
  1899. - If you register a function and later rename it, error messages will use the
  1900. original function name.
  1901. - luabind does not support class hierarchies with virtual inheritance. Casts are
  1902. done with static pointer offsets.
  1903. Acknowledgments
  1904. ===============
  1905. Written by Daniel Wallin and Arvid Norberg. © Copyright 2003.
  1906. All rights reserved.
  1907. Evan Wies has contributed with thorough testing, countless bug reports
  1908. and feature ideas.
  1909. This library was highly inspired by Dave Abrahams' Boost.Python_ library.
  1910. .. _Boost.Python: http://www.boost.org/libraries/python