lua string printing

In C, I have format strings, something like:

char *msg = "wlll you marry me"
fprintf(stderr, "%s, %s?", name, msg);

Now, can I do something similar in lua with format strings? I.e. I want something functionally equivalent to:

name .. ", " .. msg .. "?"

but not so ugly, in lua.

Okay, so I can do string.format("%s, %s?", name, msg), but can I go even a step further, something like perl style, where I can go:

"%name, %msg?"



According to the Lua Users Wiki article on String Interpolation, Lua does not offer a built-in native way to do this; however, there are a couple sort-of workarounds posted on that page.

Here's one simple implementation (-- RiciLake):

function interp(s, tab)
  return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end))
print( interp("${name} is ${value}", {name = "foo", value = "bar"}) )

getmetatable("").__mod = interp
print( "${name} is ${value}" % {name = "foo", value = "bar"} )
-- Outputs "foo is bar"

Can I do something similar [to printf] with Lua format strings?

Yes. I do this all the time:

local function printf(...) return io.stdout:write(string.format(...)) end

local function fprintf(f, ...) return f:write(string.format(...)) end

Modify to taste.

Need Your Help

What's an easy way to manage source files that are shared among different Xcode projects?

iphone xcode ipad ios

I'm diving into iOS development and I plan to build a few basic apps that make use of my own reusable code. As I update the files that contain my reusable code, I'd like those updates to be reflec...

Implementing session in SOAP Client

c# windows-phone-7 soap

I am developing a WP application for which the webservices are implemented in .NET using SOAP client. I have implemented the SOAP client in my WP app using "Add service reference" option.