File: userdefined-converters.rst

package info (click to toggle)
luabind 0.9.1%2Bgit20150823%2Bdfsg-3
  • links: PTS
  • area: main
  • in suites: bookworm, bullseye
  • size: 1,692 kB
  • sloc: cpp: 14,884; makefile: 204; sh: 41; python: 38; ansic: 11
file content (54 lines) | stat: -rw-r--r-- 1,462 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Adding converters for user defined types
========================================

It is possible to get luabind to handle user defined types like it does
the built in types by specializing ``luabind::default_converter<>``:

::

  struct int_wrapper
  {
      int_wrapper(int value)
        : value(value)
      {}

      int value;
  };

  namespace luabind
  {
      template <>
      struct default_converter<X>
        : native_converter_base<X>
      {
          static int compute_score(lua_State* L, int index)
          {
              return lua_type(L, index) == LUA_TNUMBER ? 0 : -1;
          }

          X from(lua_State* L, int index)
          {
              return X(lua_tonumber(L, index));
          }

          void to(lua_State* L, X const& x)
          {
              lua_pushnumber(L, x.value);
          }
      };

      template <>
      struct default_converter<X const&>
        : default_converter<X>
      {};
  }

Note that ``default_converter<>`` is instantiated for the actual argument and
return types of the bound functions. In the above example, we add a
specialization for ``X const&`` that simply forwards to the ``X`` converter.
This lets us export functions which accept ``X`` by const reference.

``native_converter_base<>`` should be used as the base class for the
specialized converters. It simplifies the converter interface, and
provides a mean for backward compatibility since the underlying
interface is in flux.