2013-05-03 104 views

回答

0

Lua中沒有方法的任何真實的概念,只是函數表,所以你可以寫Lua代碼,看起來很OO」 ISH:

foo = test.Foo() # will call the C++ Foo constructor and return a wrapped (Lua) Foo 
myInt = foo:Bar() 

當你寫

myInt = foo:Bar() 

Lua是實際執行

myInt = foo.Bar(foo) 

這將導致的Lua在富元表中尋找一個名爲酒吧功能,並給它foo的實例作爲第一個參數。因此,你必須做的是沿着下面的僞代碼(未測試,有可能語法錯誤,參數等錯誤的訂單,但希望你的想法)的線路更多:

%native(Bar) int Bar(lua_State * L); 

%{ 
int Bar(lua_State*L) { 
    // there should be one arg on the stack: the Foo instance 
    Foo* foo = (Foo*)<get void* from L stack> 
    int answer = foo.Bar(); 
    // push answer onto L stack 
    lua_pushnumber(L, answer); 
    return 1; 
} 
%} 

%luacode { 
    test.Foo.Bar = test.Bar 
} 
... 
%} 

的%luacode品牌Bar作爲Foo「class」的一部分提供,儘管我在該區域有點生疏,但您可能需要添加Bar代替Foo metatable,或者從C中進行添加(請參閱SWIG用戶指南的第5.6節以瞭解部分.i文件,你可以嘗試這樣做)。

想知道這是否有效。

1

在您綁定.i文件,在年底包括此代碼:

%wrapper %{ 
// This is code to add a new function to the object's metatable 
void script_addNativeMethod(lua_State *L, const char *className, const char *methodName, lua_CFunction fn) 
{ 
    SWIG_Lua_get_class_registry(L); /* get the registry */ 
    lua_pushstring(L, className); /* get the name */ 
    lua_rawget(L,-2);    /* get the metatable itself */ 
    lua_remove(L,-2);    /* tidy up (remove registry) */ 

    // If the metatable is not null, add the method to the ".fn" table 
    if(lua_isnil(L, -1) != 1) 
    { 
     SWIG_Lua_get_table(L, ".fn"); 
     SWIG_Lua_add_function(L, methodName, fn); 
     lua_pop(L, 2);    /* tidy up (remove metatable and ".fn" table) */ 
    } 
    else 
    { 
     printf("[script_addNativeMethod(..)] - \"%s\" metatable is not found. Method \"%s\" will not be added\n", className, methodName); 
     return; 
    } 
} 
%} 

這樣做是增加了一個新功能,叫做「script_addNativeMethod」包裝CPP文件。你可以調用這個函數中的「初始化」綁定代碼如下所示:

// Wrapper to add native Lua methods to existing C++ classes 
%init %{ 
    script_addNativeMethod(L, "MetatableName", "methodName", /*int function(lua_State *L)*/function); 
%} 

以上這一切,在裝訂文件,你需要有一個要作爲用戶數據的方法,使用實際的本地LUA功能:

%{ 
int function(lua_State *L) 
{ 
    printf("Method called!\n"); 
    return 0; 
} 
%} 

我幾乎只是想通了這一點,我想因爲這個網頁排名在谷歌高,這是一個相當不錯的解決方案,把工作做在這裏發佈。這需要在您使用SWIG編寫的每個包裝器綁定(* .i)文件中完成。

祝你好運!