使用Lua C函数时减少重复的任何提示

vyo*_*yom 1 c lua

我有一块看起来像这样的代码:

lua_newtable(L);

lua_pushstring(L, "gid");
lua_pushinteger(L, info[i].codepoint);
lua_settable(L, -3);
lua_pushstring(L, "cl");
lua_pushinteger(L, info[i].cluster);
lua_settable(L, -3);
lua_pushstring(L, "ax");
lua_pushnumber(L, pos[i].x_advance);
lua_settable(L, -3);
lua_pushstring(L, "ay");
lua_pushnumber(L, pos[i].y_advance);
lua_settable(L, -3);
lua_pushstring(L, "dx");
lua_pushnumber(L, pos[i].x_offset);
lua_settable(L, -3);
lua_pushstring(L, "dy");
lua_pushnumber(L, pos[i].y_offset);
lua_settable(L, -3);
lua_pushstring(L, "w");
lua_pushinteger(L, extents.width);
lua_settable(L, -3);
lua_pushstring(L, "h");
lua_pushinteger(L, extents.height);
lua_settable(L, -3);
lua_pushstring(L, "yb");
lua_pushinteger(L, extents.y_bearing);
lua_settable(L, -3);
lua_pushstring(L, "xb");
lua_pushinteger(L, extents.x_bearing);
lua_settable(L, -3);
Run Code Online (Sandbox Code Playgroud)

我正在做的只是在表格中设置几个字段.字段是字符串或数字.请注意代码的重复性.

有没有办法让这个更清洁,也许使用C宏?

mar*_*gpl 5

您可以通过替换将长度减少1/3

lua_pushstring(L, "cl");
lua_pushinteger(L, info[i].cluster);
lua_settable(L, -3);
Run Code Online (Sandbox Code Playgroud)

通过

lua_pushinteger(L, info[i].cluster);
lua_setfield(L, -2, "cl");
Run Code Online (Sandbox Code Playgroud)

等等.

  • 理论上,您可以定义一个函数`set_integer_field`,它接收字段名称和字段值.但是,您还需要为其他类型定义类似的函数,如`set_string_field`,`set_boolean_field`等.我不确定这种额外的复杂性是否值得麻烦...... (2认同)