Luaから疑似クラスを受け取ってC++で実行する

前回の記事の疑似クラス版。

luabind::objectはもちろんテーブルを受け取れるので疑似クラスも扱えます。テーブル内の関数や変数を見つけるのはoperator[]で可能です。
#include <lua.hpp>
#include <lualib.h>
#include <luabind/luabind.hpp>

int main()
{
    ::lua_State* L = ::lua_open();
    ::luaL_openlibs(L);
    ::luabind::open(L);

    if( ::luaL_loadfile(L,"test.lua") == 0 )
    {
        ::lua_pcall(L,0,0,0);
        ::luabind::object const tbl = ::luabind::call_function<::luabind::object>(L,"get_table");

        assert(::luabind::type(tbl) == LUA_TTABLE);
        assert(::luabind::type(tbl["count"]) == LUA_TNUMBER);
        assert(::luabind::type(tbl["homu"]) == LUA_TFUNCTION);
        assert(::luabind::type(tbl["homuhomu"]) == LUA_TFUNCTION);

        tbl["count"] = 5;
        ::luabind::call_function<void>(tbl["homu"],tbl);
        ::luabind::call_function<void>(tbl["homuhomu"],tbl);
    }
}
-- Lua
function get_table()
    local tbl = {}

    tbl.count = 1
    tbl.homu = function( self )
        print("homu",string.format("count : %d",self.count))
    end
    tbl.homuhomu = function( self )
        print("homuhomu",string.format("count : %d",self.count))
    end

    return tbl
end
// 実行結果
homu    count : 5
homuhomu    count : 42
luabind::call_functionで疑似クラスのメソッドを呼び出す際に第1引数にtblを渡してるのはself(クラス自身のインスタンス)を渡してるためです。