Is there a reason why the code below leads to the error:

! Illegal unit of measure (pt inserted).
<to be read again> 
l.16 ...t [domain=-.1:.1,samples = 100] (\x,{G(\x)})

function G (x) 
    return (-(x^2)/3)
\edef\pgfmathresult{\directlua{tex.print("" .. G(#1))}}%  
\draw [blue]  plot [domain=-.1:.1,samples = 100] (\x,{G(\x)});

If you modify the function to

\edef\pgfmathresult{\directlua{tex.print("" .. G(#1))}}%  

then the plot plots the (wrong:-) function without error but you get to see what you were plotting. The first few values are OK but then:

> \pgfmathresult=macro:

Presumably pgf isn't expecting the e notation. Presumably lua has some number formatting functions to prevent it using that notation?

edit ah yes:

\edef\pgfmathresult{\directlua{tex.print(string.format("\@percentchar f",G(#1)))}}%  
  • 2
    Although colossally inefficient the G function definition could be \pgfmathparse{\directlua{tex.print("" .. G(#1))}}% as the math parser can convert the e notation into something pgf can use. – Mark Wibrow Jan 24 '15 at 10:25

I would suggest to use Lua for all the calculations and also to create the relevant LaTeX code. Of course as Dave suggested use string.format('% .2f','number') to format the number. Two decimal places would be more than adequate for plotting.

local function G (x) 
    return string.format('% .2f',-(x^2)/3)

tex.print('\\draw[color=red] (0,0)')

local z=-.1
for i=1,50 do
   tex.sprint('-- (' .. i .. ',' .. G(z)..')  ') 


This normally produces cleaner code, is easier to debug and faster. Add formatting code for axes and co-ordinates to suit your requirements. For example using the above it is trivial to also export the values as a table and also do any transformations you may want.

  • maybe it is wrong, but I prefer to separate lua and tex codes? – pluton Jan 24 '15 at 16:13
  • 1
    @pluton Getting pgf to parse numbers with four decimal places will slow you down for more complicated stuff, but use what you are comfortable with. There is no right or wrong way, just programming patterns and individual preferences. – Yiannis Lazarides Jan 24 '15 at 16:46

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.