I'm writing a Lua Module for LuaLaTeX.
Does a LuaTeX C API exist?
For example, how can I use the C version of tex.print into my C code?
Thanks in advance
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It only takes a minute to sign up.
Sign up to join this communityI am by far a person that can give you an authoritative answer. As I have written in a comment to David, there is no way to use TeX as a (shared) library. But you can use LuaTeX to load modules and execute LuaTeX's functions.
Say you want to call texio.write_nl("Hello world!")
. You have to write a small C program to do that:
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <stdlib.h>
#include <stdio.h>
static int callprint (lua_State *L)
{
lua_getglobal(L, "texio");
lua_getfield(L, -1, "write_nl");
lua_remove(L, -2);
lua_pushstring(L, "Hello, world!");
lua_call(L, 1, 0);
return 0;
}
int luaopen_printfromc(lua_State *L) {
struct luaL_Reg myfuncs[] = {
{"callprint", callprint},
{NULL, NULL},
};
lua_newtable (L);
luaL_setfuncs (L, myfuncs, 0);
return 1;
}
Then you can compile this as a shared library, on my Mac it is:
cc -c printfromc.c -I /opt/homebrew/Cellar/lua/5.2.4_1/include/
cc -flat_namespace -bundle -undefined suppress -o printfromc.so printfromc.o
(on Debian GNU/Linux and derivatives, the following should work for TeX Live 2021:
gcc -o printfromc.so -shared -fpic printfromc.c -I/usr/include/lua5.3/ -llua5.3
)
and copy the result to a TeX directory
cp printfromc.so /some/path/to/TeX/luatex/test
where you can load this library from the TeX source:
\documentclass{article}
\usepackage{luacode}
\begin{document}
\begin{luacode*}
x = require("printfromc")
x.callprint()
\end{luacode*}
\end{document}
In theory you can (although making work across all the platforms supported by texlive is tricky) look at the FFI module up to TeXlive 2016 that requires luajittex rather than luatex but in texlive 2017 prerelease there is some support to work with luatex.
Alternatively there is the swig library for an alternative linking mechanism.
links for ffi and swig
http://www.luatex.org/svn/trunk/source/libs/luajit/LuaJIT-src/doc/ext_ffi_semantics.html
tex.print
in your C code, because the corresponding C function is marked asstatic
and is therefore only accessible from within the same translation unit.