tolua++によるクラスのバインド方法

1. 任意のフォルダを作成する
ここでは、apple_eaterとする。


2. 必要なファイルを作成する。
apple_eater.cpp、apple_eater.h、main.cpp、apple_eater.pkg、apple_eater.lua


3. Luaから以下のファイルをフォルダにコピー
lauxlib.h、lua.h、luaconf.h、lualib.h、lua.hpp


4. tolua++から以下のファイルをフォルダにコピー
tolua_event.c、tolua_event.h、tolua_is.c、tolua_map.c、tolua_push.c、tolua_to.c


5. 以下のコマンドでビルド
tolua++.exe -n apple_eater_glue -o apple_eater_glue.cpp -H apple_eater_glue.h apple_eater.pkg
g++ -o apple_eater.exe *.cpp *.c lua51.lib


6. apple_eater.exeの実行には、以下の2つのDLLにパスが通っている必要がある
lua51.dll、lua5.1.dll

--apple_eater.cpp
#include "apple_eater.h"

bool AppleEater::eat(int apple_num)
{
    if (m_eat_count + apple_num > 10) {
        printf("%d 個も食べられません!\n", apple_num);
        return false;
    }
    m_eat_count += apple_num;
    printf("%d 個食べます。合計: %d個\n", apple_num, m_eat_count);
    return true;
}

AppleEater *AppleEater::get_new_eater()
{
    printf("リンゴを食べてくれる人を紹介します。\n");
    return new AppleEater();
}
--apple_eater.h
#include <stdio.h>

class AppleEater
{
private:
    int m_eat_count;
public:
    AppleEater() : m_eat_count(0) {
        printf("AppleEater constructed.\n");
    }
    ~AppleEater() {
        printf("AppleEater destructed.\n");
    }
    bool eat(int apple_num);
    AppleEater *get_new_eater();
};
-- main.cpp
#include "lua.hpp"
#include "tolua++.h"
#include "apple_eater_glue.h"

int main()
{
    lua_State *L = lua_open();
    luaL_openlibs(L);
    tolua_apple_eater_glue_open(L);
    int top = lua_gettop(L);
    int ret = luaL_dofile(L, "apple_eater.lua");
    if (ret != 0) {
        printf("error: %s\n", lua_tostring(L, -1));
        return 1;
    }
    lua_settop(L, top);
    lua_close(L);

    return 0;
}
-- apple_eater.pkg
$#include "apple_eater.h"

class AppleEater
{
    AppleEater();
    ~AppleEater();
    bool eat(int apple_num);
    AppleEater *get_new_eater();
};
-- apple_eater.lua
local eater = AppleEater()
local ret = eater:eat(4)

実行結果。

> apple_eater.exe
AppleEater constructed.
4 個食べます。合計: 4個
AppleEater destructed.


Luaには例外処理がない。例えば、Cから例外を投げる関数をLuaで実行するとアプリが異常終了する。