【问题标题】:Use LuaBind to call Lua functions inside a class when Lua is bound inside THAT class当 Lua 绑定在那个类中时,使用 LuaBind 在一个类中调用 Lua 函数
【发布时间】:2011-11-18 07:27:17
【问题描述】:

基本上,我只想在我的 Manager 类中创建一个干净的 Lua 实例,然后将类中的函数导出到 Lua,这样我就可以在 Lua 中调用已创建的 C++ 类上的函数。

这是我目前正在考虑解决问题的方式。它可以编译,但在 Lua 中没有任何反应。

有谁知道我做错了什么,或者有没有其他建议?

Manager.lua

newObject("Object", 1234)
printAll()

Manager.h

#ifndef MANAGER_H
#define MANAGER_H
#include <iostream>
#include <vector>
#include <string>

extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
#include "luabind/luabind.hpp"
#include "Object.h"


class Manager
{
private :
    lua_State *L;
    std::vector<Object> obj;


public :
    Manager();
    void newObject(std::string t, int nm);
    void printAll();

};

#endif

Manager.cpp

#include "Manager.h"
Manager::Manager()
{
luabind::open(L);

luabind::module(L) [
    luabind::class_<Manager>("Manager")
        .def(luabind::constructor<>())
        .def("newObject", &Manager::newObject)
    ];

luaL_dofile(L, "Manager.lua");
}   

void Manager::newObject(std::string t, int nm)
{
    if(t == "Object")
    {
        Object object(nm);
        obj.push_back(object);
    }
}

void Manager::printAll()
{
    for(unsigned int i = 0; i < obj.size(); i++)
        std::cout << obj[i].getNum() << std::endl;
}

【问题讨论】:

    标签: c++ class lua luabind


    【解决方案1】:

    这样我就可以在 Lua 中调用已创建的 C++ 类上的函数了。

    如果你使用 Luabind 创建一个类,然后提供该类的成员,那么 Luabind 就会这样做。它将向具有成员的 Lua 公开一个类。

    在没有该类类型的对象的情况下,您不能在 C++ 中调用成员函数。因此,当您通过 Luabind 公开一个类及其成员时,如果没有该类类型的对象,您将无法在 Lua 中调用成员函数。

    因此,如果您有一些全局Manager 对象,将其公开给 Lua 的正确方法是将对象本身公开给 Lua。使用 Luabind 获取全局表,然后将指向 Manager 对象的指针放入其中。或者,您可以在执行脚本时将Manager 对象实例作为参数传递。

    第二种方法的工作原理如下:

    //Load the script as a Lua chunk.
    //This pushes the chunk onto the Lua stack as a function.
    int errCode = luaL_loadfile(L, "Manager.lua");
    //Check for errors.
    
    //Get the function from the top of the stack as a Luabind object.
    luabind::object compiledScript(luabind::from_stack(L, -1));
    
    //Call the function through Luabind, passing the manager as the parameter.
    luabind::call_function<void>(compiledScript, this);
    
    //The function is still on the stack from the load call. Pop it.
    lua_pop(L, 1);
    

    您的 Lua 脚本可以通过 Lua 的可变参数机制获取实例:

    local manager = ...
    manager:newObject("Object", 1234)
    manager:printAll()
    

    【讨论】:

    • 非常感谢您提供的信息。你不会碰巧有代码示例,或者知道有一个好的网站吗?我只是想弄清楚这种情况。
    • 我需要将模块的创建留在那里吗?
    • @User947871:是的。 Luabind 不是魔法。它无法解析 C++ 定义并神奇地绑定函数等。这就是 Luabind 绑定代码的用途。这段代码实际上是给 Lua 一个类的实例化来使用
    • 其实我还有一个问题。一旦我完成设置,我如何在同一个脚本中从 C++ 调用 Lua 函数。例如,我想要一个名为 keyPress() 的 Lua 函数,我想从 C++ 内部调用它。
    • 没关系,我自己可以使用 luabind::call_function(L, "keyPress");
    猜你喜欢
    • 2011-09-12
    • 2014-08-05
    • 1970-01-01
    • 2011-01-14
    • 2013-08-13
    • 1970-01-01
    • 2017-02-10
    • 2011-06-19
    • 2011-03-04
    相关资源
    最近更新 更多