I've been musing on ways to do object-oriented kinds of stuff in OpenSCAD and
came up with the approach below, but it's pretty clunky. Is there a more
elegant method that someone can suggest?
To be clear, I'm asking about OpenSCAD syntax kind of stuff, and not about
to implement a particular kind of data structure.
--
Sent from: http://forum.openscad.org/
The simple way is using a group functions that share the same data, such as
the way I does with my hashmap
https://openhome.cc/eGossip/OpenSCAD/lib3x-hashmap.html .
Simulating class-based oo, however, is riveting and here is my attempt to do
it.
// require dotSCAD 3.0 https://github.com/JustinSDK/dotSCAD
use <util/map/hashmap.scad>;
use <util/map/hashmap_get.scad>;
function methods(mths) = hashmap(mths);
function clz_list(data) =
methods([
["get", function(i) data[i]],
["append", function(n) clz_list(concat(data, [n]))]
]);
function _(instance, name) = hashmap_get(instance, name);
lt1 = clz_list([10, 20]);
assert((lt1, "get")(0) == 10);
assert((lt1, "get")(1) == 20);
lt2 = (lt1, "append")(30);
assert((lt2, "get")(0) == 10);
assert((lt2, "get")(1) == 20);
assert((lt2, "get")(2) == 30);
Sent from: http://forum.openscad.org/
You can encapsulate the instance even further. But the code is more complex
when defining a class.
use <util/map/hashmap.scad>;
use <util/map/hashmap_get.scad>;
function methods(mths) = hashmap(mths);
function _(name, instance) = hashmap_get(instance, name);
function clz_list(data) = function(name) _(name,
methods([
["get", function(i) data[i]],
["append", function(n) clz_list(concat(data, [n]))]
])
);
lt1 = clz_list([10, 20]);
assert(lt1("get")(0) == 10);
assert(lt2("get")(1) == 20);
lt2 = lt1("append")(30);
assert(lt2("get")(0) == 10);
assert(lt2("get")(1) == 20);
assert(lt2("get")(2) == 30);
Sent from: http://forum.openscad.org/
caterpillar wrote
...
lt1 = clz_list([10, 20]);
assert(lt1("get")(0) == 10);
assert(lt1("get")(1) == 20);
lt2 = lt1("append")(30);
assert(lt2("get")(0) == 10);
assert(lt2("get")(1) == 20);
assert(lt2("get")(2) == 30);
....
Thanks for the answers. That syntax still seems a little clunky, but I
guess that's going to happen when pushing the language to do things it's not
designed to.
--
Sent from: http://forum.openscad.org/