|
Since |
Ferreira's Home Page |
|
Lua Bit #1: Simple Templates |
The following piece of code reads a template file and a table and merges them producing an output where placholders were replaced by the appropriate table elements.
local f, e = io.open(filename) local t = dofile(conf) local line for line in f:lines() do line = string.gsub(line, '$%(([%w_]+)%)', function(a) return t[a] end) io.stdout:write(line, "\n") end
The template file is named in filename and may look like this:
a= $(A) b= $(B) c= 33 + $(C)
The table is read from a file named in conf, illustrated below:
return {
A = 'aaaaa',
B = 'bbbbb',
C = 'ccccc'
}
The output is sent to io.stdout, Lua standard output, and
for the examples above would look like this:
a= 'aaaaa' b= 'bbbbb' c= 33 + 'ccccc'