The page demonstrates how to partially emulate the C printf string formatting function in Lua.

In Lua

It's easy to write formatted text in Lua using io.write(), print() and string.format(). io.write is similar to print except io.write does not follow each output with a new line. The C function printf() can be emulated as:

In the above example the format string and the variable argument list from printf() are passed to string.format(). write() prints the resulting formatted string. [*1]

It is interesting to note how the Lua 5.1 syntax for string methods forces the separate treatment of the first argument. This makes sense, because it has a quite separate role from the others.

Note that Lua's string.format function doesn't support the full C format specification [1], so this function is not a drop-in replacement. If you want the full capabilities of the C format specification, you might want to do the printf call in C code and call that from Lua. Alternately, you may using the C string functions to emulate the behavior you need entirely in Lua (more work).

In C

The above example could be coded in C as follows. This also optimizes by capturing the two standard library functions as upvalues, rather than looking them up each time (although looking them up each time has the advantage of being more dynamic). You may just want to use the Lua version though.

A C function l_printf is registered with Lua as printf. When l_printf is called from Lua, format() is called with the given arguments, then write() is called with the result of format and finally the number of results returned.

-- Sirmabus: September 13, 2009 -
An improvement to the Lua code above is to use a pcall() wrapper to catch errors and point back to the offending printf().
Otherwise it's difficult to know exactly where the error came from.