The idea that you run code, the result of which is then spliced in is called quasiquotation. The code you run is antiquoted.
I know how to solve this problem using Lua. I've used string.gsub
with an antiquotation function I wrote myself. I've used shell syntax for the antiquotation. As in the shell the antiquoted code returns a string which is then spliced into the code.
Below prog
is the C code with antiquoted text, and antiquote
is the antiquotation function. I've used Lua's special string quoting double square brackets to full advantage. In practice you wouldn't do this; you'd put prog
in a separate file.
names = { 'John', 'Paul', 'George', 'Ringo' }
local prog = [===[
#include <stdio.h>
main() {
$(local out = { }
for _, n in ipairs(names) do
table.insert(out, string.format([[ printf("The name is %%s\n", %q);]], n))
end
return table.concat(out, '\n ')
)
}
]===]
local function antiquote(s)
local body = s:match '^%$%((.*)%)$'
return assert(loadstring(body))()
end
prog = prog:gsub('%$%b()', antiquote)
io.stdout:write(prog)
In use, the program looks like this:
: nr@curlycoat 1181 ; lua /home/nr/tmp/emit-c.lua
#include <stdio.h>
main() {
printf("The name is %s\n", "John");
printf("The name is %s\n", "Paul");
printf("The name is %s\n", "George");
printf("The name is %s\n", "Ringo");
}