2011-03-23 80 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更快。