Re: OT: why do people use python when it is slow?
On Tuesday, 13 October 2015 at 23:26:14 UTC, Laeeth Isharc wrote: https://www.quora.com/Why-is-Python-so-popular-despite-being-so-slow Andrei suggested posting more widely. Maybe also interesting: https://docs.google.com/presentation/d/1LO_WI3N-3p2Wp9PDWyv5B6EGFZ8XTOTNJ7Hd40WOUHo/mobilepresent?pli=1&slide=id.g70b0035b2_1_168
Re: OT: why do people use python when it is slow?
On Sunday, 18 October 2015 at 13:29:50 UTC, Ola Fosheim Grøstad wrote: On Sunday, 18 October 2015 at 12:50:43 UTC, Namespace wrote: On Tuesday, 13 October 2015 at 23:26:14 UTC, Laeeth Isharc wrote: https://www.quora.com/Why-is-Python-so-popular-despite-being-so-slow Andrei suggested posting more widely. Maybe also interesting: https://docs.google.com/presentation/d/1LO_WI3N-3p2Wp9PDWyv5B6EGFZ8XTOTNJ7Hd40WOUHo/mobilepresent?pli=1&slide=id.g70b0035b2_1_168 What I got out of that is that someone at Mozilla were writing a push service (stateful connections, which more demanding than regular http) and found that jitted Python was more suitable than Go for productivity reasons. Then they speculate that their own Rust will be better suited than Go for such services in the future, apparently not yet. I liked the fact that Python with PyPy is more performant than Go (in contrast to the title "Python is slow") and that Go-Routines leak. To the poster further up in the thread: turns out that reddit.com is implemented in Python and a little bit of C: https://github.com/reddit/reddit So there we have it. Python gives higher productive at the cost of efficiency, but does not have a significant impact on effectiveness, for regular web services that are built to scale.
Re: [Dtiled] Unfamiliar terms and trouble using it for Dgame
On Friday, 27 November 2015 at 13:00:16 UTC, Jack wrote: Greetings! I've been using Dgame for quite a while now and I have been learning quite a lot from using playing with it. Then I found Tiled that's a tool to draw tilemaps, and DTiled to implement it. Link [ http://code.dlang.org/packages/dtiled] I've spent about an hour in order to make it work in Dgame, basing my code in the examples, and I have a bit of trouble in using it, since I am just a newbie. I've learned about templates, and all the other doodads, but I have trouble translating the tutorial code in loading the map to work with Dgame. Can someone help me understand the code? I can't wrap my head around it. What exactly causes you problems?
Re: [Dtiled] Unfamiliar terms and trouble using it for Dgame
Well to start, I just copied the code for loading the map and tried to build it, substituting the variables like Rect and others. Then it went crazy all of a sudden: http://dpaste.com/2D59A2B The whole thing went mad, and I was sure I had my imports correct: import dtiled.data; import dtiled.map; import dtiled.grid; import dtiled.algorithm; import dtiled.coords; import Dgame.Math.Rect; import Dgame.Math.Vector2; import Dgame.Math.Geometry; import Dgame.Math.Vertex; And that's where I was left dumbfounded. I use the latest D compiler, and the latest dub. Dmd v.2.069.1 and dub v.0.9.24 That sounds like a DTiled issue. Create your issue here: https://github.com/rcorre/dtiled There you will get immediate response. :)
Re: How to make a transparent wrapper type?
This seems to work: struct RefVal(T) { private T* ptr; this(T* val) { ptr = val; } ref auto opAssign(U)(auto ref U value) { *ptr = value; return *ptr; } auto get() inout { return ptr; } }
Re: [Dgame] Is there Multiple Window support?
On Sunday, 13 December 2015 at 06:33:55 UTC, Jack wrote: Hello, so I've been experimenting with the framework and I tried to implement a game that has more than two windows. The first window is the main game and the second window is a smaller one with the various commands you can select. So I tried to render sprites onto the first window and the second window, and failed. -- window_1.clear(); window_2.clear(); window_1.draw(sprite_1); window_2.draw(sprite_2); window_1.display(); window_2.display(); --- So far, when two windows are called to clear, draw and display, it didn't render anything. There was no error message, but once I commented out the window_2 calls, it rendered the first window without flaw. So are multiple windows supported here? Should work. Please report an issue on github (https://github.com/Dgame/Dgame) with your description and the reduced example.
Re: Const vs Non const method
Try inout: import std.stdio; struct Inner { int field = 3; } struct Test { auto get() inout { return inner; } private Inner inner; } void main() { { Test test; test.get.field = 4; } { immutable Test test; writeln(test.get.field); } }
Re: Const vs Non const method
On Thursday, 25 February 2016 at 10:59:43 UTC, Rene Zwanenburg wrote: On Thursday, 25 February 2016 at 10:44:49 UTC, Andrea Fontana wrote: Check this simple code: http://dpaste.dzfl.pl/2772c9144f1c I can't understand how to minimize code duplication for function like get(). Of course on real case body is much bigger and complex than that. The only way I found is to move the body of function inside a mixin template: mixin template getterImpl() { auto getterImpl() { /* very long body */ return inner; } } and then: auto get() const { mixin getterImpl; return getterImpl; } auto get() { mixin getterImpl; return getterImpl; } Am I missing something? I don't think it's the right way. You can do this using inout: http://dpaste.dzfl.pl/678cac023051 That getter can be written even shorter due to a quirk in the D syntax, like: inout get() { return inner; } But I prefer to explicitly state inout for every parameter and return type. inout is kind of a wildcard for mutable, const, and immutable. You can also add it to your function parameters, for example: inout(int[]) doSomething(inout(SomeClass) c); So the constness of doSomething's return type depends on the constness of the passed argument. What would be the C++ way? Is there any comfortable way to solve this problem in a nice way like D?
Re: Const vs Non const method
Let's use an example: import std.stdio; class Visitor { public: void visit(inout A) { writeln("visit A"); } void visit(inout B) { writeln("visit B"); } } class A { public: void accept(Visitor v) inout { v.visit(this); } } class B : A { public: override void accept(Visitor v) inout { v.visit(this); } } This piece of code works for both versions below: #1: void main() { A a = new A(); A b = new B(); Visitor v = new Visitor(); a.accept(v); b.accept(v); } #2: void main() { const A a = new A(); const A b = new B(); Visitor v = new Visitor(); a.accept(v); b.accept(v); } Thanks to the wildcard modifier inout. Is there any possible way to do the same in C++?
Re: Const vs Non const method
On Monday, 7 March 2016 at 18:17:18 UTC, Ola Fosheim Grøstad wrote: On Monday, 7 March 2016 at 16:30:48 UTC, Namespace wrote: Thanks to the wildcard modifier inout. Is there any possible way to do the same in C++? In this specific case you could do it with a macro if you don't mind dirty macros, but you really should implement the const version explicitly or use a free function that cover both cases using templating. If you are looking for information on C++ you probably should use stack overflow: http://stackoverflow.com/questions/7792052/c-template-to-cover-const-and-non-const-method Honestly speaking, I think this case is impossible to solve in C++. I'll show my fellow students the advantages of D over C++ in next couple of weeks, and this example is pretty good. :)
Re: pass a struct by value/ref and size of the struct
auto ref add(V)(auto ref V v1, auto ref V v2); // default this(this) Vec3f vec1; // accepts both lvalues and rvalues auto res = add(vec1, Vec3f(1, 2, 3.14)); auto ref produces template bloat. That is no real solution for the rvalue ref problem. But there is (more or less) a workaround: import std.stdio; import std.algorithm : sum; struct Matrix4x4 { private Matrix4x4* _ref; float[16] values = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; ref Matrix4x4 byRef() { _ref = &this; return *_ref; } double sum() const { return this.values[].sum; } } void foo(ref const Matrix4x4 mat) { writeln("foo: ", mat.sum); } void main() { Matrix4x4 m; foo(m); foo(Matrix4x4().byRef); }
Re: Garbage Collector : Ignoring a reference
On Tuesday, 26 April 2016 at 09:07:59 UTC, Begah wrote: I am trying to create an asset manager for my textures. I had the idea ( it may be a wrong idea ) to create a hashmap of my textures with a string as the key. When the program request a texture, it firts check if it is in the hashmap and then returns if it is : Texture[string] textures; Texture loadTexture(string filename) { if(filename in textures) return textures[filename] else // Load image and put it in hashmap } Warning : I haven't tested if it actually doesn't work, but thinking about it, i think it should not. My problem is that i return a reference of the texture to the program, but i keep one to myself and i want to free the texture if my program isn't using it anymore ( no more reference to it ). The problem i see, is that i will always have atleast one reference to the texture in my hashmap, but i want the garbage collector to ignore that reference and to free the texture if there are no more references anywhere in my program ( except in the hashmap ). How could i tell the garbage collector to ignore the reference in the hashmap and to free it if there isn't any other reference that in my hashmap? Texture[string] textures; Texture* loadTexture(string filename) { if(filename in textures) return &textures[filename] else // Load image and put it in hashmap } Texture* tex = loadTexture(...);
Re: inferred size for static array initialization
On Monday, 2 May 2016 at 13:00:27 UTC, Erik Smith wrote: Is there a way to initialize a static array and have it's size inferred (and that works for arrays of structs using braced literals)? This would make it easier to maintain longer static array definitions. The code below doesn't work when removing the array size even though the array is declared as static immutable. import std.traits; static immutable int[] a = [1,2,3]; static assert(isStaticArray!(typeof(a))); // fails I still like auto s(T, size_t n)(T[n] arr) { return arr; } auto arr = [1, 2, 3].s; But of course this won't work: int[] a = [1,2,3].s; static assert(isStaticArray!(typeof(a))); // fails Since 'a' is just a slice. But this will work: immutable auto a = [1,2,3].s;
Re: inferred size for static array initialization
On Monday, 2 May 2016 at 18:57:49 UTC, Namespace wrote: A slice of a no-longer-existing temporary! Admittedly, this is not an issue with your code, but a deeper issue of allowing slicing of rvalues. This works: int[] as = [1, 2, 3].s; writeln(as[2]); Of course this slice is only valid as long as you dont leave the scope. That's maybe what you tried to say, right?
Re: inferred size for static array initialization
A slice of a no-longer-existing temporary! Admittedly, this is not an issue with your code, but a deeper issue of allowing slicing of rvalues. This works: int[] as = [1, 2, 3].s; writeln(as[2]); Bug or feature? Or did I may misunderstood you? You can drop auto. It's just a placeholder for the storage class in the case where a storage class isn't specified. Right, I forgot, it's a bit since I wrote something in D.
Re: inferred size for static array initialization
On Monday, 2 May 2016 at 19:08:52 UTC, Steven Schveighoffer wrote: On 5/2/16 3:02 PM, Namespace wrote: On Monday, 2 May 2016 at 18:57:49 UTC, Namespace wrote: A slice of a no-longer-existing temporary! Admittedly, this is not an issue with your code, but a deeper issue of allowing slicing of rvalues. This works: int[] as = [1, 2, 3].s; writeln(as[2]); Of course this slice is only valid as long as you dont leave the scope. That's maybe what you tried to say, right? No, because 'as' is pointing at stack space no longer allocated. It may work, and it may not, but having it work is not proof that it's sound. To make things clear, this is what your code effectively does: int[] as = void; { auto _tmp = [1, 2, 3].s; as = _tmp; } Which is not the same thing as having the static array a defined stack variable in the same scope. -Steve The assembler looks different than that but I may be wrong and I only looked at gdc. But anyway, that means with 'pragma(inline, true)' I'm save. Is that right?
Re: inferred size for static array initialization
The assembler might be safe in some instances, but that doesn't reflect the original internal representation in the compiler. Some other configuration of calls may allow the compiler to reuse that memory, and then you run into problems. I'm wondering if you used my rewrite if it would actually output the same thing? Not quite. Look for yourself: https://godbolt.org/g/kO8hdW https://godbolt.org/g/KCfYPy
Re: inferred size for static array initialization
On Monday, 2 May 2016 at 20:05:15 UTC, Steven Schveighoffer wrote: On 5/2/16 3:38 PM, Namespace wrote: The assembler might be safe in some instances, but that doesn't reflect the original internal representation in the compiler. Some other configuration of calls may allow the compiler to reuse that memory, and then you run into problems. I'm wondering if you used my rewrite if it would actually output the same thing? Not quite. Look for yourself: https://godbolt.org/g/kO8hdW https://godbolt.org/g/KCfYPy Except for offsets, it looks identical. May be the compiler puts things in different spots for different ways of writing. But the thing that's not disclosed here is: what happens when the compiler feels the need to reuse that stack space? Your example doesn't have anything that may compete for the space, it just returns after this is over. For example, define a static array of exactly the same size to use after the call: int[3] x; Now, see if x is pigeonholed into that same place your temporary return existed (and therefore 'as' points at it). I'm still fully on the side of this being unsafe. -Steve I used it very often, but always assigned the result to an auto-type variable, never to a slice.
Re: mutable keyword
On Thursday, 19 May 2016 at 23:21:14 UTC, Jonathan M Davis wrote: On Thursday, May 19, 2016 20:44:54 ciechowoj via Digitalmars-d-learn wrote: Is there D equivalent of C++'s mutable keyword? Like the one that allows to modify a field of struct from constant method. Or some alternative solution? No. D's const and immutable provide no backdoors. But you can cheat: int* _id; struct A { int id = 0; this(int id) { this.id = id; _id = &this.id; } void change() const { (*_id)++; } } void main() { import std.stdio; A a = A(42); a.change(); writeln(a.id); }
Re: mutable keyword
On Friday, 20 May 2016 at 18:42:44 UTC, Ali Çehreli wrote: On 05/20/2016 10:28 AM, Namespace wrote: > On Thursday, 19 May 2016 at 23:21:14 UTC, Jonathan M Davis wrote: >> On Thursday, May 19, 2016 20:44:54 ciechowoj via Digitalmars-d-learn >> wrote: >>> Is there D equivalent of C++'s mutable keyword? Like the one that >>> allows to modify a field of struct from constant method. Or some >>> alternative solution? >> >> No. D's const and immutable provide no backdoors. > > But you can cheat: > > int* _id; > > struct A > { > int id = 0; > > this(int id) > { > this.id = id; > _id = &this.id; Point taken but considering that D structs are freely movable value types, I don't think that's a valid D program. The spec does ban self-referencing structs but I think it also bans the code above in spirit. :) > } > > void change() const > { > (*_id)++; > } > } > > void main() { > import std.stdio; > > A a = A(42); > a.change(); > > writeln(a.id); > } > Ali Also works for classes. ;) It's valid as far as I can tell.
Re: Default initialization of structs?
The Factory-Pattern would be a good idea.
Re: Passing structs to functions
On Saturday, 2 July 2016 at 19:40:53 UTC, phant0m wrote: On Saturday, 2 July 2016 at 19:25:37 UTC, ketmar wrote: note the first "()", though: this is effectively a template function, which compiler will instantiate either with "ref" or without it. Yeah, I've noticed it. Always using function template for this use case seems like a weird idea. Try this little trick: import std.stdio; struct A { private A* _this = null; public int id = 0; this(int id) { this.id = id; } ref A byRef() { _this = &this; return *_this; } } void foo(ref const A a) { writeln(a.id); } void main() { foo(A(42).byRef()); }
Re: Passing structs to functions
On Saturday, 2 July 2016 at 21:15:29 UTC, ketmar wrote: On Saturday, 2 July 2016 at 21:05:18 UTC, Namespace wrote: Try this little trick: or don't. such pointers to structs are *dangerous*. Either that "dangerous" thing or 2^N template bloat.
Re: Passing structs to functions
On Saturday, 2 July 2016 at 21:19:04 UTC, ketmar wrote: On Saturday, 2 July 2016 at 21:17:33 UTC, Namespace wrote: On Saturday, 2 July 2016 at 21:15:29 UTC, ketmar wrote: On Saturday, 2 July 2016 at 21:05:18 UTC, Namespace wrote: Try this little trick: or don't. such pointers to structs are *dangerous*. Either that "dangerous" thing or 2^N template bloat. not "dangerous", but *dangerous*. I see no real danger in that code snippet of mine. 'auto ref' is the wrong solution since it leads to 2^N template bloat and passing by value is only a good solution if your struct is really small.
Re: Passing structs to functions
Just for you, a slightly adapted version: import std.stdio; struct A { public int id = 0; this(int id) { this.id = id; } ref A byRef() { return this; } } void foo(ref const A a) { writeln(a.id); } void main() { foo(A(42).byRef()); }
Re: Get class name of C++ class at runtime
On Thursday, 7 July 2016 at 09:59:23 UTC, Jacob Carlborg wrote: Is it possible to get the name of a C++ class, "extern(C++) class Foo {}", at runtime just as it's possible to do the same for a D class, like "object.classinfo.name"? Maybe with a template? void class_name(T)(T obj) if (is(T == class)) { writeln(T.stringof); }
Re: Programming a Game in D? :D
On Thursday, 22 May 2014 at 15:39:36 UTC, David wrote: Hey, I'm really new to D, and pretty new to programming overall too, But I want to make a 3d Game, (just sth. small). I really like D and want to do it in D, but in the Internet there is no shit about programming a game in D ^^ Is there any engine written in D? For example the CryEngine is for C++, so I would have to write a wrapper? So, how do I write a wrapper? I would need a wrapper for DirectX too right? Are there any wrappers ore Engines for D i can use? btw. I know I dont write that in 1 day ^^ Are there any tutorials or sth. on Programming a Game in D? S I just wanna come as far to have a little Cube where i can run around on with a few phisics :) so just the startup to load a world and so on Thanks in advance :) And sry my english sucks :D As long as I've used D, I have developed on Dgame (http://dgame-dev.de/) but built only one small official game with it: http://dgame-dev.de/?page=show But anyhow, maybe it's helpfull for you. :)
Re: Any GPL video games in D2
On Wednesday, 25 June 2014 at 14:24:11 UTC, Binarydepth wrote: I would like to show D in "action" to other programmers/students. Anyone knows of a Video Game coded in D2 ? Thank you Here are two: http://dgame-dev.de/?page=show
Re: Any GPL video games in D2
On Wednesday, 25 June 2014 at 21:12:23 UTC, Binarydepth wrote: On Wednesday, 25 June 2014 at 16:37:13 UTC, Namespace wrote: On Wednesday, 25 June 2014 at 14:24:11 UTC, Binarydepth wrote: I would like to show D in "action" to other programmers/students. Anyone knows of a Video Game coded in D2 ? Thank you Here are two: http://dgame-dev.de/?page=show That's great.They are using Derelict3 and SDL. It's in very good shape for what I want to do :) Actually, they use Dgame. Dgame however used Derelict3 (SDL & OpenGL). :)
Re: Want to read a whole file as utf-8
On Tuesday, 3 February 2015 at 23:55:19 UTC, FG wrote: On 2015-02-04 at 00:07, Foo wrote: How would I use decoding for that? Isn't there a way to read the file as utf8 or event better, as unicode? Well, apparently the utf-8-aware foreach loop still works just fine. This program shows the file size and the number of unicode glyps, or whatever they are called: import core.stdc.stdio; int main() @nogc { const int bufSize = 64000; char[bufSize] buffer; size_t bytesRead, count; FILE* f = core.stdc.stdio.fopen("test.d", "r"); if (!f) return 1; bytesRead = fread(cast(void*)buffer, 1, bufSize, f); if (bytesRead > bufSize - 1) { printf("File is too big"); return 1; } if (!bytesRead) return 2; foreach (dchar d; buffer[0..bytesRead]) count++; printf("read %d bytes, %d unicode characters\n", bytesRead, count); fclose(f); return 0; } Outputs for example this: read 838 bytes, 829 unicode characters (It would be more complicated if it had to process bigger files.) To use a foreach loop is such a nice idea! tank you very much. :) That's my code now: private: static import m3.m3; static import core.stdc.stdio; alias printf = core.stdc.stdio.printf; public: @trusted @nogc auto readFile(in string filename) nothrow { import std.c.stdio : FILE, SEEK_END, SEEK_SET, fopen, fclose, fseek, ftell, fread; FILE* f = fopen(filename.ptr, "rb"); fseek(f, 0, SEEK_END); immutable size_t fsize = ftell(f); fseek(f, 0, SEEK_SET); char[] str = m3.m3.make!(char[])(fsize); fread(str.ptr, fsize, 1, f); fclose(f); return str; } @trusted @nogc @property dstring toUTF32(in char[] s) { dchar[] r = m3.m3.make!(dchar[])(s.length); // r will never be longer than s foreach (immutable size_t i, dchar c; s) { r[i] = c; } return cast(dstring) r; } @nogc void main() { auto str = readFile("test_file.txt"); scope(exit) m3.m3.destruct(str); auto str2 = str.toUTF32; printf("%d : %d\n", cast(int) str[0], cast(int) str2[0]); } m3 is my own module and means "manual memory management", three m's so m3. If we will use D (what is now much more likely) that is our core module for memory management.
Re: Better native D 2D graphics library?
On Saturday, 7 February 2015 at 22:09:03 UTC, Gan wrote: Is there a better D graphics library in the works? I'm using SFML(which is very easy and has lots of features) but it seems to use a lot of ram(if you leave it running for a while on a graphic intensive scene) and trying to make it include the dependencies with the compiled executable is complicated. Is there a D 2D graphics library that's just as easy, cross platform, doesn't use X11, allows drawing to off-screen buffers and drawing those to screen? (plus supports nice drawing of shapes, circles, rectangles, lines) I'm probably asking too much- I doubt such a thing exists. I once wrote such a library: https://github.com/Dgame/Dgame But since I left D I don't maintain it. Maybe that will change in the next few weeks. But otherwise you are free to use or improve it.
Re: Better native D 2D graphics library?
On Sunday, 8 February 2015 at 01:39:19 UTC, Gan wrote: On Saturday, 7 February 2015 at 23:29:01 UTC, Namespace wrote: On Saturday, 7 February 2015 at 22:09:03 UTC, Gan wrote: Is there a better D graphics library in the works? I'm using SFML(which is very easy and has lots of features) but it seems to use a lot of ram(if you leave it running for a while on a graphic intensive scene) and trying to make it include the dependencies with the compiled executable is complicated. Is there a D 2D graphics library that's just as easy, cross platform, doesn't use X11, allows drawing to off-screen buffers and drawing those to screen? (plus supports nice drawing of shapes, circles, rectangles, lines) I'm probably asking too much- I doubt such a thing exists. I once wrote such a library: https://github.com/Dgame/Dgame But since I left D I don't maintain it. Maybe that will change in the next few weeks. But otherwise you are free to use or improve it. That's really cool. Very very similar to SFML. Only thing that makes me concerned is: static immutable string Disk = "D"; static immutable string Mode = "Release"; pragma(lib, Disk ~ ":\\D\\dmd2\\src\\ext\\derelict\\lib\\dmd\\DerelictSDL2.lib"); pragma(lib, Disk ~ ":\\D\\dmd2\\src\\ext\\derelict\\lib\\dmd\\DerelictUtil.lib"); pragma(lib, Disk ~ ":\\D\\dmd2\\src\\ext\\derelict\\lib\\dmd\\DerelictGL3.lib"); pragma(lib, Disk ~ ":\\D\\dmd2\\src\\ext\\Dgame\\lib\\" ~ Mode ~ "\\DgameInternal.lib"); pragma(lib, Disk ~ ":\\D\\dmd2\\src\\ext\\Dgame\\lib\\" ~ Mode ~ "\\DgameAudio.lib"); pragma(lib, Disk ~ ":\\D\\dmd2\\src\\ext\\Dgame\\lib\\" ~ Mode ~ "\\DgameGraphics.lib"); pragma(lib, Disk ~ ":\\D\\dmd2\\src\\ext\\Dgame\\lib\\" ~ Mode ~ "\\DgameSystem.lib"); pragma(lib, Disk ~ ":\\D\\dmd2\\src\\ext\\Dgame\\lib\\" ~ Mode ~ "\\DgameMath.lib"); pragma(lib, Disk ~ ":\\D\\dmd2\\src\\ext\\Dgame\\lib\\" ~ Mode ~ "\\DgameWindow.lib"); I'm not entirely sure what that is or if it's cross-compatible friendly or sharing-with-friends friendly. Though I really hope you re-maintain it. It worked on Mac, Linux and Windows so far without any problems. Forget to add the documentation page I made: http://rswhite.de/dgame4/
Re: Better native D 2D graphics library?
Let me hear what comes out. ;)
Re: Better native D 2D graphics library?
On Monday, 9 February 2015 at 05:50:00 UTC, uri wrote: On Saturday, 7 February 2015 at 23:29:01 UTC, Namespace wrote: On Saturday, 7 February 2015 at 22:09:03 UTC, Gan wrote: Is there a better D graphics library in the works? I'm using SFML(which is very easy and has lots of features) but it seems to use a lot of ram(if you leave it running for a while on a graphic intensive scene) and trying to make it include the dependencies with the compiled executable is complicated. Is there a D 2D graphics library that's just as easy, cross platform, doesn't use X11, allows drawing to off-screen buffers and drawing those to screen? (plus supports nice drawing of shapes, circles, rectangles, lines) I'm probably asking too much- I doubt such a thing exists. I once wrote such a library: https://github.com/Dgame/Dgame But since I left D I don't maintain it. Maybe that will change in the next few weeks. But otherwise you are free to use or improve it. I use Dgame for hobby projects and can definitely recommend it. That's nice to hear! Thank you.
How can I do that in @nogc?
void glCheck(lazy void func, string file = __FILE__, uint line = __LINE__) { func(); glCheckError(file, line); } How can I specify that 'func' is @nogc? Or can define the function otherwise?
Re: How can I do that in @nogc?
On Wednesday, 25 February 2015 at 20:15:10 UTC, anonymous wrote: On Wednesday, 25 February 2015 at 19:32:50 UTC, Namespace wrote: void glCheck(lazy void func, string file = __FILE__, uint line = __LINE__) { func(); glCheckError(file, line); } How can I specify that 'func' is @nogc? Or can define the function otherwise? First of all, if glCheck always uses/evaluates func, then there is no point in making it lazy. On to the @nogc vs. lazy issue. Simpler test case: --- void glCheck(scope lazy int thing) @nogc {auto x = thing;} int costly() @nogc {return 42;} void main() @nogc { glCheck(costly()); /* A */ int x; glCheck(x); /* B */ } --- I guess, the compiler could see that the delegate made for the lazy parameter must be @nogc. But it doesn't. So it tries to call a non-@nogc delegate in a @nogc function which fails of course. You can make the delegate explicit so that you can tag the delegate as @nogc yourself: --- void glCheck(scope int delegate() @nogc thing) @nogc {auto x = thing();} int costly() @nogc {return 42;} void main() @nogc { glCheck(()=>costly()); int x; glCheck(()=>x); } --- The calls are not as nice, requiring an explicit delegate ("()=>"), but it works. It may be possible to hack through this limitation - NOT THOUGHT-OUT, NOT TESTED, NOT RECOMMENDED: --- void glCheck(scope lazy int thing) @nogc; pragma(mangle, glCheck.mangleof) void glCheckImpl(scope int delegate() @nogc thing) @nogc {auto x = thing();} int costly() @nogc {return 42;} void main() @nogc { glCheck(costly()); int x; glCheck(x); } --- That last thing works. But I have no clue why. o.O Anyway, thanks a lot!
Re: How can I do that in @nogc?
On Wednesday, 25 February 2015 at 19:53:16 UTC, Ivan Timokhin wrote: On Wed, Feb 25, 2015 at 07:32:48PM +, Namespace wrote: void glCheck(lazy void func, string file = __FILE__, uint line = __LINE__) { func(); glCheckError(file, line); } How can I specify that 'func' is @nogc? Or can define the function otherwise? Try void glCheck(scope void delegate() @nogc func,...) That seems not to work: Error: function test.glCheck (scope void delegate() @nogc func, ...) is not callable using argument types (void)
Re: How can I do that in @nogc?
On Wednesday, 25 February 2015 at 20:46:32 UTC, ketmar wrote: On Wed, 25 Feb 2015 20:36:32 +, Namespace wrote: That last thing works. But I have no clue why. o.O Anyway, thanks a lot! this is a smart hack. that should be NEVER used in production code. anyway, it's good that you don't understand it. your code will crash sooner or later, and you will be forced to remove that trick. Instead of some wise talk, you could simply explain it. ;) The code is only used for debugging purposes.
Re: Will D have a serious dedicated well supported IDE like Visual Studio or Eclipse?
On Thursday, 26 February 2015 at 20:55:52 UTC, Rinzler wrote: Thanks! Actually I had already seen that page, but I was asking for other open-source projects. If there's someone working on a D dedicated IDE or not. You could search on dub: http://code.dlang.org/
New package behaviour in 2.067
I'm unsure, but I think this code should work: module A.B.Foo; import core.stdc.stdio : printf; struct Foo { package(A) void foo() { printf("Hallo\n"); } } package(A) void bar() { printf("Hallo\n"); } and module A.C.Bar; import A.B.Foo; void main() { Foo f; f.foo(); bar(); } The call of bar() works, but f.foo() triggers the error: Error: struct A.B.Foo.Foo member foo is not accessible Is this intended?
Bypass the protection level
Let's say we have these files: module Foo.Graphic.Drawable; interface Drawable { void draw(bool); } module Foo.Graphic.Sprite; import Foo.Graphic.Drawable; class Sprite : Drawable { protected: void draw(bool enable) { import core.stdc.stdio : printf; if (enable) printf("draw\n"); else printf("no drawing...\n"); } } module Foo.Window.Window; import Foo.Graphic.Drawable; class Window { void draw(Drawable d) { d.draw(true); } } I can call draw on Drawable, because it is declared public and I cannot call draw on Sprite because it is declared protected (this is already a bit weird, why can I redeclare the interface method draw as protected?) but I can call the protected draw method from Sprite through Drawable. Is this intended?
Re: Template. C++ to D
import std.stdio; T foo(T)(auto ref const T val) { return val; } T foo(T, Args...)(auto ref const T val, auto ref const Args u) { static if (is(T == string)) return val ~ foo(u); else return val + foo(u); } void main() { writeln(foo("some ", "test")); // prints some test writeln(foo(2, 2, 1)); // prints 5 }
Re: Template. C++ to D
Or even shorter: import std.stdio; T foo(T, Args...)(auto ref const T val, auto ref const Args u) { static if (Args.length > 0) { static if (is(T == string)) return val ~ foo(u); else return val + foo(u); } else { return val; } } void main() { writeln(foo("some ", "test")); // prints some test writeln(foo(2, 2, 1)); // prints 5 }
enum and static if
This code does not work: enum Test { Foo, static if (__VERSION__ >= 2067) Bar, } Quatz } Any chance that this could work?
Re: enum and static if
On Wednesday, 11 March 2015 at 14:34:32 UTC, ketmar wrote: On Wed, 11 Mar 2015 13:48:45 +, Namespace wrote: This code does not work: enum Test { Foo, static if (__VERSION__ >= 2067) Bar, } Quatz } Any chance that this could work? nope. `static if` is statement, so it works only where statement is allowed. the same is true for `version`. this is by design. Thanks, I've hoped that 'static if' is a full replacement for #if
Re: Bypass the protection level
Could it be that this is intentional and has always worked?
Re: Bypass the protection level
On Wednesday, 11 March 2015 at 15:22:43 UTC, Ali Çehreli wrote: On 03/11/2015 04:40 AM, Namespace wrote: > I can call draw on Drawable, because it is declared public and I cannot > call draw on Sprite because it is declared protected (this is already a > bit weird, why can I redeclare the interface method draw as protected?) It is the same in C++. > but I can call the protected draw method from Sprite through Drawable. > Is this intended? As far as I know, yes it's intended and again the same in C++. Ali o.O nice to know. Thank you.
Re: moving from c++ to D is easy?
On Thursday, 12 March 2015 at 18:57:51 UTC, Ali Çehreli wrote: On 03/12/2015 06:01 AM, ayush wrote: > Is D a lot like c++ ? I came to D from C++. I remember the following being notable differences: - In D, classes have reference semantics. I quickly realized that this is not an issue because so many of my C++ types were hand-reference-typified :p by this idiom, almost everywhere: class C { /* ... */ }; typedef boost::shared_ptr CPtr; void foo(CPtr c); This is a common mistake. In 99 percent of cases you want to use a std::unique_ptr. std::shared_ptr is rarely common and often an indication of an error in design. In general, there is exactly one owner only. But I think you know that already. :)
Re: moving from c++ to D is easy?
On Thursday, 12 March 2015 at 21:41:07 UTC, Ali Çehreli wrote: On 03/12/2015 01:19 PM, Namespace wrote: > On Thursday, 12 March 2015 at 18:57:51 UTC, Ali Çehreli wrote: >> On 03/12/2015 06:01 AM, ayush wrote: >> >> > Is D a lot like c++ ? >> >> I came to D from C++. I remember the following being notable differences: >> >> - In D, classes have reference semantics. I quickly realized that this >> is not an issue because so many of my C++ types were >> hand-reference-typified :p by this idiom, almost everywhere: >> >> class C { /* ... */ }; >> typedef boost::shared_ptr CPtr; >> void foo(CPtr c); > > This is a common mistake. In 99 percent of cases you want to use a > std::unique_ptr. Agreed. Here is an excerpt from a comment from one of our header files: "We could not use boost::unique_ptr because the version of the Boost library that we currently use does not include it." > std::shared_ptr is rarely common and often an indication of an > error in design. In general, there is exactly one owner only. Of course. We had definitions like the following as well, where the C objects are stored in: typedef vector MyCs; > But I think you know that already. :) I think so. :) Maybe we should pass weak_ptrs around instead of shared_ptr. You could also pass raw pointers around. Since they have no owner it's fine. Or references. Anyway... That's old code and this is a D newsgroup. Ali Agreed.
Re: 'strong types' a la boost
You can do it this way: struct dollars_t { uint _dollar; this(uint d) { _dollar = d; } alias _dollar this; } struct cents_t { uint _cent; this(uint c) { _cent = c; } alias _cent this; } void do_something_with_dollars(dollars_t d) { writeln(d); } void main() { dollars_t d = 1; do_something_with_dollars(d); cents_t c = 2; //do_something_with_dollars(c); //do_something_with_dollars(2); } Or you can create your own small TypeDef: struct TypeDef(T, size_t l = __LINE__) { T _val; this(T v) { _val = v; } alias _val this; } alias dollars_t = TypeDef!(uint); alias cents_t = TypeDef!(uint); Thanks to the second template parameter 'l' the template instances of dollars_t and cents_t aren't equal.
Re: 'strong types' a la boost
On Saturday, 14 March 2015 at 16:55:09 UTC, Charles Cooper wrote: Interesting. I think in the second example there are pathological cases where one has similar declarations in two modules at the same line. Yes, that right, I've kept it simple, but of course it is not complete safe. :)
ref for (const) variables
Currently, if you want to store a long getter into a variable without copying it (because it may be a big struct), your only way is to store it as a pointer: struct Matrix { float[16] values= [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; } struct Test { private: Matrix _matrix; public: ref const(Matrix) getCurrentModelViewMatrix() const pure nothrow { return _matrix; } } void main() { Test t; const(Matrix)* m = &t.getCurrentModelViewMatrix(); // currently } But IMO it would be a lot nicer if I could store the reference like this: ref const(Matrix) m = t.getCurrentModelViewMatrix(); // nicer [Of course the name is exaggerated for the purpose of demonstration.] May this be worth of an enhancement request? Or was this already rejected? And, no, I want no mutable references such as C++.
Re: ref for (const) variables
On Monday, 16 March 2015 at 19:20:09 UTC, anonymous wrote: On Monday, 16 March 2015 at 18:47:00 UTC, Namespace wrote: const(Matrix)* m = &t.getCurrentModelViewMatrix(); // currently } But IMO it would be a lot nicer if I could store the reference like this: ref const(Matrix) m = t.getCurrentModelViewMatrix(); // nicer [Of course the name is exaggerated for the purpose of demonstration.] May this be worth of an enhancement request? Maybe, but I think you'd have to present a better argument. It's not obvious to me how `ref T x = y;` is supposed to be a lot nicer than `T* x = &y;`. It is, for example, not nullable. ;) Or was this already rejected? I don't know. But since it's a C++ thing, it's probably been discussed. I will research this. Thank you.
Re: ref for (const) variables
On Tuesday, 17 March 2015 at 09:56:09 UTC, Jonathan M Davis wrote: On Monday, March 16, 2015 18:46:59 Namespace via Digitalmars-d-learn wrote: May this be worth of an enhancement request? Or was this already rejected? And, no, I want no mutable references such as C++. Walter has been adamantly against having ref variables like C++ has. They're a potential @safety issue and add a fair bit of complication to the language. I doubt that suggesting that we have them as const-only would change his mind any - especially since that addresses none of the @safety issues. - Jonathan M Davis If I can't mutate them, where are the @safety issues?
Re: PrimitiveRef ?
Something like that? struct PrimitiveRef(T) { private T* _value; @property ref inout(T) get() inout pure nothrow { assert(_value); return *_value; } alias get this; this(T val) { _value = new T(val); } } alias BoolRef = PrimitiveRef!bool; void test(BoolRef b) { b = true; } void main() { BoolRef b = false; test(b); assert(b == true); }
Re: reinterpret_cast float to uint
On Sunday, 29 March 2015 at 16:29:40 UTC, ketmar wrote: On Sun, 29 Mar 2015 16:00:05 +, matovitch wrote: On Sunday, 29 March 2015 at 14:50:24 UTC, ketmar wrote: On Sun, 29 Mar 2015 13:45:10 +, matovitch wrote: you can also use unions. Good idea ! In my case I think it was better to cast, but this could be helpful another time thanks ! :) unions also looks better than pointers, and they are easier to read, i think. ;-) union FU { float f; uint u; } void main () pure { float t = 42.0; assert((cast(FU)t).u == 0x4228); } AFAIK this would be undefined behaviour in C++, right?
Re: Issue with free() for linked list implementation
On Friday, 3 April 2015 at 22:02:13 UTC, Kitt wrote: Hello. I’m trying to write my own version of a list that doesn’t rely on the garbage collector. I’m working on a very bare bones implementation using malloc and free, but I’m running into an exception when I attempt to call free. Here is a very minimal code sample to illustrate the issue: // Some constant values we can use static const int two = 2, ten = 10; // Get memory for two new nodes Node* head = cast(Node*)malloc(two.sizeof); Node* node1 = cast(Node*)malloc(ten.sizeof); // Initialize the nodes node1.value = ten; node1.next = null; head.value = two; head.next = node1; // Attempt to free the head node Node* temp = head.next; head.next = null; free(head); // Exception right here head = temp; Note, if I comment out the line ‘head.next = node1’, this code works. Does anyone know what I’m doing wrong with my manual memory management? Why did you allocate only 2 / 10 bytes and not Node.sizeof bytes? Since your Node struct has at least one pointer (nexT) and a value (I assume of type int) you must allocate at least 8 bytes for one Node. I'm sure that is at least one of your problems.
Re: Issue with free() for linked list implementation
Wow, I can't even begin to explain how red my cheeks are right now. You're completely right; I have no idea what my head was thinking. Sure enough, call malloc with the correct type, and the error goes away =P Thanks for the help =) I guess I've been in C# land at work for way too long now, my low level C skills are evaporating! Sometimes you wonder how simple such a problem can be. :D My pleasure.
Re: Issue with free() for linked list implementation
On Friday, 3 April 2015 at 22:38:00 UTC, Gary Willoughby wrote: On Friday, 3 April 2015 at 22:08:52 UTC, Kitt wrote: Thanks for the help =) I guess I've been in C# land at work for way too long now, my low level C skills are evaporating! I've written a straight forward linked list implementation here: https://github.com/nomad-software/etcetera/blob/master/source/etcetera/collection/linkedlist.d Even though I'm using the GC to manage memory, maybe it will help you. Good idea to link to some existing code. Here is mine: https://github.com/Dgame/m3/blob/master/source/m3/List.d
Re: Issue with free() for linked list implementation
On Saturday, 4 April 2015 at 09:05:03 UTC, bearophile wrote: Namespace: I've written a straight forward linked list implementation here: https://github.com/nomad-software/etcetera/blob/master/source/etcetera/collection/linkedlist.d Even though I'm using the GC to manage memory, maybe it will help you. Good idea to link to some existing code. Here is mine: https://github.com/Dgame/m3/blob/master/source/m3/List.d In 99%+ of cases it's a bad idea to use a linked list. Bye, bearophile The thread creator wanted to use it.
Re: Conditional compilation for debug/release
On Monday, 6 April 2015 at 14:50:29 UTC, Johan Engelen wrote: How do conditionally compile code for either release ("-release") or debug ("-debug")? Something like this: version(Debug) { pragma(lib, "libcmtd.lib"); } else { pragma(lib, "libcmt.lib"); } In the documentation [1], I don't see any predefined version identifiers for this purpose. Thanks, Johan [1] http://dlang.org/version.html debug { pragma(lib, "libcmtd.lib"); } else { pragma(lib, "libcmt.lib"); }
Re: Conditional compilation for debug/release
On Monday, 6 April 2015 at 15:15:48 UTC, Johan Engelen wrote: On Monday, 6 April 2015 at 14:55:58 UTC, Namespace wrote: debug { pragma(lib, "libcmtd.lib"); } else { pragma(lib, "libcmt.lib"); } Thanks for the quick reply! Worth adding an example like that to http://dlang.org/version.html ? It's there already: http://dlang.org/version.html#debug ;)
Re: Issue with free() for linked list implementation
2. When you malloc, you use 'two.sizeof' and 'ten.sizeof'. Integers are 4 bytes, so you were allocating 4 bytes for each of these (not 2 or 10 bytes as is alluded to above). Yeah, my mistake. I saw the mistake but could not describe it correctly. :)
Re: [DerelictOrg] Forum down ?
On Tuesday, 7 April 2015 at 10:48:38 UTC, ParticlePeter wrote: Hi, I think I have a bug report for DerelictGL3, but cannot find the related Forum ( http://dblog.aldacron.net/forum/index.php ), is it still in the process of being moved ? Regards, ParticlePeter Post it there: https://github.com/DerelictOrg/DerelictGL3/issues
Re: alias this of non-public member
On Tuesday, 7 April 2015 at 17:21:09 UTC, Daniel Kozak wrote: On Tue, 07 Apr 2015 16:40:29 + via Digitalmars-d-learn wrote: Hi! Excuse me if this is obvious, but I can't recall coming across anything similar and a quick search returns nothing relevant: struct Foo { } struct FooWrapper { alias x_ this; private Foo* x_; // doesn't work, as x_ is private } Basically, I want x_ to never be visible, except through the "alias this" mechanism, at which point it should instead be seen as public. Assuming something like this is not already possible in a clean way, I would like to suggest a tiny(I think) addition to the language: struct FooWrapper { public alias x_ this; // overrides the visibility through the alias; private Foo* x_; } While I think this would be useful for the language, the reason I want such a wrapper, is because I want to give opIndex, toString, to a pointer, or, in fact just value semantics, while keeping the rest of the interface through the pointer. I thought about using a class instead of a struct pointer, but I am not sure about the memory layout for classes, nor about the efficiency of overriding Object's methods, so I didn't want to risk making it any less efficient. If someone could shed some light about D's class memory layout and general performance differences to a simple struct (or a C++ class for that matter), that would also be great. In general, more information about these sort of things would be great for us also-C++ programmers. :) Works for me: struct M { void callMe() { writeln("Ring..."); } } struct S { alias m this; private M m; } void main(string[] args) { S s; s.callMe(); } Modules are like friends in C++: Even private members can be accessed. @ Márcio Martins: You need a public getter function: @property @nogc @safe inout(Foo*) getFoo() inout pure nothrow { return x_; } alias getFoo this;
Reuse object memory?
Is it somehow possible to reuse the memory of an object? My current idea is: @nogc T emplace(T, Args...)(ref T obj, auto ref Args args) nothrow if (is(T == class)) { if (obj is null) return null; enum size_t SIZE = __traits(classInstanceSize, T); void[] buf = (cast(void*) obj)[0 .. SIZE]; buf = typeid(T).init[]; //obj = cast(T) buf.ptr; static if (args.length) obj.__ctor(args); return obj; } Foo f = new Foo(42); Foo f2 = emplace(f, 23); But is there a more elegant way to do that? Maybe without calling the internal __ctor? In C++ you can do that: #include class Foo { public: int id; explicit Foo(int _id) : id(_id) { } }; int main() { Foo* f = new Foo(42); std::cout << f << ':' << f->id << std::endl; new (f) Foo(23); std::cout << f << ':' << f->id << std::endl; delete f; }
Re: Reuse object memory?
And if I have an already instantiated object? Foo f = new Foo(); // reuse f's memory Is there an nicer way to override the memory instead of: void[] buf = (cast(void*) f)[0 .. __traits(classInstanceSize, Foo)]; buf = typeid(Foo).init[]; // or: buf = f.classinfo.init[]; ? The void* cast looks very ugly.
Re: Reuse object memory?
It seems that D has currently no direct support to reuse object memory. D should add a new-placement syntax: Foo f = new Foo(42); new (f) Foo(23); and/or should add an emplace overload which takes an object: T emplace(T, Args...)(ref T obj, auto ref Args args) if (is(T == class)) { if (obj is null) return null; enum size_t ClassSize = __traits(classInstanceSize, T); void[] buf = (cast(void*) obj)[0 .. ClassSize]; import std.conv : emplace; return emplace!(T)(buf, args); }
Re: Reuse object memory?
On Sunday, 19 April 2015 at 21:17:18 UTC, Ali Çehreli wrote: On 04/19/2015 09:04 AM, Namespace wrote: > Is it somehow possible to reuse the memory of an object? Yes, when you cast a class variable to void*, you get the address of the object. > @nogc > T emplace(T, Args...)(ref T obj, auto ref Args args) nothrow if (is(T == > class)) { There is already std.conv.emplace: import std.conv; import core.memory; class Foo { int i; this(int i) { this.i = i; } } void main() { void* buffer = GC.calloc(1234); enum FooSize = __traits(classInstanceSize, Foo); /* These two object are constructed on a void[] slice: */ auto f = emplace!Foo(buffer[0..FooSize], 42); auto f2 = emplace!Foo(buffer[0..FooSize], 43); /* f3 is constructed on top of an existing object: */ auto f2_addr = cast(void*)f2; auto f3 = emplace!Foo(f2_addr[0..FooSize], 44); /* At this point, all three reference the same object: */ assert(&f.i == &f2.i); assert(&f.i == &f3.i); } Ali I'm sorry if I annoy you, but I would really like to know how you would reuse already instantiated storage of an existing object. Example code: final class Foo { uint id; @nogc this(uint id) { this.id = id; } } Foo f = new Foo(42);
Re: Reuse object memory?
Thank you. Do you mean this is worth a PR, to add this functionality to Phobos? My current code looks like this: http://dpaste.dzfl.pl/19b78a600b6c
Re: Reuse object memory?
On Monday, 20 April 2015 at 21:58:59 UTC, Ali Çehreli wrote: On 04/20/2015 02:44 PM, Namespace wrote: > Thank you. Do you mean this is worth a PR, to add this > functionality to Phobos? I am not familiar with such a need so I don't have a strong opinion. However, if an object needs to be emplaced on top of an existing one, I can imagine that the original object was emplaced on some piece of memory anyway. In that case, the problem becomes "emplacing an object on a piece of memory", which is already supported by std.conv.emplace. Your idea seems to be for the case where the original object is created by some third party code, and that they want us to replace it with another object. If they are aware of the wholesale change in the object, fine. :) Ali I have currently an array of objects which may be reloaded (it's a tilemap). If the array is reused, I can do that with: arr.length = 0; arr.assumeSafeAppend(); But then I thought: why not reuse the memory of the objects? In C++ you can do that very elegant, but in D I have to produce garbage since the old object stays alive until the GC collects it and I have to allocate new GC memory.
Re: Example from d-idioms is incorrect
On Thursday, 30 April 2015 at 21:30:36 UTC, TheGag96 wrote: I was looking at the d-idioms website today and saw this code example: http://p0nce.github.io/d-idioms/#Adding-or-removing-an-element-from-arrays And I was kind of irked. I just recently working with removing an element from an array in a small project I worked on two weeks ago, and I had to learn the hard way that to properly remove an element from an array in the way this example describes, you have to do array.length--; as well. This code: import std.stdio, std.algorithm; void main() { int[] arr; //ensuring it's dynamic arr ~= 1; arr ~= 5; arr ~= 10; arr.remove(1); writeln(arr); writeln(arr == [1, 10]); arr.length--; writeln(arr); writeln(arr == [1, 10]); } produces this output: [1, 10, 10] false [1, 10] true Compiled and ran on Windows, dmd v2.067.0. Unless I'm totally missing something here, that website is giving some pretty wrong information... Was the behavior of the remove() function changed recently? Thanks guys. http://dpaste.dzfl.pl/007a9319371d Application output: [1, 10] true [1] false
Re: Example from d-idioms is incorrect
Same output: [1, 10] true [1] false with dmd 2.067.1
Re: Factory pattern in D
How about this: struct A { int x = 42; } struct B { int x = 7; } T factory(T)() { return T(); } void main() { auto a = factory!(A); }
Re: Factory pattern in D
On Friday, 1 May 2015 at 10:04:46 UTC, Namespace wrote: How about this: struct A { int x = 42; } struct B { int x = 7; } T factory(T)() { return T(); } void main() { auto a = factory!(A); } Of course, you can restrict the type to A or B, or both: T factory(T)() if (is(T == A) || is(T == B)) { return T(); }
Re: Efficiently passing structs
I've discussed that so many times... just search for auto / scope ref... ;) It will never happen. See: http://forum.dlang.org/thread/ntsyfhesnywfxvzbe...@forum.dlang.org?page=1 http://forum.dlang.org/thread/ylebrhjnrrcajnvtt...@forum.dlang.org?page=1 http://forum.dlang.org/thread/mailman.2989.1356370854.5162.digitalmar...@puremagic.com http://forum.dlang.org/thread/tkzyjhshbqjqxwzpp...@forum.dlang.org#post-mailman.2965.1356319786.5162.digitalmars-d-learn:40puremagic.com http://forum.dlang.org/thread/hga1jl$18hp$1...@digitalmars.com
Re: Efficiently passing structs
On Tuesday, 5 May 2015 at 21:58:57 UTC, bitwise wrote: On Tue, 05 May 2015 17:33:09 -0400, Namespace wrote: I've discussed that so many times... just search for auto / scope ref... ;) It will never happen. See: http://forum.dlang.org/thread/ntsyfhesnywfxvzbe...@forum.dlang.org?page=1 http://forum.dlang.org/thread/ylebrhjnrrcajnvtt...@forum.dlang.org?page=1 http://forum.dlang.org/thread/mailman.2989.1356370854.5162.digitalmar...@puremagic.com http://forum.dlang.org/thread/tkzyjhshbqjqxwzpp...@forum.dlang.org#post-mailman.2965.1356319786.5162.digitalmars-d-learn:40puremagic.com http://forum.dlang.org/thread/hga1jl$18hp$1...@digitalmars.com I did read some of these. Has anyone brought up simply allowing "in ref" or "const scope ref" to accept rvalues? If DIPs 69 and 25 were implemented, I don't see why this would be a problem. I agree that "const ref" should not, but I don't see a problem with "const scope ref". I haven't seen a conversation that was strongly in favor of DIP 36. Why hasn't it been rejected? Bit We proposed that in DIP 36: http://forum.dlang.org/thread/ylebrhjnrrcajnvtt...@forum.dlang.org?page=1 Some more interesting discussion parts: http://forum.dlang.org/thread/4f84d6dd.5090...@digitalmars.com http://forum.dlang.org/thread/km3k8v$80p$1...@digitalmars.com?page=1 http://forum.dlang.org/thread/cafdvkcvf6g8mc01tds6ydxqczbfp1q-a-oefvk6bgetwciu...@mail.gmail.com As you can see there are debate for ages. Many people of the community really wants a solution, but since Andrei and Walter believe that it brings no real benefit, nothing has changed. I stuck with auto ref + templates if I need lvalues + rvalues (which is often the case in game dev).
Re: Dynamic / resizable array type, and a crash problem
On Thursday, 14 May 2015 at 13:26:27 UTC, ivoras wrote: On Thursday, 14 May 2015 at 12:46:48 UTC, Adam D. Ruppe wrote: I would just use a regular `string[]` array... Is it resizable? Somehow I didn't get that impression from the docs. Apparently it doesn't even have an "insert" method: http://dlang.org/phobos/std_array.html . string[] arr; arr ~= "Foo"; arr ~= "Bar"; writeln(arr, ':', arr.length); It's all built in. ;) A nice article: http://dlang.org/d-array-article.html and the language reference: http://dlang.org/arrays.html
ICE?
Is this error an ICE? I think so, because I see the internal filename, but I'm not sure. Error: e2ir: cannot cast malloc(length * 8u) of type void* to type char[]
Re: ICE?
On Sunday, 17 May 2015 at 09:30:16 UTC, Gary Willoughby wrote: On Sunday, 17 May 2015 at 09:25:33 UTC, Namespace wrote: Is this error an ICE? I think so, because I see the internal filename, but I'm not sure. Error: e2ir: cannot cast malloc(length * 8u) of type void* to type char[] Have you got a code sample to reproduce this? Of course: void main() { import core.stdc.stdlib : malloc, free; auto ptr = cast(char[]) malloc(42); }
Re: ICE?
On Sunday, 17 May 2015 at 09:59:41 UTC, Daniel Kozak wrote: On Sun, 17 May 2015 09:33:27 + Namespace via Digitalmars-d-learn wrote: On Sunday, 17 May 2015 at 09:30:16 UTC, Gary Willoughby wrote: > On Sunday, 17 May 2015 at 09:25:33 UTC, Namespace wrote: >> Is this error an ICE? I think so, because I see the >> internal filename, but I'm not sure. >> >> Error: e2ir: cannot cast malloc(length * 8u) of type void* >> to type char[] > > Have you got a code sample to reproduce this? Of course: void main() { import core.stdc.stdlib : malloc, free; auto ptr = cast(char[]) malloc(42); } I guess it should be: auto ptr = cast(char*)malloc(42)[0 .. 42]; That would work, but I did it on purpose. I wanted to test whether such dangerous code compiles or whether the compiler is smart enough and hits the alarm.
Re: overloading evaluation (treating objects as functions)
On Sunday, 17 May 2015 at 18:49:40 UTC, dan wrote: Is it possible to define a class F so that auto f=new F(); writeln("The value of f at 7 is ",f(7)); compiles and works as expected? So the idea would be to be able to use notation like f(7) instead of f.eval(7) or something along those lines. My guess is no, it is impossible to do this, because i can't find it on the internet or in Alexandrescu's book. But it is also possible that everybody considers it so obvious that they just don't elaborate on it. I'd be delighted if there were the case, at least if somebody would elaborate on it if so. TIA for any info! dan http://dlang.org/operatoroverloading.html#function-call
Re: -vgc Info ok?
On Monday, 18 May 2015 at 14:30:43 UTC, Chris wrote: The following string[string] myarray = ["key":"value"]; string entry; entry = myarray["key"]; // => vgc: indexing an associative array may cause GC allocation Why is _accessing_ an assoc treated as indexing it? No error if you use myarray.get("key", null); or string* entry = "key" in myarray;
Re: -vgc Info ok?
On Tuesday, 19 May 2015 at 09:43:06 UTC, Chris wrote: On Tuesday, 19 May 2015 at 09:10:50 UTC, Namespace wrote: On Monday, 18 May 2015 at 14:30:43 UTC, Chris wrote: The following string[string] myarray = ["key":"value"]; string entry; entry = myarray["key"]; // => vgc: indexing an associative array may cause GC allocation Why is _accessing_ an assoc treated as indexing it? No error if you use myarray.get("key", null); or string* entry = "key" in myarray; What are the advantages / disadvantages of the two methods? You could get null with "in" if your key is not there. Besides that, no disadvantages.
Re: GC Destruction Order
On Tuesday, 19 May 2015 at 19:36:23 UTC, rsw0x wrote: On Tuesday, 19 May 2015 at 18:37:31 UTC, bitwise wrote: On Tue, 19 May 2015 14:19:30 -0400, Adam D. Ruppe wrote: On Tuesday, 19 May 2015 at 18:15:06 UTC, bitwise wrote: Is this also true for D? Yes. The GC considers all the unreferenced memory dead at the same time and may clean up the class and its members in any order. Ugh... I was really hoping D had something better up it's sleeve. It actually does, check out RefCounted!T and Unique!T in std.typecons. They're sort of limited right now but undergoing a major revamp in 2.068. By the way: when is 2.068 released?
Re: GC Destruction Order
On Tuesday, 19 May 2015 at 20:02:07 UTC, rsw0x wrote: On Tuesday, 19 May 2015 at 19:45:38 UTC, Namespace wrote: On Tuesday, 19 May 2015 at 19:36:23 UTC, rsw0x wrote: On Tuesday, 19 May 2015 at 18:37:31 UTC, bitwise wrote: On Tue, 19 May 2015 14:19:30 -0400, Adam D. Ruppe wrote: On Tuesday, 19 May 2015 at 18:15:06 UTC, bitwise wrote: Is this also true for D? Yes. The GC considers all the unreferenced memory dead at the same time and may clean up the class and its members in any order. Ugh... I was really hoping D had something better up it's sleeve. It actually does, check out RefCounted!T and Unique!T in std.typecons. They're sort of limited right now but undergoing a major revamp in 2.068. By the way: when is 2.068 released? "After dconf" http://forum.dlang.org/thread/5554d763.1080...@dawg.eu#post-5554D763.1080308:40dawg.eu I thought the new releases would come faster.
Re: Template type deduction and specialization
On Wednesday, 20 May 2015 at 06:31:13 UTC, Mike Parker wrote: I don't understand why this behaves as it does. Given the following two templates: ``` void printVal(T)(T t) { writeln(t); } void printVal(T : T*)(T* t) { writeln(*t); } ``` I find that I actually have to explicitly instantiate the template with a pointer type to get the specialization. ``` void main() { int x = 100; printVal(x); int* px = &x; printVal(px);// prints the address printVal!(int*)(px) // prints 100 } ``` Intuitively, I would expect the specialization to be deduced without explicit instantiation. Assuming this isn't a bug (I've been unable to turn up anything in Bugzilla), could someone in the know explain the rationale behind this? What about: import std.stdio; void printVal(T)(T t) { static if (is(T : U*, U)) printVal(*t); else writeln(t); } void main() { int x = 100; printVal(x); int* px = &x; printVal(px); }
Re: Regex-Fu
On Monday, 25 May 2015 at 11:11:50 UTC, Chris wrote: I'm a bit at a loss here. I cannot get the longest possible match. I tried several versions with eager operators and stuff, but D's regex engine(s) always seem to return the shortest match. Is there something embarrassingly simple I'm missing? void main() { import std.regex : regex, matchFirst; import std.stdio : writeln; auto word = "blablahula"; auto m = matchFirst(word, regex("^([a-z]+)(hula|ula)$")); writeln(m); // prints ["blablahula", "blablah", "ula"] } I want it to return "hula" not "ula". Make the + operator less greedy: matchFirst(word, regex("^([a-z]+?)(hula|ula)$"));
Re: Base type for arrays
import std.stdio; template BaseTypeOf(T) { static if (is(T : U[], U)) alias BaseTypeOf = BaseTypeOf!(U); else alias BaseTypeOf = T; } void foo(T : U[], U)(T arr) if (is(BaseTypeOf!(U) == real)) { } void main() { //real _x; real[2] x; real[2][2] xx; real[2][2][2] xxx; //float[2] yy; //foo(_x); foo(x); foo(xx); foo(xxx); //foo(yy); } should work
Re: Base type for arrays
On Wednesday, 17 June 2015 at 20:58:10 UTC, jmh530 wrote: On Wednesday, 17 June 2015 at 20:33:11 UTC, Namespace wrote: import std.stdio; template BaseTypeOf(T) { static if (is(T : U[], U)) alias BaseTypeOf = BaseTypeOf!(U); else alias BaseTypeOf = T; } void foo(T : U[], U)(T arr) if (is(BaseTypeOf!(U) == real)) { } void main() { //real _x; real[2] x; real[2][2] xx; real[2][2][2] xxx; //float[2] yy; //foo(_x); foo(x); foo(xx); foo(xxx); //foo(yy); } should work Thanks. I'm going to make a lot of use of this. I would say it deserves to be in std.traits. Maybe you can also make use of some of those here (just in case): https://github.com/Dgame/m3/blob/master/source/m3/m3.d
Re: pass by value && elide dtor + post-blit
Dear Ali, thank you for helping! Problem happens when passing by value as in param. Change 'foo' to this: ref S foo(ref S s) { s.val+=1; return s; }
Re: Yes or No Options
Look at my example: import std.stdio; import std.string; import std.conv : to; void main() { while (true) { write("Roll the dice: Enter a number: "); int dieNumber = readln.strip.to!int; if (dieNumber < 4) { writeln("You won!"); } else if ((dieNumber >= 4) && (dieNumber <= 6)) { writeln("I won!"); } else if (dieNumber > 6){ writeln("ERROR: Invalid Value"); } writeln("Do you want to play again? Y/N?"); immutable string yesno = readln.strip; if (yesno.toLower() != "y") break; writeln("Let's go again!"); } } With the while loop you really can "go again" ;)
Re: How disruptive is the GC?
On Wednesday, 29 July 2015 at 09:25:50 UTC, Snape wrote: I'm in the early stages of building a little game with OpenGL (in D) and I just want to know the facts about the GC before I decide to either use it or work around it. Lots of people have said lots of things about it, but some of that information is old, so as of today, what effect does the GC have on the smooth operation of a real-time application? Is it pretty noticeable with any use of the GC or only if you're deallocating large chunks at a time? http://3d.benjamin-thaut.de/?p=20
Re: [Dgame] Sprite loading and setting position in another class
Edit: Basically my code is: //Texman.d// Class TextureManager { //variables void addSprite(string sprite_file, string name) { Surface wiki_img = Surface(sprite_file); Texture wiki_tex = Texture(wiki_img); sprite_list[name] = new Sprite(wiki_tex); sprite_list[name].setPosition(1,1); //tried to remedy by this } } You have to store your Texture. See "My Sprite is only a white Rectangle" on http://dgame-dev.de/index.php?controller=faq I'll change that with v0.7, so that Sprite will manage the Texture by himself.
Re: [Dgame] Sprite loading and setting position in another class
Note that Texture is (in constrast to Sprite) a struct and not a class, so it is a value type. Dgame tries to use as many value types as possible to reduce the amount of garbage.
Re: [Dgame] Sprite loading and setting position in another class
Thank you for answering so quickly. If you don't mind me asking when will v0.7 be out? Not so soon. But maybe I'll release v0.6.5 with this feature at the end of september. For now you need to store your Texture in e.g. a Texture manager.
Re: Chaining struct method invocations
On Monday, 7 September 2015 at 14:12:25 UTC, Bahman Movaqar wrote: I need some help understand the behaviour of my code[1]. Specifically I have trouble with `add` method on line 79. My impression is that since it returns `this`, multiple invocations can be chained like `obj.add(X).add(Y).add(Z)`. However the test on line 92 fails and if I do a `writeln`, only "p1" and "p2" records show up. What am I missing here? Thanks in advance. [1] https://github.com/bahmanm/d-etudes/blob/master/source/e002/models.d You should mark your return type with ref. Structs are value types and therefore you return only a copy currently.
Re: how to access struct member using [] operator?
On Sunday, 25 September 2016 at 04:54:31 UTC, grampus wrote: Dear all For example, I have a struct struct point{int x;int y} point a; Is there an easy way to access x and y by using a["x"] and a["y"] I guess I need to overload [], but can't figure out how. Someone can help? Thank you very much import std.stdio; struct Something { int x, y; float z; auto opIndex()(string member) { switch (member) { case "x": return this.x; case "y": return this.y; case "z": return this.z; default: assert(0); } } } void main(string[] args) { Something s; writeln(s["x"]); writeln(s["z"]); }
Re: Explicit casting of enum -- intentional restriction?
The Code below still works, so I guess it's some problem with the constraint of "exists". import std.stdio; enum Foo { A = "B" } void test(string a) { } void main() { test(Foo.A); Foo.A.test(); }
Re: inferred size for static array initialization
On Tuesday, 18 October 2016 at 10:35:44 UTC, Nordlöw wrote: On Monday, 2 May 2016 at 17:43:56 UTC, Namespace wrote: immutable auto a = [1,2,3].s; Will that have zero run-time overhead compared to: immutable int[3] a = [1,2,3]; ? I'm not quite sure if pragma(inline, true) would result in zero runtime overhead, but without you have 3 lines of assembler more (with gdc). https://godbolt.org/g/JUjP1d https://godbolt.org/g/qaqylp