2011-03-23 38 views
0

我是Lua的新手,對我很袒護! 我真的不想去掉metatables等路由,因爲它看起來很複雜。 目前以粗製濫造訪問 'C' 在Lua結構我做的:Lua以'C'呼叫約定問題

void execute_lua_script(char *name) 
{ 
    lua_pushstring (L,name); 
    lua_gettable (L, LUA_GLOBALSINDEX); 
    lua_pushstring(L,"junk"); 
    lua_pushinteger(L,7); 
    lua_pushlightuserdata(L, avatar_obj); 
    lua_pcall (L, 3, 2, 0); 
} 

註冊ÇFUNC是:

int get_obj_struct(lua_State *L) 
{ 
    const char *str; 
    OBJECT_DEF *obj; 
    int stack; 

    obj=(OBJECT_DEF *)lua_touserdata(L,1); 

    str=lua_tostring(L,2); 

    //printf("\nIN OBJ:%d %s",obj,str); 

    if (!strcmp(str,"body->p.x")) 
     lua_pushnumber(L,obj->body->p.x); 

    if (!strcmp(str,"collided_with")) 
     lua_pushlightuserdata(L, obj->collided_with); 

    if (!strcmp(str,"type")) 
     lua_pushnumber(L,obj->type); 

    stack=lua_gettop(L); 
    //printf("\n%d",stack); 

    if (stack<3) 
     report_error("Unknown structure request ",(char *)str); 

    return 1; 
} 

雖然原油;有用! :-) 問題是當我請求「collided_with」(一個指針)時;我需要把它還給我的腳本。但由於我不明白的原因,'obj'最終爲零。

我的LUA腳本:

function test(a,b,obj) 
    --print("\nLUA! test:",a,b); 

    b=b+1; 

    c=get_obj_struct(obj,"body->p.x"); 

    --print("x:",c); 

    collided_with=get_obj_struct(obj,"collided_with"); 
    type=get_obj_struct(collided_with,"type"); 

    print("type:",type); 

    return a,b; 
end 

我期待「collided_with」是一個指針,我可以再通過回get_obj_struct並查找類型。 我知道這是與我錯誤使用pushlightuserdata和也閱讀obj。 所以一個解釋將是偉大的!另外如果有人希望給出一個使用「表格」的版本(因爲我認爲這會更有效),那麼我會很感激這個幫助。

乾杯

回答

1

在線「Programming In Lua」一書提供瞭如何實現C. Lua的類型。在我看來,一個很好的說明,你最好的選擇將遵循Chapter 28提供的「做正確」的例子併爲你的對象創建一個完整的Lua包裝器。除了易於維護之外,它幾乎肯定會比基於實施的strcmp更快。