string.format() function in Lua programming

LuaServer Side ProgrammingProgramming

There are cases when we want to format strings which will help us to print the output in a particular format.

When we use the string.format() function it returns a formatted version of its variable number of arguments following the description given by its first argument, the so-called format string.

The format string that we get the output, is similar to those of the printf function of standard C: It is composed of regular text and directives, which control where and how each argument must be placed in the formatted string.

Syntax

string.format(“s = %a”)

The string.format() syntax above contains an identifier s which is the string and the identifier a is the letter that tells how to format the argument.

There are many letters to tell how to format the argument, these are −

  • ‘d’ - a decimal number
  • ‘x’ - for hexadecimal
  • ‘o’ - for octal
  • ‘f’ - for a floating-point number
  • ‘s’ - strings
  • and there are many other variants.

Now let’s consider some examples where we will run the string.format() function.

Example

Consider the following example −

 Live Demo

s = string.format("x = %.4f",2345)
print(s)

Output

x = 2345.0000

Example

Now let’s consider one more example where we will print the string in a format that looks exactly similar to a date. Consider an example shown below −

 Live Demo

d = 5; m = 11; y = 2021
date = string.format("%02d/%02d/%04d",d,m,y)
print(date)

Output

05/11/2021
raja
Published on 19-Jul-2021 12:15:34
Advertisements