*** empty log message ***
[luabind.git] / examples / any_converter / any_converter.cpp
blob72c27bd76f5abf06c818e94534ce98a11d222d88
1 #include <iostream>
3 extern "C"
5 #include "lua.h"
6 #include "lauxlib.h"
7 #include "lualib.h"
10 bool dostring(lua_State* L, const char* str)
12 if (luaL_loadbuffer(L, str, std::strlen(str), str) || lua_pcall(L, 0, 0, 0))
14 const char* a = lua_tostring(L, -1);
15 std::cout << a << "\n";
16 lua_pop(L, 1);
17 return true;
19 return false;
22 #define LUABIND_NO_HEADERS_ONLY
24 #include <luabind/luabind.hpp>
25 #include <boost/any.hpp>
27 template<class T>
28 struct convert_any
30 static void convert(lua_State* L, const boost::any& a)
32 typename luabind::detail::default_policy::template generate_converter<T, luabind::detail::cpp_to_lua>::type conv;
34 conv.apply(L, *boost::any_cast<T>(&a));
38 std::map<const std::type_info*, void(*)(lua_State*, const boost::any&)> any_converters;
40 template<class T>
41 void register_any_converter()
43 any_converters[&typeid(T)] = convert_any<T>::convert;
46 namespace luabind
48 namespace converters
50 yes_t is_user_defined(by_value<boost::any>);
51 yes_t is_user_defined(by_const_reference<boost::any>);
53 void convert_cpp_to_lua(lua_State* L, const boost::any& a)
55 typedef void(*conv_t)(lua_State* L, const boost::any&);
56 conv_t conv = any_converters[&a.type()];
57 conv(L, a);
62 boost::any f(bool b)
64 if (b) return "foobar";
65 else return "3.5f";
68 int main()
70 register_any_converter<int>();
71 register_any_converter<float>();
72 register_any_converter<const char*>();
73 register_any_converter<std::string>();
75 lua_State* L = lua_open();
76 lua_baselibopen(L);
78 luabind::open(L);
79 luabind::function(L, "f", &f);
81 dostring(L, "print( f(true) )");
82 dostring(L, "print( f(false) )");
84 dostring(L, "function update(p) print(p) end");
86 boost::any param = std::string("foo");
88 luabind::call_function<void>(L, "update", param);
90 lua_close(L);