Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#include <Siv3D.hpp>
#include <memory>
// Console app
#pragma comment(linker, "/SUBSYSTEM:CONSOLE")
// Lua 5.2.x (need 'lua52.dll' at runtime)
#include <lua.hpp>
#pragma comment(lib, "lua52.lib")
// Sol 2.14
#include <sol.hpp>
// User-defined type
class A
{
public:
A(const int val) : val_(val)
{
}
virtual void f()
{
std::cout << "A::f() " << val() << "\n";
}
const int val() { return val_; }
private:
int val_ = 0;
};
// User-defined type (derived)
class B : public A
{
public:
using A::A;
virtual void f() override
{
std::cout << "B::f() " << val() << "\n";
}
};
void Main()
{
// Init Sol
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::package, sol::lib::math, sol::lib::coroutine);
// Register function
lua["func"] = [](A* a) {
std::cout << "func()\n";
a->f();
};
// Register user-defined types
lua.new_usertype<A>("A",
sol::constructors<sol::types<const int>>(),
"f", &A::f,
"val", &A::val
);
lua.new_usertype<B>("B",
sol::constructors<sol::types<const int>>(),
sol::base_classes, sol::bases<A>()
);
// Run script
lua.script(
"a = A.new(100)\n"
"b = B.new(200)\n"
"a:f()\n"
"b:f()\n"
"func(a)\n"
"func(b)"
);
lua.script(
"function luafunc(a)\n"
" print(\"luafunc()\")\n"
" a:f()\n"
"end"
);
// Call Lua function
std::shared_ptr<A> a = std::make_shared<A>(300);
lua["luafunc"](a);
std::shared_ptr<B> b = std::make_shared<B>(400);
lua["luafunc"](b);
WaitKey();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment