| 26 | |
| 27 | |
| 28 | int main() { |
| 29 | |
| 30 | std::cout << "=== usertype basics ===" << std::endl; |
| 31 | |
| 32 | static const bool way_1 = true; |
| 33 | |
| 34 | sol::state lua; |
| 35 | lua.open_libraries(sol::lib::base); |
| 36 | |
| 37 | if (way_1) { |
| 38 | lua.new_usertype<ship>( |
| 39 | "ship", // the name of the class, as you want it |
| 40 | // to be used in lua List the member |
| 41 | // functions you wish to bind: |
| 42 | // "name_of_item", |
| 43 | // &class_name::function_or_variable |
| 44 | "shoot", |
| 45 | &ship::shoot, |
| 46 | "hurt", |
| 47 | &ship::hurt, |
| 48 | // bind variable types, too |
| 49 | "life", |
| 50 | &ship::life, |
| 51 | // names in lua don't have to be the same as C++, |
| 52 | // but it probably helps if they're kept the same, |
| 53 | // here we change it just to show its possible |
| 54 | "bullet_count", |
| 55 | &ship::bullets); |
| 56 | } |
| 57 | else { |
| 58 | // set usertype explicitly, with the given name |
| 59 | sol::usertype<ship> usertype_table |
| 60 | = lua.new_usertype<ship>("ship"); |
| 61 | usertype_table["shoot"] = &ship::shoot; |
| 62 | usertype_table["hurt"] = &ship::hurt; |
| 63 | usertype_table["life"] = &ship::life; |
| 64 | usertype_table["bullet_count"] = &ship::bullets; |
| 65 | } |
| 66 | |
| 67 | const auto& code = R"( |
| 68 | fwoosh = ship.new() |
| 69 | -- note the ":" that is there: this is mandatory for member function calls |
| 70 | -- ":" means "pass self" in Lua |
| 71 | local success = fwoosh:shoot() |
| 72 | local is_dead = fwoosh:hurt(20) |
| 73 | -- check if it works |
| 74 | print(is_dead) -- the ship is not dead at this point |
| 75 | print(fwoosh.life .. "life left") -- 80 life left |
| 76 | print(fwoosh.bullet_count) -- 19 |
| 77 | )"; |
| 78 | |
| 79 | |
| 80 | lua.script(code); |
| 81 | |
| 82 | std::cout << std::endl; |
| 83 | |
| 84 | return 0; |
| 85 | } |
nothing calls this directly
no test coverage detected