Page 1 of 1

Using String Interpolation

Posted: Thu Jul 27, 2017 11:14 am
by Belgarath
In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

I was looking over the lua-users website a while back and came across this useful script that I've been using for some time. I felt it might be useful to share here so other people can find it useful too.

Both Ruby and Python have a short form for string formatting, using the % operator.

The following snippet adds a similar use of the mod operator to lua:
Code: [show] | [select all] lua
getmetatable("").__mod = function(a, b)
  if not b then
    return a
  elseif type(b) == "table" then
    return string.format(a, unpack(b))
    return string.format(a, b)
All you need to do is stick it in the scripts section somewhere.

Example usage:
Code: [show] | [select all] lua
print( "%5.2f" % math.pi )

print( "%-10.10s %04d" % { "test", 123 } )
In my personal opinion, it looks a bit nicer than having to regularly use string.format. I've also found it more convenient.

Re: Using String Interpolation

Posted: Fri Jul 28, 2017 8:06 am
by Vadi
How do you use it with Lua's patterns, which also make use of %?

Re: Using String Interpolation

Posted: Fri Jul 28, 2017 9:17 am
by keneanung
I think you misunderstand, Vadi. This defines the "mod" operator on strings, but doesn't touch the string content at all.