Not directly supported, but easy to do with Lua's string.gsub
.
res = ("$VAR is expanded"):gsub('%$(%w+)',SUBST)
$
is 'magic', so it needs to be escaped, and the 'digits or letters' pattern %w+
is captured and passed on to SUBST
as 'VAR'. (A more correct pattern for a general identifier is '[_%a][_%w]*').
Here SUBST
can either be a string, a function or a table of key-value pairs. So using os.getenv
would allow us to expand environment variables and using something like {VAR = 'dolly'}
would replace the symbol with the associated value in the table.
Cosmo packages and extends this pattern safely with sub-templates:
require "cosmo"
template = [==[
<h1>$list_name</h1>
<ul>
$do_items[[<li>$item</li>]]
</ul>
]==]
print(cosmo.fill(template, {
list_name = "My List",
do_items = function()
for i=1,5 do
cosmo.yield { item = i }
end
end
}
))
==>
<h1>My List</h1>
<ul>
<li>1</li><li>2</li><li>3</li><li>4</li><li>5</li>
</ul>
Python-like string formatting can be done in Lua:
print( "%5.2f" % math.pi )
print( "%-10.10s %04d" % { "test", 123 } )
The implementation is short and cool:
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
Lua strings share a metatable, so this code overrides the %
(modulo) operator for all strings.
For this and other options see the String Interpolation page on the Wiki.
LuaShell is a very cool demonstration of how string interpolation and automatic function generation can give you a better shell scripting language:
require 'luashell'
luashell.setfenv()
-- echo is a built-in function
-- note that environment and local variables can be accessed via $
echo 'local variable foo is $foo'
echo 'PATH is $PATH'
cd '$HOME' -- cd is also a built-in function
-- the ls function is dynamically created when called
-- the ls function will fork and exec /bin/ls ls ()
ls '-la --sort=size'