OpenSCAD User Manual/General

出典: フリー教科書『ウィキブックス(Wikibooks)』


コメント[編集]

OpenSCAD では C++形式のコメントを用いる:

// これはコメント

myvar = 10; // ここからもコメント

/*
複数行のコメント    
*/

変数[編集]

変数は以下のように簡単に作ることができる。

例:

myvar = 5 + 4;

文字列[編集]

ダブルクォートとバックスラッシュはエスケープする必要がある (順に\" と \\ )。その他のエスケープ文字は、改行 (\n)、タブ (\t) とCR (\r) である。

NB! この仕様は OpenSCAD-2011.04 からである。古いソースはsed コマンド『sed 's/\\/\\\\/' non-escaped.scad > escaped.scad』で変換できる。

例:

 echo("The quick brown fox \tjumps \"over\" the lazy dog.\rThe quick brown fox.\nThe \\lazy\\ dog.");

Output:
ECHO: "The quick brown fox jumps "over" the lazy dog.
The quick brown fox.
The \lazy\ dog."

変数は実行時ではなくコンパイル時に格納される[編集]

注意: OpenSCAD は変数の値の計算を実行時ではなくコンパイル時に行なうので、 一番最後に代入された値がプログラム中のあらゆる参照で有効となる。 変数というより、再定義可能な定数と考えたほうがよいかもしれない。

例:

 // 変数 'a' への最後の格納のみが反映される
    a = 0;
    echo(a);

    a = 5;
    echo(a);

出力

ECHO: 5
ECHO: 5

このことから、変数は "if" ブロックの中では代入できない:

Example:

a=0;
if (0==a) 
  {
  a=1; // <- この行でエラーになる
  }

出力 Compile Error

この振る舞いのスコープは、root (一番上のレベル) または module の呼び出しごとに限られる。 このことから、変数はスコープの外部に影響されることなくモジュール内で再定義できる。 しかしスコープ内でのすべてのインスタンスは、上述のように最後に定義された値になる。

例:

p = 4;
test(5);
echo(p);

p = 6;
test(8);
echo(p);

module test(q)
{
    p = 2 + q;
    echo(p);

    p = 4 + q;
    echo(p);
}

Output

ECHO: 9
ECHO: 9
ECHO: 6
ECHO: 12
ECHO: 12
ECHO: 6

これは直感に反するようであるが、面白い使い方ができる。 つまり、デフォルト値を持つようなシェアードライブラリを作成した場合、そのファイルをインクルードしたファイルでは、 単純にデフォルト値を『再定義』つまり上書きするだけで新しい値で使うことができる。

変数の値のスコープをより厳密に定義するには、assign ステートメントを参照。

Getting input[編集]

Now we have variables, it would be nice to be able to get input into them instead of setting the values from code. There are a few functions to read data from DXF files, or you can set a variable with the -D switch on the command line.

Getting a point from a drawing

Getting a point is useful for reading an origin point in a 2D view in a technical drawing. The function dxf_cross will read the intersection of two lines on a layer you specify and return the intersection point. This means that the point must be given with two lines in the DXF file, and not a point entity.

OriginPoint = dxf_cross(file="drawing.dxf", layer="SCAD.Origin", 
                        origin=[0, 0], scale=1);

Getting a dimension value

You can read dimensions from a technical drawing. This can be useful to read a rotation angle, an extrusion height, or spacing between parts. In the drawing, create a dimension that does not show the dimension value, but an identifier. To read the value, you specify this identifier from your script:

TotalWidth = dxf_dim(file="drawing.dxf", name="TotalWidth",
                        layer="SCAD.Origin", origin=[0, 0], scale=1);

For a nice example of both functions, see Example009 and the image on the homepage of OpenSCAD.