Button Button Button

Previous Next

This function replaces all $ names in a string with the value found in a table, or a function. string.gsub simply requires a suitable pattern for matching these names; note that $ must be escaped.

See StringInterpolation

Author: steved

License: MIT/X11 Tags: string utility template

Snippet

function string_interpolate(tmpl,t)
    return (tmpl:gsub('%$([%a_][%w_]*)',t))
end

Tests/Usage

local function test(tmpl,t)
    print(string_interpolate(tmpl,t))
end

test('$animal ($name)',{animal='dog',name='bonzo'})
test('what is $USER?',os.getenv)

--> dog (bonzo)
--> what is steve?

Related Snippets


Revision 000002 by steved; created Tue, 11 Jan 2011 15:48:01 +0000

0 comments

Add a Comment