Remove old unused files accidentally left around.
[luabind.git] / examples / any_converter / any_converter.cpp
bloba5f6995c85b3b5ee748338f8cec8819b36559e6b
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 #include <luabind/luabind.hpp>
23 #include <luabind/detail/convert_to_lua.hpp>
24 #include <boost/any.hpp>
26 template<class T>
27 struct convert_any
29 static void convert(lua_State* L, const boost::any& a)
31 luabind::detail::convert_to_lua(L, *boost::any_cast<T>(&a));
35 std::map<const std::type_info*, void(*)(lua_State*, const boost::any&)> any_converters;
37 template<class T>
38 void register_any_converter()
40 any_converters[&typeid(T)] = convert_any<T>::convert;
43 namespace luabind
45 namespace converters
47 yes_t is_user_defined(by_value<boost::any>);
48 yes_t is_user_defined(by_const_reference<boost::any>);
50 void convert_cpp_to_lua(lua_State* L, const boost::any& a)
52 typedef void(*conv_t)(lua_State* L, const boost::any&);
53 conv_t conv = any_converters[&a.type()];
54 conv(L, a);
59 boost::any f(bool b)
61 if (b) return "foobar";
62 else return 3.5f;
65 int main()
67 register_any_converter<int>();
68 register_any_converter<float>();
69 register_any_converter<const char*>();
70 register_any_converter<std::string>();
72 lua_State* L = lua_open();
73 #if LUA_VERSION_NUM >= 501
74 luaL_openlibs(L);
75 #else
76 lua_baselibopen(L);
77 #endif
79 using namespace luabind;
81 open(L);
82 module(L)
84 def("f", &f)
87 dostring(L, "print( f(true) )");
88 dostring(L, "print( f(false) )");
89 dostring(L, "function update(p) print(p) end");
91 boost::any param = std::string("foo");
93 luabind::call_function<void>(L, "update", param);
95 lua_close(L);