我发现Luabridge在执行这些任务时非常方便。它是一个仅适用于较旧 C++ 代码(c++11 之前及之后)的标头库。
您不直接针对 Lua 堆栈进行编程,而是将普通类/结构包装到绑定定义中。
绑定代码如下所示:
getGlobalNamespace(L).beginNamespace("GameFrameworkName")
.beginClass<RectF>("Rect")
.addStaticFunction("__call", &RectF_Ctor) // Constructor from Table!
.addData<float>("x", &RectF::x)
.addData<float>("y", &RectF::y)
.addData<float>("width", &RectF::width)
.addData<float>("height", &RectF::height)
.addFunction("Union", &RectF::Union)
.addFunction("Intersects", (bool (RectF::*)(const RectF&)) &RectF::Intersects)
.addFunction("Intersection", &RectF::Intersection)
.addFunction("Contains", (bool (RectF::*)(const PointF&)) &RectF::Contains)
.addFunction("Offset", (void (RectF::*)(const PointF&)) &RectF::Offset)
.addFunction("Inflate", (void (RectF::*)(float, float)) &RectF::Inflate)
.addFunction("__tostring", &RectF_ToString)
.addFunction("__eq", (bool (RectF::*)(const RectF&)) &RectF::operator==)
.addFunction("Copy", &RectF_Copy)
.endClass()
.beginClass<PointF>("Point")
.addStaticFunction("__call", &PointF_Ctor) // Constructor from Table!
.addData<float>("x", &PointF::x)
.addData<float>("y", &PointF::y)
.addFunction("__tostring", &PointF_ToString)
.addFunction("__add", (PointF (PointF::*)(const PointF&)) &PointF::operator+ )
.addFunction("__sub", &PointF_SubtractOperator )
.addFunction("__mul", &PointF_MultiplyOperator )
.addFunction("__div", &PointF_DivideOperator )
.addFunction("__eq", (bool (PointF::*)(const PointF&)) &PointF::operator==)
.addFunction("__unm", &PointF_Unm)
.addFunction("Copy", &PointF_Copy)
.endClass()
.endNamespace();
对于游戏对象,我通常会在 C++ 中管理生命周期,并将指针传递给 Lua。Luabind 允许您覆盖 Lua CTor (__call) 和 ~Tor (__gc)。这是我的副本:
template<typename T>
std::string DoNotCreate()
{
DBG_ASSERT(false); // Do not try to create a new instance of this type
return StrFormat("ERROR: Lua cannot create an instance of %s.", typeid(T).name());
}
///////////////////////////////////////
// \brief Do Not Allow Lua or Luabridge to delete us
void DoNotGarbageCollect(void*) {}
以及它们的用途:
.deriveClass<Sprite, DisplayObject>("Sprite")
.addStaticFunction("__call", &DoNotCreate<Sprite>)
.addFunction("__gc", (void (*) (Sprite*)) &DoNotGarbageCollect)
要从 C++ 调用 Lua 代码,您可以使用 LuaRefs,它 (IIRC) 基本上是可以是任何 Lua 类型的变体。
如果你有兴趣,我发现Zerobrane是一个很好的调试器,你只需要添加套接字 lua 库