【问题标题】:Alert messages for lua functionslua 函数的警报消息
【发布时间】:2016-02-12 16:03:19
【问题描述】:

我有以下代码:

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

【问题讨论】:

  • 我不明白这个问题。您当然可以编写一个“帮助”函数来减少这些行中的重复以获取“整数”值,但这并不完全是它的样子。
  • 为了更好地理解而编辑的主题,我打算做的是一条消息,说 lua_tointeger 只接受数字,例如,如果我使用字符串或布尔值,它会显示警报消息。
  • 是的,您希望能够轻松处理少量“整数”值并在它们无效时发出警报。您可以轻松地将现有代码重构为一个帮助函数,它可以让您这样做,而不是每次都复制整个行集。你有没有尝试过?我不确定你认为lua_tointeger() != lua_isinteger() 会为你做什么(因为它们分别返回一个lua_Integer 和一个布尔值int),但是检查你得到一个有效的整数肯定是可能的。
  • 我该怎么办?通过检查仅发生在lua_getfield (L, -3, "time"); 中,其他两个无法阅读该消息。另一个问题是如何捕获 lua_getfield 名称,例如:The entry value_pos_x is invalid;
  • 宏可以按原样替换这些行(并且还包括最后的行和错误消息)。一个函数可以替换除赋值之外的所有内容(这可以通过函数的返回值或类似方法来完成)。

标签: c lua lua-api


【解决方案1】:

类似这样的宏(未经测试并在 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")

【讨论】:

  • Etan 你帮助我了解了如何进行。现在最后一个问题是函数 cr-> 是否与 lua_getfield 不同,因为我可以进行检查。例如:lua_getfield(L, -1, "value_time_expire"); cr->expire = lua_tointeger(L, -1);
  • 宏版本要求相同。功能版本没有。函数版本将分配给您的 cr 结构与 lua 端键名分开。你绝对可以做cr->expire = get_integer_warn(L, -3, "value_time_expire") 或其他任何事情。
  • 我明白了,谢谢 Etan 的解释,问题解决了。
猜你喜欢
  • 1970-01-01
  • 2013-07-18
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
  • 1970-01-01
  • 1970-01-01
  • 2017-03-15
  • 2016-10-29
相关资源
最近更新 更多