如何在Lua 5.3中注册一个C ++类和函数 [英] How can I register a C++ class and function in Lua 5.3

查看:217
本文介绍了如何在Lua 5.3中注册一个C ++类和函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直使用这个游戏引擎一段时间,我可以创建一个使用内置事件的游戏,或者我可以使用C ++,但我最近试图嵌入Lua 5.3,但我有一个问题,如何注册一个特定的C ++类Lua,例如:
在游戏引擎的C ++中,我会改变背景颜色,如下:

So I've been using this game engine for quite some time, I can create a game using that with either the built-in events or I can use C++ but I've recently tried to embed Lua 5.3 to it, but I'm having problems on how to register a certain C++ class to Lua, example: In the game engine's C++, I would change the background color like this:

#include "GDCpp/RuntimeScene.h"

void changeBackground(RuntimeScene & scene)
{
     scene.SetBackgroundColor(250,100,85)
}

但我的问题是,我该怎么做在Lua?如何在Lua 5.3中注册该函数和类?

But my problem is, how can I do that in Lua ? how can I register that function and class in Lua 5.3?

推荐答案

this example。

您创建/请求 metatable 与类名称,推成员函数(除了构造函数)到他和注册一个构造函数,它返回你的类作为userdata,链接metatable。

You create/request a metatable with the class name, push member functions (except constructor) into him and register a constructor function which returns your class as userdata, linked with the metatable.

需要在自表上设置字段__index,以便以后的成员访问引导metatable,而不是userdata。 __gc发生在垃圾收集 - 你的析构函数。因为Lua是用C编写的,所以分配userdata内存不会调用构造函数,所以类实例放在堆上,地址传递给Lua。

Setting field "__index" on self table is required that later member access leads to the metatable, not userdata. "__gc" happens on garbage collection - your destructor. Because Lua is written in C, allocating userdata memory doesn't invoke constructors, so the class instance was put on the heap and the address passed to Lua.

这篇关于如何在Lua 5.3中注册一个C ++类和函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆