3

I have a std::list of objects, and I want to give Lua a function that returns its multidimensional positions. So I need to create a table of tables:

{{1,2,3...,512}, {1,2,3...,512},...,512}

lua_newtable(L);

    for (int i = 0; i < 512; i++)
    {
        lua_newtable(L);

        lua_pushnumber(L, pos[i]);
        lua_rawseti(L, -2, i);
        lua_rawseti(L, -2, i+1);

        for (int j = 0; j < 512; j++)
        {
                //pos[i][j]
        }
    }

I'd try by trial and error, but since I don't know how to debug it for now, I'm really lost.

2
  • 2
    I think you should try to reword the question so that it is more clear. What are "its multidimensional positions". Also, what are the "objects". In lua you can only push either lua primitive types, functions, userdata.... a few others. Are the things you want to push userdata, or do you have some other function at hand that knows how to push them? Is that the part you are trying to figure out or is it mainly the part about "how do I make a table of tables using the C api" Commented Aug 15, 2015 at 19:10
  • Thanks for your attention.I will study english hard. Commented Aug 16, 2015 at 2:01

2 Answers 2

3

I think you want to create nested tables (or matrix) with 512x512 dimension.

static int CreateMatrix( lua_State *L ) {
    lua_newtable( L );
    for( int i = 0; i < 512; i++ ) {
        lua_pushnumber( L, i + 1 );    // parent table index
        lua_newtable( L );             // child table
        for( int j = 0; j < 512; j++ ) {
            lua_pushnumber( L, j + 1 );  // this will be the child's index
            lua_pushnumber( L, j + 1 );  // this will be the child's value
            lua_settable( L, -3 );
        }
        lua_settable( L, -3 );
    }
    return 1;
}

You can of course, use your own values/indexes.

Sign up to request clarification or add additional context in comments.

1 Comment

That's it my want.Thank you and again :)
1

Since you know the size of the tables beforehand, you can avoid reallocating memory by using lua_createtable and some overhead by using rawseti.

static int make_matrix(lua_State *L) {
    lua_createtable(L, 512, 0);
    for (int i = 0; i < 512; ++i) {
        lua_createtable(L, 512, 0);
        for (int j = 0; j < 512; ++j) {
           lua_pushnumber(L, i + j);  // push some value, e.g. "pos[i][j]"
           lua_rawseti(L, -2, j + 1);
        }
        lua_rawseti(L, -2, i + 1);
    }
    return 1;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.