Question: I have a block of code that looks like this:

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

```

What I am doing is just setting a few fields inside a table. The fields are either strings or numbers. Note how repetitive the code is.

Is there a way to make this a bit cleaner, maybe using C macros?

Answer: 
You can reduce the length by 1/3 by replacing

```
lua_pushstring(L, "cl");
lua_pushinteger(L, info[i].cluster);
lua_settable(L, -3);

```

by

```
lua_pushinteger(L, info[i].cluster);
lua_setfield(L, -2, "cl");

```

and so on.
> 
> maybe using C macros?
> 
> 
> 

More practical
==============

With C11 generic macros, it gets simpler:

```
#define lua_push(L, X) _Generic((X), const char*: lua_pushstring, \
                                     float: lua_pushnumber, \
                                     int: lua_pushinteger)(L, X)

```

Then you can wrap it up in a `lua_setfield_generic`:

```
#define lua_setfield_generic(L, NAME, X) \
    lua_push(L, X); \
    lua_setfield(L, -2, NAME);

```

And here's how your code would look:

```
lua_setfield_generic(L, "gid", info[i].codepoint);
lua_setfield_generic(L, "cl", info[i].codepoint);
lua_setfield_generic(L, "ax", pos[i].x_advance);

```

Less practical, but fancy
=========================

Since you're essentially marshaling data to Lua, it's best to make it more declarative and data based.

Imagine such a `struct` definition:

```
STRUCT(Point)
FIELD(x, float);
FIELD(y, float);
END_STRUCT

```

With some clever thinking, you can build a structure out of this and a function `PointToLuaTable` (To create a name you need `##`) that will pick appropriate types of lua functions and call them in order, taking the names from the names of fields (obtained via `#`).

You could take it even further. Craft your own preprocessor that uses e.g. Clang's API to parse your struct definitions and generate the appropriate functions, then as a 2nd build step use those files to build those functions.

That being said - *why* would you do that in C at all? It's not a language that's designed to do that. It lacks reflection and proper generics in order to make it worthwhile.