简体   繁体   中英

How to access multidimensional table from lua in C?

Hello I am really stumped with this seemingly simple task. I can access the properties of a table passed to a function in C, but cannot access the members of any subtable i create in it.

Basically I want to simply be able to extract the strings from the properties table so i can create say a "wheel" according to the users expectations.

Here is what I have so far (tried so much my brain is fried)

Lua Side:

--Function
createSomething( "wheel", { canInflate = true, properties = { "large", "full" } } )

C Side:

//I can retrieve any value easily within that table, but cannot seem to extract the table
//Within it named "properties", i can access the table, but cannot extract the strings     inside

if( lua_istable(L, 2) ) {
    lua_getfield(L, 2, "canInflate");  // Let's extract the value for the key 'someKey'. Pushes the value on the top of the stack
    static int canInflate = lua_toboolean(L, -1); // get the value of bool now at the top of stack (index: -1)

    //printf("can inflate is %d\n", canInflate);
    //lua_pop(L, 1); // pop the value now that we are done with it
}


//try to get the properties table
if ( lua_istable(L, 2) ) {
    lua_getfield(L, 2, "properties");

    const char *str = lua_tostring(L, -1);

    printf( "properties 1 = %s\n", str); // NULL

    lua_pop(L, 2);
}

Any help on this would be greatly appreciated

The problem you're having is with how you specify tables in Lua: the following 3 statements have exactly the same result:

t = { 'full','large'}
t = { [1] = 'full', [2] = 'large'}
t={};t[1]='full';t[2]='large'

What you want is to use the strings as keys instead of values (as is done in your code and the above samples):

t={full=true,large=true}
-- or 
t={}; t.full=true; t.large=true

If you use the strings as keys your C code should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM