从 C++ 调用 Lua 表中的函数

发布于 2024-08-14 20:14:51 字数 1129 浏览 2 评论 0原文

例如,我有一个 Lua 表/对象:

bannana

这个 Lua 表有一个其中的函数名为 chew,它采用一个

bannana.chew(5)

我也使用过的参数 SWIG,并且有一个类CPerson

class CPerson {
    public:
        // ....
        void Eat();
        // ....
};

我可以从Lua获取这个对象的实例:

person = engine:getPerson()

我需要做的是以下Lua代码:

person = engine:getPerson()
person:Eat(bannana)

其中person:eat< /code> 将调用 bannana 表中的 chew 函数,并传递一个参数。

由于 CPerson 是用 C++ 实现的,假设 CPerson 类已经有一个 Lua 状态指针,那么实现 Eat() 需要进行哪些更改?

Edit1:我不想知道如何将C++类绑定到Lua,我已经有SWIG为我做这件事,我想知道如何从C++调用Lua表内的Lua函数。

Edit2: CPerson 类和 bannana 表都是一般示例,可以假设 CPerson 类已经有一个 LuaState 指针/引用,并且 Eat 方法的函数签名可以由应答者更改。

I have for example, a Lua table/object:

bannana

And this Lua table has a function inside it called chew, that takes a parameter

bannana.chew(5)

I have also used SWIG, and have for example a class CPerson:

class CPerson {
    public:
        // ....
        void Eat();
        // ....
};

I can obtain an instance of this object from Lua:

person = engine:getPerson()

What I need to be able to do is the following Lua code:

person = engine:getPerson()
person:Eat(bannana)

Where person:eat would call the chew function in the bannana table, passing a parameter.

Since CPerson is implemented in C++, what changes are needed to implement Eat() assuming the CPerson class already has a Lua state pointer?

Edit1: I do not want to know how to bind C++ classes to Lua, I already have SWIG to do this for me, I want to know how to call Lua functions inside Lua tables, from C++.

Edit2: The CPerson class and bannana table, are both general examples, it can be assumed that the CPerson class already has a LuaState pointer/reference, and that the function signature of the Eat method can be changed by the person answering.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一紙繁鸢 2024-08-21 20:14:51

忽略任何错误检查...

lua_getglobal(L, "banana"); // or get 'banana' from person:Eat()
lua_getfield(L, -1, "chew");
lua_pushinteger(L, 5);
lua_pcall(L, 1, 0, 0);

Ignoring any error checking ...

lua_getglobal(L, "banana"); // or get 'banana' from person:Eat()
lua_getfield(L, -1, "chew");
lua_pushinteger(L, 5);
lua_pcall(L, 1, 0, 0);
农村范ル 2024-08-21 20:14:51

也许“更简单的 Cpp 绑定”会有所帮助。

Maybe "Simpler Cpp Binding" will be helpful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文