Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an array as table from C function to lua?

Tags:

c

lua

I need impelement a C function for lua script to call.I shall return an array as table from that function.I used the code blow but crashed.Could anyone tell me how to use it?


struct Point {
    int x, y;
}
typedef Point Point;


static int returnImageProxy(lua_State *L)
{
    Point points[3] = {{11, 12}, {21, 22}, {31, 32}};

    lua_newtable(L);

    for (int i = 0; i  3; i++) {
        lua_newtable(L);
        lua_pushnumber(L, points[i].x);
        lua_rawseti(L, -2, 2*i+1);
        lua_pushnumber(L, points[i].y);
        lua_rawseti(L, -2, 2*i+2);
        lua_settable(L,-3);
    }

    return 1;   // I want to return a Lua table like :{{11, 12}, {21, 22}, {31, 32}}
}

like image 447
Suge Avatar asked Aug 28 '13 11:08

Suge


People also ask

How do I insert a table into Lua?

In Lua, the table library provides functions to insert elements into the table. The insert function usually takes two arguments, the first argument is usually the name of the table from which we want to insert the element to, and the second argument is the element that we want to insert.

Are there arrays in Lua?

In Lua, arrays are implemented using indexing tables with integers. The size of an array is not fixed and it can grow based on our requirements, subject to memory constraints.

How big can a Lua table be?

The table type implements associative arrays. An associative array is an array that can be indexed not only with numbers, but also with strings or any other value of the language, except nil. Moreover, tables have no fixed size; you can add as many elements as you want to a table dynamically.

How do you call ac function from Lua?

Moreover, for a C function to be called from Lua, we must register it, that is, we must give its address to Lua in an appropriate way. When Lua calls a C function, it uses the same kind of stack that C uses to call Lua. The C function gets its arguments from the stack and pushes the results on the stack.


2 Answers

Need to change the lua_settable as @lhf mentions. Also, you are always adding into the first 2 indices of the sub-tables

typedef struct Point {
    int x, y;
} Point;


static int returnImageProxy(lua_State *L)
{
    Point points[3] = {{11, 12}, {21, 22}, {31, 32}};

    lua_newtable(L);

    for (int i = 0; i < 3; i++) {
        lua_newtable(L);
        lua_pushnumber(L, points[i].x);
        lua_rawseti(L, -2, 1);
        lua_pushnumber(L, points[i].y);
        lua_rawseti(L, -2, 2);

        lua_rawseti(L, -2, i+1);
    }

    return 1;   // I want to return a Lua table like :{{11, 12}, {21, 22}, {31, 32}}
}
like image 161
Alex Avatar answered Sep 23 '22 01:09

Alex


Try replacing lua_settable(L,-3) with lua_rawseti(L,-2,i+1).

like image 22
lhf Avatar answered Sep 26 '22 01:09

lhf