Using String Interpolation

Post Reply
User avatar
Belgarath
Posts: 232
Joined: Fri Jul 26, 2013 7:19 am
Discord: macjabeth#7149

Using String Interpolation

Post 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))
  else
    return string.format(a, b)
  end
end
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.

User avatar
Vadi
Posts: 5035
Joined: Sat Mar 14, 2009 3:13 pm

Re: Using String Interpolation

Post by Vadi »

How do you use it with Lua's patterns, which also make use of %?

User avatar
keneanung
Site Admin
Posts: 94
Joined: Mon Mar 21, 2011 9:36 am
Discord: keneanung#2803

Re: Using String Interpolation

Post by keneanung »

I think you misunderstand, Vadi. This defines the "mod" operator on strings, but doesn't touch the string content at all.

Post Reply