[NTG-context] Checking existence of a macro (control sequence) by Lua

context at vivaldi.net context at vivaldi.net
Thu May 28 13:24:45 CEST 2020


Hello,

thanks Henri and Hans for all solutions!

On 2020-05-28 10:34, Hans Hagen wrote:
> On 5/28/2020 12:42 AM, context at vivaldi.net wrote:
>> Hello,
>> 
>> is it possible to check whether a macro exists (or - is it a 
>> non-\undefined control sequence) with Lua? Suppose:
>> 
>> ----
>> \starttext
>>    \def\MyMacro{Ahoj}
>>    \def\MyMac#1#2{Something}
>> 
>>    \startluacode
>>      IsDefined = function(ctl_seq)
>>        print("CS " .. ctl_seq ..
>>                                  (tex.IsCS(ctl_seq) -- Or what to come 
>> here?
>>                                                     "is defined" or 
>> "is unknown") .. ".")
>>      end
>> 
>>      -- So the function should print to the console:
>> 
>>      IsDefined("MyMacro") --> "CS MyMacro is defined."
>>      IsDefined("MyMac") --> "CS MyMac is defined."
>>      IsDefined("bf") --> "CS bf is defined."
>>      IsDefined("dummy") --> "CS dummy is unknown."
>> 
>>    \stopluacode
>> \stoptext
>> ----
>> 
>> Is it possible?
> A lot is possible. Take this:
> 
>            \def\MyMacroA{Ahoj A}
> \unexpanded\def\MyMacroB{Ahoj B}
> \frozen    \def\MyMacroC{Ahoj C} % in lmtx
>          % \def\MyMacroC{Ahoj C} % barks
> 
> At the tex end you can check for several properties:
> 
> \ifusercmd \hbox     Y\else N\fi % in lmtx
> \iffrozen  \hbox     Y\else N\fi % in lmtx
> \ifusercmd \MyMacroA Y\else N\fi % in lmtx
> \iffrozen  \MyMacroA Y\else N\fi % in lmtx
> \iffrozen  \MyMacroC Y\else N\fi % in lmtx
> 
> At the Lua end you can check for being defined:
> 
> \startluacode
>     local function whatever(s)
>         context.type("\\" .. s)
>         context(" is %s", tokens.defined(s) and "defined" or 
> "undefined")
>         context.par()
>     end
>     whatever("MyMacroA")
>     whatever("MyMacroD")
>     whatever(" ")
>     whatever("-")
> \stopluacode
> 
> alternatively you can say:
> 
> \startluacode
>    local t = token.create("MyMacro")
>    print(t.cmdname == "undefined_cs")
> \stopluacode
> 
> which is less efficient unless you want to access more properties.
> 
> Hans

(@Hans: I'm using vivaldi's mail account in "good will" - I didn't 
suppose it would cause any unwanted actions, like resending mails or 
whatever.)

Bets regards,

Lukas


More information about the ntg-context mailing list