当Lua被绑定到一个类中时,使用LuaBind在类内部调用Lua函数。

基本上,我只想在我的经理类中创建一个干净的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;
}

原文链接 https://stackoverflow.com/questions/7438594

点赞
stackoverflow用户734069
stackoverflow用户734069

如果使用 Luabind 创建一个类并提供该类的成员,那么 Luabind 就会如此操作。它会将一个具有成员的类暴露给 Lua。

在没有该类对象的情况下,您无法调用 C++ 成员函数。因此,在通过 Luabind 暴露类及其成员时,如果没有该类的对象,就无法在 Lua 中调用成员函数。

因此,如果您有一个全局 Manager 对象,则最好的方式是将该对象本身暴露给 Lua。使用 Luabind 获取全局表,然后在其中放入指向 Manager 对象的指针。或者,您可以在执行脚本时将 Manager 对象实例作为参数传递。

第二种方法的示例:

//将脚本作为 Lua chunk 加载。
//这会将该 chunk 作为一个函数推送到 Lua 栈上。
int errCode = luaL_loadfile(L, "Manager.lua");
//检查错误。

//将 Lua 栈顶的函数作为 Luabind 对象获取。
luabind::object compiledScript(luabind::from_stack(L, -1));

//通过 Luabind 调用该函数,并将 Manager 作为参数传递。
luabind::call_function<void>(compiledScript, this);

//该函数仍然在加载调用中保留在栈上。将其弹出。
lua_pop(L, 1);

您的 Lua 脚本可以使用 Lua 的 varargs 机制获取实例:

local manager = ...
manager:newObject("Object", 1234)
manager:printAll()
2011-09-16 01:21:33