开发者

Lua to 'C' calling convention issues

开发者 https://www.devze.com 2023-02-19 10:11 出处:网络
I don\'t really want to go down the metatables etc. route as it seems rather complicated. To crudely access \'C\' structs in Lua I do:

I don't really want to go down the metatables etc. route as it seems rather complicated. To crudely access 'C' structs in Lua I do:

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);
}

The registered C func is:

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;
}

Although crude; it works! :-) The problem is when I request "collided_with" (a pointer); I need to return that back to my script; but for reasons I don't understand 'obj' ends up as nil.

My lua script:

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;
e开发者_运维知识库nd

I am expecting 'collided_with' to be a pointer that I can then pass back into get_obj_struct and look for type. I know it's something to do with me mis-using pushlightuserdata and also reading for the obj. So an explanation would be great!. Also if someone wishes to give a version that uses 'tables' (as I assume that would be much more efficient) then I would be grateful for the help.


The online "Programming In Lua" book provides a good description of how to implement Lua types in C. In my opinion, your best bet would be to follow the examples provided in Chapter 28 to "do it right" and create a complete Lua wrapper for your object. In addition to being easier to maintain, it will almost certainly be more faster than a strcmp based implementation.

0

精彩评论

暂无评论...
验证码 换一张
取 消