1 #define SOL_ALL_SAFETIES_ON 1
2 #include <sol/sol.hpp>
3 
4 #include <string>
5 #include <iostream>
6 
7 class MyClass {
8 public:
MyClass(double d)9 	MyClass(double d) : data(d) {
10 	}
11 	double data;
12 };
13 
main()14 int main() {
15 	std::cout << "=== usertype constructors ===" << std::endl;
16 
17 
18 	sol::state lua;
19 	lua.open_libraries(sol::lib::base);
20 
21 	lua.new_usertype<MyClass>("MyClass",
22 	     sol::meta_function::construct,
23 	     sol::factories(
24 	          // MyClass.new(...) -- dot syntax, no "self" value passed in
25 	          [](const double& d) { return std::make_shared<MyClass>(d); },
26 	          // MyClass:new(...) -- colon syntax, passes in the "self" value
27 	          // as first argument implicitly
28 	          [](sol::object, const double& d) { return std::make_shared<MyClass>(d); }),
29 	     // MyClass(...) syntax, only
30 	     sol::call_constructor,
31 	     sol::factories([](const double& d) { return std::make_shared<MyClass>(d); }),
32 	     "data",
33 	     &MyClass::data);
34 
35 	sol::optional<sol::error> maybe_error = lua.safe_script(R"(
36 		d1 = MyClass(2.1)
37 		d2 = MyClass:new(3.1)
38 		d3 = MyClass(4.1)
39 		assert(d1.data == 2.1)
40 		assert(d2.data == 3.1)
41 		assert(d3.data == 4.1)
42 	)",
43 	     sol::script_pass_on_error);
44 
45 	if (maybe_error) {
46 		// something went wrong!
47 		std::cerr << "Something has gone horribly unexpected and wrong:\n" << maybe_error->what() << std::endl;
48 		return 1;
49 	}
50 
51 	// everything is okay!
52 	std::cout << "Everything went okay and all the asserts passed!" << std::endl;
53 
54 	return 0;
55 }
56