test_user_defined_converter.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright Daniel Wallin 2008. Use, modification and distribution is
  2. // subject to the Boost Software License, Version 1.0. (See accompanying
  3. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4. #include "test.hpp"
  5. #include <luabind/luabind.hpp>
  6. struct X
  7. {
  8. X(int value)
  9. : value(value)
  10. {}
  11. int value;
  12. };
  13. namespace luabind {
  14. template <>
  15. struct default_converter<X>
  16. : native_converter_base<X>
  17. {
  18. int compute_score(lua_State* L, int index)
  19. {
  20. return cv.compute_score(L, index);
  21. }
  22. X from(lua_State* L, int index)
  23. {
  24. return X(lua_tonumber(L, index));
  25. }
  26. void to(lua_State* L, X const& x)
  27. {
  28. lua_pushnumber(L, x.value);
  29. }
  30. default_converter<int> cv;
  31. };
  32. } // namespace luabind
  33. int take(X x)
  34. {
  35. return x.value;
  36. }
  37. X get(int value)
  38. {
  39. return X(value);
  40. }
  41. void test_main(lua_State* L)
  42. {
  43. using namespace luabind;
  44. module(L) [
  45. def("take", &take),
  46. def("get", &get)
  47. ];
  48. DOSTRING(L,
  49. "assert(take(1) == 1)\n"
  50. "assert(take(2) == 2)\n"
  51. );
  52. DOSTRING(L,
  53. "assert(get(1) == 1)\n"
  54. "assert(get(2) == 2)\n"
  55. );
  56. }