0

基本的には、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;
}
4

1 に答える 1

3

Lua 内で作成済みの C++ クラスの関数を呼び出せるようにします。

Luabind を使用してクラスを作成し、そのクラスのメンバーを提供すると、Luabind はまさにそれを行います。メンバーを持つ Lua にクラスを公開します。

そのクラスの型のオブジェクトなしでは、C++ でメンバー関数を呼び出すことはできません。したがって、クラスとそのメンバーを Luabind を介して公開すると、そのクラスの型のオブジェクトがないと、Lua でメンバー関数を呼び出すことができなくなります。

したがって、グローバルManagerオブジェクトがある場合、これを Lua に公開する適切な方法は、オブジェクト自体を Lua に公開することです。Luabind を使用してグローバル テーブルを取得し、そこに Manager オブジェクトへのポインタを置きます。Managerまたは、スクリプトの実行時にオブジェクト インスタンスをパラメータとして渡すこともできます。

2 番目の方法は次のように機能します。

//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 の varargs メカニズムを使用してインスタンスを取得できます。

local manager = ...
manager:newObject("Object", 1234)
manager:printAll()
于 2011-09-16T01:21:33.240 に答える