1.packageファイルとヘッダファイルを作る
$#include "test.h"
class CTest
{
public:
CTest(); // これを省略するとlua側でnew出来ない
char* a();
};
#include <stdio.h>
class CTest
{
public:
char* a () { return "A"; }
};
2.toluaでpackageをcppに変換する
> tolua -o test.cpp test.pkg
/*
** Lua binding: test
** Generated automatically by tolua 5.0a on 10/28/05 12:30:00.
*/
#ifndef __cplusplus
#include "stdlib.h"
#endif
#include "string.h"
#include "tolua.h"
/* Exported function */
TOLUA_API int tolua_test_open (lua_State* tolua_S);
#include "test.h"
/* function to register type */
static void tolua_reg_types (lua_State* tolua_S)
{
tolua_usertype(tolua_S,"CTest");
}
/* method: a of class CTest */
static int tolua_test_CTest_a00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"CTest",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
CTest* self = (CTest*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'a'",NULL);
#endif
{
char* tolua_ret = (char*) self->a();
tolua_pushstring(tolua_S,(const char*)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'a'.",&tolua_err);
return 0;
#endif
}
/* Open function */
TOLUA_API int tolua_test_open (lua_State* tolua_S)
{
tolua_open(tolua_S);
tolua_reg_types(tolua_S);
tolua_module(tolua_S,NULL,0);
tolua_beginmodule(tolua_S,NULL);
tolua_cclass(tolua_S,"CTest","CTest","",NULL);
tolua_beginmodule(tolua_S,"CTest");
tolua_function(tolua_S,"a",tolua_test_CTest_a00);
tolua_endmodule(tolua_S);
tolua_endmodule(tolua_S);
return 1;
}
3.ビルドする
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
#include "test.h"
int main ()
{
int tolua_test_open (lua_State*); // 自動作成された関数プロトタイプ
lua_State* L = lua_open();
luaopen_base(L);
tolua_test_open(L); // ここで自動作成された関数をよぶ
lua_dofile(L,"test.lua");
lua_close(L);
return 0;
}
local ct = CTest:new();
print(ct:a());
all:
g++ -IC:/tolua-5.0/include -LC:/tolua-5.0/lib test.cpp main.cpp -ltolua -llua -llualib