- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
string.format() function in Lua programming
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 −
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 −
d = 5; m = 11; y = 2021 date = string.format("%02d/%02d/%04d",d,m,y) print(date)
Output
05/11/2021