c - lua 函数的警报消息

标签 c lua lua-api

我有以下代码:

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;");

代码完美运行。我想知道是否可以只保留一条消息并且这适用于每个函数的问题:

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);

最佳答案

像这样的宏(未经测试并在SO编辑框中编写):

#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)

会让你做这样的事情:

lua_getglobal(L, "lgd");

GET_INTEGER_WARN(-1, value_pos_x);

GET_INTEGER_WARN(-2, value_pos_y);

GET_INTEGER_WARN(-3, time);

像这样的函数(与之前相同的注意事项):

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);
}

会让你做这样的事情:

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")

关于c - lua 函数的警报消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33652665/

相关文章:

包含子包的 Lua 包

c - 如何在 C 中以任何预处理器指令形式定义一组配置

c - C程序的内存分析

lua - 如何忽略Luacheck警告?

lua - 如何在Lua中创建一个唯一字符串表?

c++ - luabind 如何隐式转换对象?

c - 指向文字值的指针

C 指针挫折 EXC_BAD_ACCESS

lua - 如何从c函数回调lua函数

c - 从同一表字段调用 C 函数时获取表作为自动参数