Home > front end >  How to read complex lua table using c code
How to read complex lua table using c code

Time:11-22

I'm starting in the world of lua currently I'm creating table readings using C code

I have a table that looks like this:

Consume = 
{
    Consume_first = {
        Value = 100
        Request = 200
    },
    Require_var = {
        Enable= true
        Name = "Am"
    
    }
}

I would like to know some information

Consume is defined as lua_getglobal(L, "Consume");

Value, Request, Enable and Name would the lua_getfield function be used?

Example:

lua_getfield(L, 1, "Value")

And in Consume_first and Require_var what should I use to define them?

My code:

void read_table(void) {
    lua_State *L;
    L = luaL_newstate();
    luaL_openlibs(L);

    if (luaL_loadfile(L, "table.lua") || lua_pcall(L, 0, 0, 0))
    {
        ShowError("Error reading 'table.lua'\n");
        return;
    }

    lua_getglobal(L, "Consume");
    .... 
    lua_getfield(L, -1, "Value");
    lua_getfield(L, -1, "Request");
    ....
    lua_getfield(L, -1, "Enable");
    lua_getfield(L, -1, "Name");

    lua_close(L);
    printf("Read Table complete.\n");

}

I'm using lua 5.4

CodePudding user response:

Something like this:

lua_getglobal(L, "Consume");

// Get Consume.Consume_first
lua_getfield(L, -1, "Consume_first");

// Get Consume.Consume_first.Value
lua_getfield(L, -1, "Value");

// Get Consume.Consume_first.Request
// Note that currently Consume.Consume_first.Value is on the stack
// So Consume.Consume_first is at index -2
lua_getfield(L, -2, "Request");

If you are confused with the index, you can also use lua_gettop to help.

lua_getglobal(L, "Consume");

// Get Consume.Consume_first
lua_getfield(L, -1, "Consume_first");
int Consume_first_index = lua_gettop(L);

// Get Consume.Consume_first.Value
lua_getfield(L, Consume_first_index, "Value");

// Get Consume.Consume_first.Request
lua_getfield(L, Consume_first_index, "Request");
  •  Tags:  
  • clua
  • Related