I need to determine if a TeX macro is already defined or not via a Lua function. Any ideas?

function IsTeXMacroDefined(macroname)
   if defined(macroname) then return true end
   return false

1 Answer 1


I don't know how robust it is but the following seems to work.



  function is_defined(s)
    local undef = 'undefined_cs'
    if token.command_name(token.create(s)) == undef then
      return false
      return true
  if is_defined('test') then tex.sprint('test is defined\noexpand\\par') else
  tex.sprint('test is not defined\noexpand\\par') end  
  if is_defined('testa') then tex.sprint('testa is defined\noexpand\\par') else
  tex.sprint('testa is not defined\noexpand\\par') end}



I added a TeX wrapper. It takes as an argument the name of the control sequence to be tested or the control sequence itself (this is done by removing the backslash at lua level with the help of lpeg). The TeX wrapper uses the expandability of \directlua to define on the fly a TeX \iftrue or \iffalse statement inside a \csname.

As pointed out in comments, one should always write lua code in a separate lua file.

First the lua file (save it as is_def.lua).

local lpeg = require('lpeg')
local P, C, Cs, V, match = lpeg.P, lpeg.C, lpeg.Cs, lpeg.V, lpeg.match

function is_cs_defined (s)
   s = match(Cs(P({(C('\\') / '' + 1) * V(1) + true})),s)
   local undef = 'undefined_cs'
   return not(token.command_name(token.create(s)) == undef)

Then the .tex file.



  \csname if\directlua{if is_cs_defined('\luatexluaescapestring{#1}')
  then tex.sprint('true') else tex.sprint('false') end}\endcsname
    is defined
    is not defined







enter image description here

  • Thanks. This will probably work good enough. You'll need to use no expand on the \\par for the example to work though.
    – Uiy
    Commented Apr 10, 2012 at 12:21
  • ... Or better put it into a Lua file :-)
    – topskip
    Commented Apr 10, 2012 at 14:03
  • Do you know whether it's possible to go further and get the actual definition this way? Commented Feb 22, 2018 at 22:52
  • ^ Answering above comment: yes, with token.get_macro and/or token.get_meaning Commented Feb 23, 2018 at 2:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .