OpenSCAD 使用者手冊/WIP/模組字面量
外觀
< OpenSCAD 使用者手冊 | WIP
模組引用使用模組字面量進行初始化。在以下程式碼片段中,my_cube 是模組引用,而 module cube([2,3,4]) 是模組字面量。模組字面量是一個表示式,其語法特徵是它以 module 關鍵字為字首。
根據你的需要,定義模組引用有幾種不同的方法。
在此語法中,你定義的模組與你期望看到其輸出完全相同。
// Create a reference to a cube module
my_cube = module cube([2,3,4]);
|
以上程式碼建立了變數 my_cube,但不會例項化它,因此在圖形視窗中不會有任何輸出。若要例項化模組,你使用與模組相同的語法。
// Instantiate the module through the module reference
my_cube();
|
在此變體中,模組引用的名稱只是模組的另一個名稱。
my_cylinder = module cylinder;
|
要例項化模組,別名接受與它所引用的模組完全相同的引數。
my_cylinder(h=20, r=10, center=true);
|
在另一種形式中,你向模組字面量提供引數。這些引數被轉發到原始模組。
my_cylinder = module(height) cylinder(h = height, r=10, center=true);
|
在這種情況下,你使用修改後的引數呼叫引用。
my_cylinder(20);
|
在最後的幾種形式中,你可以建立一個匿名模組字面量,並將引用初始化到它。
( 請注意,在此形式中,在右花括號後面必須有一個分號 )
my_shapes = module {
cube(2,center = true);
translate([5,0,0])
sphere(1,center = true);
};
|
模組可以使用通常的方式例項化。
my_shapes();
|
匿名模組形式當然也可以接受引數。
my_rotated_square = module ( r, s) { rotate(r) square(s);};
|
模組引用可以使用通常的方式例項化。
my_rotated_square(45,10);
|
模組字面量可以儲存在陣列中,並從函式中返回。在這些情況下,在呼叫它們之前將它們分配給符號可能會很不方便。可以透過在例項化引數之前用括號括起解析為模組字面量的表示式來例項化表示式。
//-------------
// n is an integer index between 0 and 3
// choose_shape returns the shape given by the index
function choose_shape(n) =
let (ar = [
module cube([5,20,30]),
module sphere(r = 6 , $fn = 20),
module cylinder(d = 15, h = 20, $fn = 30)
])
ar[n];
//--------------
// instantiate the chosen module
(choose_shape(2))(); // choose the cylinder
|
有關模組字面量和模組引用的更高階用法,請參見 https://github.com/kwikius/openscad/tree/module_literal_v3/examples/ModuleLiterals

