Lua Methods on Literal Strings

I’ve been using Lua on my game for the past six-hundred thirty-five days (since the first commit) and just today came across a useful trick.

Previously I have wanted to use string.format as a method like so:

local foo = "Lobby"
local bar = 36

print("%s: %d":format(foo, bar))

This fails with a syntax error on the final line. However, it does work if you wrap the string in parentheses, like so:

local foo = "Lobby"
local bar = 36

print(("%s: %d"):format(foo, bar))

Simple, but useful in my opinion. This also works with literal table expressions, e.g. ({ … }):foo() although I personally have had no reason to use that so far.

Advertisements

Add Your Thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s