【问题标题】:DelphiScript, why does Pos() function returns several values?DelphiScript,为什么 Pos() 函数返回多个值?
【发布时间】:2021-08-26 14:01:22
【问题描述】:

我目前正在处理一个大型脚本(对我而言),我需要在其中删除文件夹中的一些文件。为了确定我需要删除哪些文件,我正在阅读一个包含我需要的所有信息的文本文件。我正在使用 TStringList 类和函数 Pos() 来获取这些信息。

我的问题来自函数 Pos(),它返回多个值,StringList(文本文件)的每个字符串一个值。

所以这是我脚本的专用部分:

Procedure Delete;
Var
SL      : TStringList;
i, A, B : Integer;     //i is a Counter, A and B are not mandatory but are useful for DEBUG
PCBFile : String;
Begin
PCBFile := //Full Path
SL := TStringList.Create;
SL.LoadFromFile(PCBFile);
For i := 1 To (SL.Count - 1) Do         //I don't need to check the 1st line of the text file.
     A := Pos('gtl', SL.Strings[i]);    //Here is when the problem occurs.
     B := Pos('gbl', SL.Strings[i]);    //Doesn't get to here because i = SL.Count before looping
     If (A = 0) And (B = 0) Then        //The goal
          ChangeFileExt(PCBFile, '.TX');
          PCBFile := PCBFile + FloatToStr(i-2);     //The files I want to delete can have several extensions (tx1, tx2... txN)
          DeleteFile(PCBFile);
     End;
End;
SL.Free;
End;

如果我改变这一行:

A := Pos('gtl', SL.Strings[i]);

对此:

ShowInfo (Pos('gtl', SL.Strings[i]));  //Basic function from Altium Designer, same as Writeln()

它将显示一个弹出窗口,其中包含文本文件每一行的函数 Pos() 的结果。我假设 SL.Strings[i] 对 i 进行内部自动增量,但我想用我的 For Do 循环来管理它。

我这两天在网上搜索,但没有找到任何线索,可能是Altium Designer的问题,它一开始并不是真正的编程软件。

我也尝试过使用 SL.IndexOf() 函数,但它只适用于严格的字符串,这不是我的情况。

感谢您的时间和帮助。

最好的问候, 约旦

【问题讨论】:

  • 您确实意识到if ... then 之后的所有三行都需要被begin ... end 块包围,否则无论if 条件是否为真,都会执行第二行和第三行?
  • 请参阅我对Proper structure syntax for Delphi/Pascal if then begin end and ; 的回答,了解如何正确使用它们,您在这里没有。答案是为 Pascal 编写的,但同样适用于 PascalScript 和 Delphi。

标签: pascal tstringlist altium-designer


【解决方案1】:

代码中有一些错误,即不完整的Begin .. End;块。

第一个是for i .. 循环。如果要在循环的每次迭代中执行多个语句,则必须将它们括在 Begin .. End; 对中。您的代码缺少Begin,因此它在到达分配B 的行之前分配了A SL.Count-1 次。 第二个是在If .. 语句之后。如果您想有条件地执行多个语句,您必须在 If .. 语句之后将它们括在 Begin .. End; 对中。

添加如下标记的两行

For i := 1 To (SL.Count - 1) Do         //I don't need to check the 1st line of the text file.
Begin  // Add this line
    A := Pos('gtl', SL.Strings[i]);    //Here is when the problem occurs.
    B := Pos('gbl', SL.Strings[i]);    //Doesn't get to here because i = SL.Count before looping
    If (A = 0) And (B = 0) Then        //The goal
    Begin  // Add this line
        ChangeFileExt(PCBFile, '.TX');
        PCBFile := PCBFile + FloatToStr(i-2);     //The files I want to delete can have several extensions (tx1, tx2... txN)
        DeleteFile(PCBFile);
    End;
End;

还要记住,在 Pascal 中,缩进对代码的执行方式没有影响(就像在其他一些语言中一样)。缩进对于可读性很重要,但仅此而已。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2019-01-08
    • 2014-06-06
    相关资源
    最近更新 更多