3

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

1 Answer 1

2

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");
Sign up to request clarification or add additional context in comments.

3 Comments

Just a question. Would the lua_getfield index for Require_var have a value of -2?
No If you would follow this, the index is -4, -1 => Request; -2 => Value; -3 => Consume_first; -4 => Consume.
Got it, I'll read more about the lua index.

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.