2019-05-22 07:17:31 +08:00
|
|
|
#define SOL_ALL_SAFETIES_ON 1
|
2018-09-28 13:27:38 +08:00
|
|
|
#include <sol/sol.hpp>
|
2017-04-03 04:10:00 +08:00
|
|
|
|
2017-09-25 04:36:45 +08:00
|
|
|
#include <iostream>
|
2016-09-09 19:48:28 +08:00
|
|
|
|
|
|
|
int main() {
|
2018-03-16 05:16:28 +08:00
|
|
|
std::cout << "=== namespacing ===" << std::endl;
|
2017-09-25 04:36:45 +08:00
|
|
|
|
2016-09-09 19:48:28 +08:00
|
|
|
struct my_class {
|
|
|
|
int b = 24;
|
|
|
|
|
|
|
|
int f() const {
|
|
|
|
return 24;
|
|
|
|
}
|
|
|
|
|
|
|
|
void g() {
|
|
|
|
++b;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
sol::state lua;
|
|
|
|
lua.open_libraries();
|
|
|
|
|
2017-09-25 04:36:45 +08:00
|
|
|
// "bark" namespacing in Lua
|
|
|
|
// namespacing is just putting things in a table
|
2018-11-10 22:41:06 +08:00
|
|
|
// forces creation if it does not exist
|
|
|
|
auto bark = lua["bark"].get_or_create<sol::table>();
|
|
|
|
// equivalent-ish:
|
2021-03-06 14:03:23 +08:00
|
|
|
// sol::table bark = lua["bark"].force(); // forces table creation
|
2018-11-10 22:41:06 +08:00
|
|
|
// equivalent, and more flexible:
|
2021-03-06 14:03:23 +08:00
|
|
|
// sol::table bark = lua["bark"].get_or_create<sol::table>(sol::new_table());
|
2018-11-10 22:41:06 +08:00
|
|
|
// equivalent, but less efficient/ugly:
|
2021-03-06 14:03:23 +08:00
|
|
|
// sol::table bark = lua["bark"] = lua.get_or("bark", lua.create_table());
|
|
|
|
bark.new_usertype<my_class>("my_class", "f", &my_class::f, "g", &my_class::g); // the usual
|
2017-09-25 04:36:45 +08:00
|
|
|
|
|
|
|
// can add functions, as well (just like the global table)
|
|
|
|
bark.set_function("print_my_class", [](my_class& self) { std::cout << "my_class { b: " << self.b << " }" << std::endl; });
|
2016-09-09 19:48:28 +08:00
|
|
|
|
2017-09-25 04:36:45 +08:00
|
|
|
// this works
|
|
|
|
lua.script("obj = bark.my_class.new()");
|
2016-09-09 19:48:28 +08:00
|
|
|
lua.script("obj:g()");
|
2017-09-25 04:36:45 +08:00
|
|
|
|
|
|
|
// calling this function also works
|
|
|
|
lua.script("bark.print_my_class(obj)");
|
2016-09-09 19:48:28 +08:00
|
|
|
my_class& obj = lua["obj"];
|
2021-03-06 14:03:23 +08:00
|
|
|
sol_c_assert(obj.b == 25);
|
2016-09-09 19:48:28 +08:00
|
|
|
|
2017-09-25 04:36:45 +08:00
|
|
|
std::cout << std::endl;
|
|
|
|
|
2016-09-09 19:48:28 +08:00
|
|
|
return 0;
|
|
|
|
}
|