4

I want to load a lot of numbers in my document from a single JSON file that is returned from a simulation. To do that I so far followed this stackexchange answer but for multiple values I would have to load the JSON file several times throughout the documents (I am new to LuaLatex so maybe I am missing something essential). What I want is something like this:

\documentclass{article}
\usepackage{luacode}

\begin{document}

\begin{luacode}
function read(file)
    local handler = io.open(file, "rb")
    local content = handler:read("*all")
    handler:close()
    return content
end
JSON = (loadfile "JSON.lua")()
local table = JSON:decode(read("recipes.json"))
\end{luacode}

The fat content of the recipe \directlua{tex.print(table['recipe']
['title'])} is \directlua{tex.print(table['recipe']
['fat'])}.

\end{document}

What is the cleanest way to achieve that?

  • 2
    Have you read the warning in the linked answer and tried the other one (from Yiannis)? – TeXnician Oct 13 '17 at 9:05
2

I found the answer: in the example above the relevant variable (table) is defined as local. That's why it is not accessible in subsequent lua calls. The solution is thus

\documentclass{article}
\usepackage{luacode}

\begin{document}

% load json file
\begin{luacode}
function read(file)
    local handler = io.open(file, "rb")
    local content = handler:read("*all")
    handler:close()
    return content
end
JSON = (loadfile "JSON.lua")()
table = JSON:decode(read("recipes.json"))
\end{luacode}

The fat content of the recipe \directlua{tex.print(table['recipe']
['title'])} is \directlua{tex.print(table['recipe']
['fat'])}.

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.