String formatting

From Sim Innovations Wiki
Jump to navigation Jump to search

Lua contains a very powerful function that takes care of most (maybe all) string formatting. It creates a formatted string from a format argument and a list of dynamic variables.

string.format(format, arg_0, arg_1, ...)

Format argument

The format argument is a string that can contain certain tags. These tags will be replaced by dynamic content.

-- Create some number
  my_number = 123

  -- The '%d' will be replaced by the value in 'my_number'
  my_txt = string.format("The number is %d", my_number)

  -- Prints "The number is 123"
  print(my_txt)

Multiple tags

You can have as many tags if you need.

-- The '%d' will be replaced by the value in 'my_number'
  my_txt = string.format("First number is %d, second is %d", 123, 999)

  -- Prints "First number is 123, second is 999"
  print(my_txt)
Info The number of tags in the format string should match the number of arguments!

Available tags

Each data type in lua has it's own tag. See the table below which tag you should use for each data type.

Argument Type Code Result
%s String string.format("Name = %s", "Jack") "Name = Jack"
%d Integer string.format("Number = %d", 123) "Number = 123"
%f Float & Double string.format("Number = %f", 12.45) "Number = 12.45"
%c Character string.format("Char = %c", 65) "Char = A" (65 corresponds to the letter 'A' in the ASCII table)
%s Boolean string.format("Value = %s", true) "Value = true"

Customizing tags

You can customize tags even further. You will see some examples below

Number of integer characters (xxx.)

my_number = 100.123

  -- Prints 'Number = 100.123'
  print(string.format("Number = %f", my_number))

  -- Prints 'Number = 00000100' (8 characters total, 0 fractional characters)
  print(string.format("Number = %08.0f", my_number))

  -- Prints 'Number = 00100.12' (8 characters total, 2 fractional characters)
  print(string.format("Number = %08.2f", my_number))

  -- Prints 'Number = 100.1230' (8 characters total, 4 fractional characters)
  print(string.format("Number = %08.4f", my_number))

Number of fractional characters (.xxx)

my_number = 100.123

  -- Prints 'Number = 100.123'
  print(string.format("Number = %f", my_number))

  -- Prints 'Number = 100' (0 fractional characters)
  print(string.format("Number = %.0f", my_number))

  -- Prints 'Number = 100.12' (2 fractional characters)
  print(string.format("Number = %.2f", my_number))

  -- Prints 'Number = 100.1230' (4 fractional characters)
  print(string.format("Number = %.4f", my_number))