| 12 | }; |
| 13 | |
| 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 |
| 25 | // passed in |
| 26 | [](const double& d) { |
| 27 | return std::make_shared<MyClass>(d); |
| 28 | }, |
| 29 | // MyClass:new(...) -- colon syntax, passes in the |
| 30 | // "self" value as first argument implicitly |
| 31 | [](sol::object, const double& d) { |
| 32 | return std::make_shared<MyClass>(d); |
| 33 | }), |
| 34 | // MyClass(...) syntax, only |
| 35 | sol::call_constructor, |
| 36 | sol::factories([](const double& d) { |
| 37 | return std::make_shared<MyClass>(d); |
| 38 | }), |
| 39 | "data", |
| 40 | &MyClass::data); |
| 41 | |
| 42 | sol::optional<sol::error> maybe_error = lua.safe_script(R"( |
| 43 | d1 = MyClass(2.1) |
| 44 | d2 = MyClass:new(3.1) |
| 45 | d3 = MyClass(4.1) |
| 46 | assert(d1.data == 2.1) |
| 47 | assert(d2.data == 3.1) |
| 48 | assert(d3.data == 4.1) |
| 49 | )", |
| 50 | sol::script_pass_on_error); |
| 51 | |
| 52 | if (maybe_error) { |
| 53 | // something went wrong! |
| 54 | std::cerr << "Something has gone horribly unexpected " |
| 55 | "and wrong:\n" |
| 56 | << maybe_error->what() << std::endl; |
| 57 | return 1; |
| 58 | } |
| 59 | |
| 60 | // everything is okay! |
| 61 | std::cout |
| 62 | << "Everything went okay and all the asserts passed!" |
| 63 | << std::endl; |
| 64 | |
| 65 | return 0; |
| 66 | } |
nothing calls this directly
no test coverage detected