| 44 | }; |
| 45 | |
| 46 | int main() { |
| 47 | std::cout << "=== usertype ===" << std::endl; |
| 48 | |
| 49 | sol::state lua; |
| 50 | lua.open_libraries(sol::lib::base, sol::lib::math); |
| 51 | |
| 52 | // the simplest way to create a class is through |
| 53 | // sol::state::new_userdata |
| 54 | // the first template is the class type |
| 55 | // the rest are the constructor parameters |
| 56 | // using new_userdata you can only have one constructor |
| 57 | |
| 58 | |
| 59 | // you must make sure that the name of the function |
| 60 | // goes before the member function pointer |
| 61 | lua.new_usertype<foo>("foo", |
| 62 | sol::constructors<foo(std::string)>(), |
| 63 | "print", |
| 64 | &foo::print, |
| 65 | "test", |
| 66 | &foo::test); |
| 67 | |
| 68 | // making the class from lua is simple |
| 69 | // same with calling member functions |
| 70 | lua.script( |
| 71 | "x = foo.new('test')\n" |
| 72 | "x:print()\n" |
| 73 | "y = x:test(10)"); |
| 74 | |
| 75 | auto y = lua.get<int>("y"); |
| 76 | std::cout << y << std::endl; // show 14 |
| 77 | |
| 78 | // if you want a class to have more than one constructor |
| 79 | // the way to do so is through set_userdata and creating |
| 80 | // a userdata yourself with constructor types |
| 81 | |
| 82 | { |
| 83 | // Notice the brace: this means we're in a new scope |
| 84 | |
| 85 | // first, define the different types of constructors |
| 86 | // notice here that the return type |
| 87 | // on the function-type doesn't exactly matter, |
| 88 | // which allows you to use a shorter class name/void |
| 89 | // if necessary |
| 90 | sol::constructors<vector(), |
| 91 | vector(float), |
| 92 | void(float, float)> |
| 93 | ctor; |
| 94 | // then you must register it |
| 95 | sol::usertype<vector> utype |
| 96 | = lua.new_usertype<vector>("vector", ctor); |
| 97 | |
| 98 | // add to it as much as you like |
| 99 | utype["is_unit"] = &vector::is_unit; |
| 100 | // You can throw away the usertype after |
| 101 | // you set it: you do NOT |
| 102 | // have to keep it around |
| 103 | // cleanup happens automagically! |
nothing calls this directly
no test coverage detected