Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following code:

lua_getglobal(L, "lgd");

lua_getfield(L, -1, "value_pos_x");
cr->value_pos_x = lua_tointeger(L, -1);

if (!lua_isinteger(L, -1))
    printf("value_pos_x allows only numbers;");

lua_getfield(L, -2, "value_pos_y");
cr->value_pos_y = lua_tointeger(L, -1);

if (!lua_isinteger(L, -1))
    printf("value_pos_y allows only numbers;");

lua_getfield(L, -3, "time");
    cr->time = lua_tointeger(L, -1);

if (!lua_isinteger(L, -1))
    printf("time allows only numbers;");

The code works perfectly. The question I wanted to know if it is possible to keep only one message and that would apply to each function for example:

lua_getglobal(L, "lgd");

lua_getfield(L, -1, "value_pos_x");
cr->value_pos_x = lua_tointeger(L, -1);

lua_getfield(L, -2, "value_pos_y");
cr->value_pos_y = lua_tointeger(L, -1);

lua_getfield(L, -3, "time");
cr->time = lua_tointeger(L, -1);

if (lua_tointeger(L, -1) != lua_isinteger(L, -1))
        printf("The entry %s is invalid;", capture_lua_getfield_name);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
180 views
Welcome To Ask or Share your Answers For Others

1 Answer

A macro something like this (untested and written in SO editing box):

#define GET_INTEGER_WARN(ind, fld) do { 
    lua_getfield(L, ind, #fld); 
    cr->fld = lua_tointeger(L, -1); 
    
    if (!lua_isinteger(L, -1)) 
        printf(#fld" allows only numbers;"); 
    } while (0)

Would let you do something like this:

lua_getglobal(L, "lgd");

GET_INTEGER_WARN(-1, value_pos_x);

GET_INTEGER_WARN(-2, value_pos_y);

GET_INTEGER_WARN(-3, time);

A function like this (same caveats as before):

lua_Integer
get_integer_warn(lua_State *L, int ind, char *fld)
{
    lua_getfield(L, ind, fld);

    if (!lua_isinteger(L, -1))
        printf("%s allows only numbers", fld);

    return lua_tointeger(L, -1);
}

Would let you do something like this:

cr->value_pos_x = get_integer_warn(L, -1, "value_pos_x")
cr->value_pos_y = get_integer_warn(L, -2, "value_pos_y")
cr->time = get_integer_warn(L, -3, "time")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...