Pass C struct to lua script

Asked

Viewed 153 times

1

When I got past my frame Book to the script in Moon, the method writes the value as nil.

How I pass the structure Book to my moon code?

main. c:

#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

#include <stdio.h>

lua_State *lua_lib;

typedef struct{
    char name[512];
    char author[512];
    int age;
}Book;

void save_in_list(int index, void *data){
    lua_getglobal(lua_lib, "insert");
    lua_pushinteger(lua_lib, index);
    lua_pushvalue(lua_lib, data);

    lua_call(lua_lib, 2, 0);
}

int main(int argc, char **argv){
    lua_lib = luaL_newstate();
    luaL_openlibs(lua_lib);

    if(luaL_dofile(lua_lib, "list.lua")){
        lua_close(lua_lib);
        puts("file not load");
        return 1;
    }

    Book *b1 = malloc(sizeof(Book));
    Book *b2 = malloc(sizeof(Book));

    strcpy(b1->name,"Avenger");
    strcpy(b1->author,"Fulano");
    b1->age = 2010;
    strcpy(b2->name,"Chapolim");
    strcpy(b2->author,"Chaves");
    b2->age = 1990;

    save_in_list(0, b1);
    save_in_list(1, b2);
}

list.moon:

list = {
    data = {}
}

function list:count()
    return table.maxn(self.data)
end

function list:get(index)
    return self.data[index+1]
end

function list:insert(index, value)
    table.insert(self.data, (index+1), value)
end

function count()
    return list:count()
end

function get(index)
    return list:get(index)
end

function insert(index, value)
    print(value)
    list:insert(index, value)
end

1 answer

0


Problem solved!

lua_pushvalue(lua_lib, data);

was replaced by:

lua_pushlightuserdata(lua_lib, data);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.