STM publishing: tools, technologies and change A WordPress site for STM Publishing

27Apr/14Off

Neat trick with LuaTeX: Passing Lua tables from TeX to Lua

It has been a long time since I wrote a blog post so I thought I'd share a rather nice "trick" I discovered today. You can pass a Lua table from a TeX macro to Lua. Here's how.

% We start by creating a simple macro that takes one argument, but when we expand
% the macro we enclose its argument in braces {...}, which is then coerced, by Lua, 
% into a table constructor! 

\def\tabtest#1{
\directlua{
% This simple function is just for demo purposes
function join(a,b)
print("I was called with ("..a..","..b..")")
end

%Here's the neat bit, our TeX macro argument, enclosed in braces {...}, becomes a Lua table!
str=#1 % Yay, str becomes a Lua table!
% Here we call the join function with values in the table 
str[1][1](str[1].x,str[1].y)
}}

% Here's our macro call --- \tabtest{{<--this becomes a table-->}}
% We include a pointer to the function "join", together with the values to call it with
\tabtest{%
{% start of Lua table to send
{[1]=join, x=1, y=2}
}% end table to send
}% end \tabdef call

The result of running the above calls join(1,2) and is printed to the terminal: I was called with (1,2). Rather nice, I thought!

Filed under: Examples, LuaTeX Comments Off
Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.