如何在 metapost 函数中使用 Lua 的 string.len()?

如何在 metapost 函数中使用 Lua 的 string.len()?

我正在使用以下宏为我的学生练习设计伪填字游戏:

\startMPinclusions
% could'nt achieve using the word string length as a first parameter
vardef MotMystere (expr taille,speciale,index) =
   numeric avant,apres;
   path case;
   case:= fullsquare scaled 13;
   avant=speciale-1;
   apres=taille-speciale;
   if avant >= 1:
      for j=1 upto avant:
         draw (case rotated 180
            cutafter point 3 of case rotated 180)
            shifted (-13j,-13*index);
      endfor;
   fi;
   label.lft (index,point 3.5 of 
      case shifted (-13*avant,-13*index));
   draw case yshifted (-13*index);
   fill case yshifted (-13*index)
      withcolor \MPcolor{gray-8};
   if apres > 0:
      for j=1 upto apres:
         draw (case cutafter point 3 of case) 
            shifted (13j,-13*index);
      endfor;
   fi;
enddef;
\stopMPinclusions
\starttext
An example with "enigma"

\startMPcode
MotMystere(6,4,1)
\stopMPcode
\stoptext

我尝试使用 来避免一些容易出错的计数string.len()。想法是将单词作为第一个参数,而不是手动计算的字符串长度,例如MotMystere("enigma",4,1)。但是我不知道如何将这个字符串参数传递给 lua 函数。

答案1

在 ASCII 模式下,MetaPostlength就足够了。否则,您可能需要使用utflen

\startMPinclusions
vardef MotMystere(expr taille, speciale, index) =
    save avant,apres,case; 
    numeric avant,apres;
    path case;
    case  := fullsquare scaled 13;
    avant := speciale-1;
    %Use parentheses to avoid issues in LMTX
    apres := (length(taille)) - speciale;
   if avant >= 1:
        for j=1 upto avant:
            draw (case rotated 180
            cutafter point 3 of case rotated 180)
            shifted (-13j,-13*index);
      endfor;
   fi;
    label.lft (index,point 3.5 of 
    case shifted (-13*avant,-13*index));
    draw case yshifted (-13*index);
    fill case yshifted (-13*index)
        withcolor \MPcolor{gray-8};
    if apres > 0:
        for j=1 upto apres:
            draw (case cutafter point 3 of case) 
                shifted (13j,-13*index);
        endfor;
    fi;
enddef;
\stopMPinclusions
\starttext
An example with "enigma"

\startMPcode
MotMystere("enigma",4,1)
\stopMPcode
\stoptext

当你询问 Lua 处理字符串的方式时,Lua(>=5.3)提供了一个utf8库,utf8.len返回 Unicode 字符串的长度。此外,LuaTeX 和 LuaMetaTeX 提供,ConTeXt 足够智能,可以在可用时选择其中任一函数。虽然您可以从 Lua 定义自己的 Unicode 函数,然后使它们对 MetaPost 可见,但以下内容已在 ConTeXt(或)string.utflength中定义:和。请参阅以下示例:mp-luas.mpivmp-luas.mpxlutflenutfnumutfsub

\startMPpage
%If any of those doesn't work, just add parentheses until Hans fixes it
string Oracion;
Oracion := "El Perú será grande, el Perú será lo que debe ser, si todos los peruanos nos resolvemos a engrandecerlo.";
draw thetextext(utflen(Oracion),1cm*up);
draw thetextext(utfsub(Oracion,1,19),origin);
draw thetextext(utfnum("Ñ"),1cm*down); %0xD1=209
\stopMPpage

在此处输入图片描述

相关内容