2013-05-03 117 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)文件中完成。

祝你好运!