any_converter.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include <iostream>
  2. extern "C"
  3. {
  4. #include "lua.h"
  5. #include "lauxlib.h"
  6. #include "lualib.h"
  7. }
  8. bool dostring(lua_State* L, const char* str)
  9. {
  10. if (luaL_loadbuffer(L, str, std::strlen(str), str) || lua_pcall(L, 0, 0, 0))
  11. {
  12. const char* a = lua_tostring(L, -1);
  13. std::cout << a << "\n";
  14. lua_pop(L, 1);
  15. return true;
  16. }
  17. return false;
  18. }
  19. #include <luabind/luabind.hpp>
  20. #include <luabind/detail/convert_to_lua.hpp>
  21. #include <boost/any.hpp>
  22. template<class T>
  23. struct convert_any
  24. {
  25. static void convert(lua_State* L, const boost::any& a)
  26. {
  27. luabind::detail::convert_to_lua(L, *boost::any_cast<T>(&a));
  28. }
  29. };
  30. std::map<const std::type_info*, void(*)(lua_State*, const boost::any&)> any_converters;
  31. template<class T>
  32. void register_any_converter()
  33. {
  34. any_converters[&typeid(T)] = convert_any<T>::convert;
  35. }
  36. namespace luabind
  37. {
  38. namespace converters
  39. {
  40. yes_t is_user_defined(by_value<boost::any>);
  41. yes_t is_user_defined(by_const_reference<boost::any>);
  42. void convert_cpp_to_lua(lua_State* L, const boost::any& a)
  43. {
  44. typedef void(*conv_t)(lua_State* L, const boost::any&);
  45. conv_t conv = any_converters[&a.type()];
  46. conv(L, a);
  47. }
  48. }
  49. }
  50. boost::any f(bool b)
  51. {
  52. if (b) return "foobar";
  53. else return 3.5f;
  54. }
  55. int main()
  56. {
  57. register_any_converter<int>();
  58. register_any_converter<float>();
  59. register_any_converter<const char*>();
  60. register_any_converter<std::string>();
  61. lua_State* L = lua_open();
  62. #if LUA_VERSION_NUM >= 501
  63. luaL_openlibs(L);
  64. #else
  65. lua_baselibopen(L);
  66. #endif
  67. using namespace luabind;
  68. open(L);
  69. module(L)
  70. [
  71. def("f", &f)
  72. ];
  73. dostring(L, "print( f(true) )");
  74. dostring(L, "print( f(false) )");
  75. dostring(L, "function update(p) print(p) end");
  76. boost::any param = std::string("foo");
  77. luabind::call_function<void>(L, "update", param);
  78. lua_close(L);
  79. }