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-10-12 22:20:57 +08:00
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
|
|
|
|
#include <memory>
|
|
|
|
#include <mutex>
|
|
|
|
|
|
|
|
struct SomeLib {
|
|
|
|
private:
|
2021-03-06 14:03:23 +08:00
|
|
|
SomeLib() {
|
|
|
|
}
|
|
|
|
|
2017-10-12 22:20:57 +08:00
|
|
|
public:
|
|
|
|
static std::shared_ptr<SomeLib> getInstance();
|
|
|
|
|
|
|
|
int doSomething() const {
|
|
|
|
return 20;
|
|
|
|
}
|
|
|
|
|
2021-03-06 14:03:23 +08:00
|
|
|
// destructor must be public to work with
|
2017-10-12 22:20:57 +08:00
|
|
|
// std::shared_ptr and friends
|
|
|
|
// if you need it to be private, you must implement
|
|
|
|
// a custom deleter with access to the private members
|
|
|
|
// (e.g., a deleter struct defined in this class)
|
2021-03-06 14:03:23 +08:00
|
|
|
~SomeLib() {
|
|
|
|
}
|
2017-10-12 22:20:57 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
std::shared_ptr<SomeLib> SomeLib::getInstance() {
|
|
|
|
static std::weak_ptr<SomeLib> instance;
|
|
|
|
static std::mutex m;
|
|
|
|
|
|
|
|
m.lock();
|
|
|
|
auto ret = instance.lock();
|
|
|
|
if (!ret) {
|
|
|
|
ret.reset(new SomeLib());
|
|
|
|
instance = ret;
|
|
|
|
}
|
|
|
|
m.unlock();
|
|
|
|
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
|
|
|
|
int main(int, char*[]) {
|
2018-03-16 05:16:28 +08:00
|
|
|
std::cout << "=== singleton ===" << std::endl;
|
2017-10-12 22:20:57 +08:00
|
|
|
|
|
|
|
sol::state lua;
|
|
|
|
lua.open_libraries(sol::lib::base);
|
|
|
|
|
2021-03-06 23:14:48 +08:00
|
|
|
lua.new_usertype<SomeLib>("SomeLib",
|
|
|
|
"new",
|
|
|
|
sol::no_constructor,
|
|
|
|
"getInstance",
|
|
|
|
&SomeLib::getInstance,
|
|
|
|
"doSomething",
|
|
|
|
&SomeLib::doSomething);
|
2017-10-12 22:20:57 +08:00
|
|
|
|
|
|
|
lua.script(R"(
|
|
|
|
|
|
|
|
-- note we use the `.` here, not `:` (there's no self to access)
|
|
|
|
local sli = SomeLib.getInstance()
|
|
|
|
|
|
|
|
-- we use the `:` here because there is something to access
|
|
|
|
local value = sli:doSomething()
|
|
|
|
|
|
|
|
-- check
|
|
|
|
print('sli:doSomething() returned:', value)
|
|
|
|
assert(value == 20)
|
|
|
|
)");
|
|
|
|
|
|
|
|
std::cout << std::endl;
|
|
|
|
return 0;
|
|
|
|
}
|