Main Content

String formatting in Lua - string.format as a wrapper for sprintf

Archive - Originally posted on "The Horse's Mouth" - 2014-05-07 12:49:25 - Graham Ellis

Lua is a small language - and so for some elements of its functionallity it uses wrappers around underlying C functions rather than re-implementing and duplicating logic. A good example is the string.format function which in essence is a wrapper around sprintf.

For example:
  thing = string.format("> %8.2f > %d",person[1],person[2])
  print (thing)


• using the string template which is the first paramater of the function call, substitute a floating point number 8 characters wide, of which two characters are afer the decimal point, into the first place holder and a decimal (base 10) integer as many characters wide as it needs to be into the second placeholder, and store the resulting string into a variable called thing

• then output the contents of the variable called thing, adding a new line onto the end.

This may feel a bit clunky and old fashioned but it works very well. And the Lua wrapper saves you all the extra work of declaring and allocating memory for the variable called thing, adding the new line, ensuring you have space for a null terminator too. And it save you the heartache of scratching your head while you debug if you have forgotten to allocate the memory of leave space for the terminator.

Another very simple and logical solution from Lua ... we teach Lua [descriptions] ... and there's an example from a past course with some more formatting examples [here]. Further string format examples [here].