Skip to content

Instantly share code, notes, and snippets.

@Leandros
Last active December 3, 2018 12:01
Show Gist options
  • Save Leandros/31732278c1f6f442880c5593ef3812cb to your computer and use it in GitHub Desktop.
Save Leandros/31732278c1f6f442880c5593ef3812cb to your computer and use it in GitHub Desktop.
Lua C preprocessor
/*
* Copyright (c) 2018 Arvid Gerstmann.
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include <stdio.h>
/*lua!
local func = [[
T foo_T(T in) {
return in;
}
]]
return repl(func, "T", { "int", "float" })
*/
int
main(void)
{
printf("foo_int: %d\n", foo_int(2));
printf("foo_float: %f\n", foo_float(1.0f));
return 0;
}
-- Copyright (c) 2018 Arvid Gerstmann.
-- This software may be modified and distributed under the terms
-- of the MIT license. See the LICENSE file for details.
if #arg == 2 then
assert(arg[1] ~= arg[2], "arguments must not be the same")
end
local fin = assert(io.open(arg[1], "r"))
local fout = assert(#arg == 2 and io.open(arg[2], "w+") or io.stdout)
local s = fin:read("*all")
local sandbox = {
debug = print,
repl = function(code, pattern, repl)
local out = ""
for i = 1, #repl do
out = out .. "\n" .. string.gsub(code, pattern, repl[i])
end
return out
end
}
local out = string.gsub(s, "%/%*lua%!.-\n(.-)%*%/", function(code)
return assert(load(code, "sandbox", "bt", sandbox))()
end)
fout:write(out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment