How to make a function that accepts optional struct but can accept struct literal too

2021-10-15 Thread JN via Digitalmars-d-learn
Is there some nice way of achieving something like this C99 code 
in D?


```c
#include 

typedef struct {
int x, y;
} inputs_t;

void foo(inputs_t* optional_inputs)
{
if (!optional_inputs) {
printf("0 0\n");
} else {
printf("%d %d \n", optional_inputs->x, 
optional_inputs->y);

}
}

int main(void) {
foo(NULL); // prints 0 0
foo(&(inputs_t){.x = 5, .y = 6}); // prints 5 6
}
```

below code won't work. Yes, I know I can just use a local 
variable in this case and pass a pointer, but I'd like to get it 
to work with literal structs too.


```d
import std.stdio;

struct inputs_t {
int x, y;
};

void foo(inputs_t* optional_inputs)
{
if (!optional_inputs) {
writeln("0 0");
} else {
writeln(optional_inputs.x, optional_inputs.y);
}
}

void main() {
foo(null); // prints 0 0
foo(&(inputs_t(5, 6))); // error: inputs_t(5,6) is not an 
lvalue and cannot be modified

}
```



Why sometimes stacktraces are printed and sometimes not?

2021-09-29 Thread JN via Digitalmars-d-learn
What makes the difference on whether a crash stacktrace gets 
printed or not?


Sometimes I get a nice clean stacktrace with line numbers, 
sometimes all I get is "segmentation fault error -1265436346" 
(pseudo example) and I need to run under debugger to get the 
crash location.


Re: Looking to get typeof parseXML return value

2021-09-07 Thread JN via Digitalmars-d-learn

On Tuesday, 7 September 2021 at 04:13:08 UTC, Chris Piker wrote:
Like almost all new users to D I'm tripping over how to save 
and pass around variables since nothing has an understandable 
type anymore and you can't use "auto" for *class member* 
storage types.


I struggle with this often. Templated types that pretty much 
require you to use auto look nice on the paper and in samples, 
but once you try to integrate them into a larger project, it can 
get messy.


Any UML generators for D code?

2021-08-12 Thread JN via Digitalmars-d-learn
I'd like to see the relationships between my D classes in a 
graphical form. Is there any tool that supports that?


Detect if a struct is a 3-float vector

2021-06-23 Thread JN via Digitalmars-d-learn

I'm looking for a way to test a struct for these conditions:

1. has members named x, y and z
2. these members are floating point type

This works, but feels kinda verbose, is there some shorter way? 
Can I somehow avoid the hasMember/getMember calls?


```d
import std.traits;

struct Vector3f
{
float x, y, z;
}

struct Vector2f
{
float x, y;
}

struct Vector3i
{
int x, y, z;
}

bool isVector3fType(T)()
{
static if (__traits(hasMember, T, "x") && __traits(hasMember, 
T, "y") && __traits(hasMember, T, "z"))

{
static if (isFloatingPoint!(typeof(__traits(getMember, T, 
"x")))
&& isFloatingPoint!(typeof(__traits(getMember, T, 
"y")))&& isFloatingPoint!(typeof(__traits(getMember, T, "z" {

return true;
}
}
return false;
}

void main()
{
static assert(isVector3fType!Vector3f);
static assert(!isVector3fType!Vector2f);
static assert(!isVector3fType!Vector3i);
}
```


Arrays of variants, C++ vs D

2021-06-17 Thread JN via Digitalmars-d-learn

This C++ code compiles:
```cpp
#include 
#include 
#include 

int main()
{
using Foo = std::variant;
std::map foos =  {{0, "abc"}, {1, 5}};
}

This code doesn't:

```d
import std.variant;

void main()
{
alias Foo = Algebraic!(int, string);
Foo[int] foos = [
0: "abc",
1: 5
];
}
```
but this does:

```d
import std.variant;

void main()
{
alias Foo = Algebraic!(int, string);
Foo[int] foos = [
0: Foo("abc"),
1: Foo(5)
];
}
```

Why does D need the explicit declarations whereas C++ can infer 
it?


Re: Cast class reference to pointer of another class?

2021-06-10 Thread JN via Digitalmars-d-learn

On Saturday, 29 May 2021 at 22:26:48 UTC, ag0aep6g wrote:
You're writing @system code, so dangerous casts are allowed. 
It's no surprise that the code compiles. If you want to be 
safeguarded against such things, use @safe.


The result is a class object being reinterpreted as a struct 
object. Usually, that's just nonsense. But it might be useful 
for some expert who wants to tinker with the object's internals.


I have to disagree. I don't see a good reason for this behavior 
and it's just one more thing to trip people. I think it'd be 
better if such thing was done explicit, something like:


```d
Bar b = new Bar();
Foo* f2 = cast(Foo*)b.ptr;
```


Re: Cast class reference to pointer of another class?

2021-05-29 Thread JN via Digitalmars-d-learn

fixed formatting:

```d
struct Foo
{
}

class Bar
{
}

void main()
{
Bar b = new Bar();
Foo* f = cast(Foo*)b;
}
```




Cast class reference to pointer of another class?

2021-05-29 Thread JN via Digitalmars-d-learn

```struct Foo
{
}

class Bar
{
}

void main()
{
Bar b = new Bar();
Foo* f = cast(Foo*)b;
}```

this code compiles. Why? What is even the result in "f" in this 
case?


Re: Why is this allowed? Inheritance variable shadowing

2021-05-26 Thread JN via Digitalmars-d-learn

On Tuesday, 13 August 2019 at 04:40:53 UTC, Chris Katko wrote:

You can drop this straight into run.dlang.io:

import std.stdio;

class base{ float x=1;}
class child : base {float x=2;} //shadows base variable!

void main()
{

base []array;
child c = new child;
array ~= c;

writeln(c.x); //=2
writeln(array[0].x); //=1  //uses BASE's interface, yes,
//but why does the CHILD instance one exist at all?
}



Just got bitten by this. When copy pasting code of a bigger 
class, it's easy to miss the redefinition of variable.


Is there any viable usecase for this behavior? I am not buying 
the "C++ does it and it's legal there" argument. There's a reason 
most serious C++ projects use static analysis tools anyway. D 
should be better and protect against dangerous code by default. I 
think a warning in this case would be warranted.




Re: Compiler version "dirty"

2021-05-20 Thread JN via Digitalmars-d-learn

On Tuesday, 9 March 2021 at 01:36:18 UTC, Paul Backus wrote:

On Monday, 8 March 2021 at 22:29:58 UTC, Q. Schroll wrote:

When I enter `dmd --version`, it says:
  DMD64 D Compiler v2.095.1-dirty
What should the "dirty" mean? To me, it seems looks something 
went wrong somewhere.


It means someone made a mistake when preparing the release. 
Probably harmless.


v2.096.1 also reports as -dirty


Struct initialization extra comma - should it compile

2021-04-25 Thread JN via Digitalmars-d-learn

struct Foo
{
int x, y, z;
}

void main()
{
 Foo bar = Foo(1,);
}

This compiles without syntax errors, is this expected?


Re: Foo Foo = new Foo();

2021-02-21 Thread JN via Digitalmars-d-learn
On Sunday, 21 February 2021 at 18:09:29 UTC, FeepingCreature 
wrote:

On Sunday, 21 February 2021 at 18:07:49 UTC, JN wrote:

class Foo
{
}

void main()
{
Foo Foo = new Foo();
}

this kind of code compiles. Is this expected to compile?


Yes, why wouldn't it? main is a different scope than global; 
you can override identifiers from global in main. And "Foo" 
only exists after the declaration, so it doesn't conflict.


I was worried I hit some corner case where it compiles even 
though it shouldn't. Can lead to some confusing code. I guess D 
is smart enough to figure out which is a type and which is a 
variable. C++ gets confused in similar situation.


Re: How add png image to zip file using std.zip?

2021-02-21 Thread JN via Digitalmars-d-learn

On Sunday, 21 February 2021 at 17:17:56 UTC, Marcone wrote:

ZipArchive zip = new ZipArchive();
std.file.write("foo.zip", zip.build());

ArchiveMember f = new ArchiveMember();
f.name = "Wallpaper_001.png";

zip.addMember(f);
std.file.write("foo.zip", zip.build());

File is added with file size 0.
How can I use expandedData for add images files? Or what I use 
for it?


expandedData should hold the contents of the uncompressed file, 
as byte array. So something like:


f.name = "Wallpaper_001.png";
f.expandedData = cast(ubyte[])std.file.read("Wallpaper_001.png");

should work. f.name = "Wallpaper_001.png" only says "create a 
file named Wallpaper_001.png inside the zip". It doesn't say "put 
the Wallpaper_001.png file into the zip".


Foo Foo = new Foo();

2021-02-21 Thread JN via Digitalmars-d-learn

class Foo
{
}

void main()
{
Foo Foo = new Foo();
}

this kind of code compiles. Is this expected to compile?


Any tools to track heap/stack corruptions?

2021-02-03 Thread JN via Digitalmars-d-learn
I am dealing with some nasty issue in my code. Basically random 
unrelated lines of code are crashing with access violations, and 
if I switch from dmd to ldc the crash goes away, or crash comes 
back, or it crashes in a different spot. Seems like I am 
corrupting some memory somewhere (I interact a lot with C 
libraries). Do you know of any tools I could use to try to narrow 
it down?


I've used Application Verifier but so far it didn't point me to 
anything specific.


Re: Refactoring tools

2021-02-03 Thread JN via Digitalmars-d-learn

On Wednesday, 3 February 2021 at 07:20:06 UTC, Imperatorn wrote:

2. If not, why? (Is D still too small?)


D uses templates and a lot of code is generated at compile time. 
It's the same reason C++ doesn't have any advanced refactoring 
tools like e.g. Java does. In Java, it's simple to rename a class 
in all files that use it, and the tools know that X class is 
actually the class from module A and not the X class from module 
B. In D, for all you know you could have someone using 
mixin("My"~"Class"), good luck automatically renaming that.


Re: How to resize an image ? 樂

2020-12-27 Thread JN via Digitalmars-d-learn

On Friday, 25 December 2020 at 20:59:03 UTC, vnr wrote:

Hello 

For a small "script" that generates printable files, I would 
need to change the size of an image (which is loaded into 
memory as an array of bytes) to shrink it to scale if it 
exceeds the A4 page size.


To load the images into memory and generate a PDF, I use the 
"printed" package. It is not very provided but is sufficient 
for my use, I just need the resize option... Is there a 
relatively simple way to do this?


Thank you.


I use the trusty stb_image C libraries (bindings here 
https://code.dlang.org/packages/stb ), specifically the 
stbir_resize_* functions.


Why are default template parameters not permitted on class templates?

2020-11-29 Thread JN via Digitalmars-d-learn

class ValueHolder(T = int)
{
T t;
}

void main()
{
ValueHolder!int v1;
ValueHolder v2; // error
}

onlineapp.d(9): Error: template class onlineapp.ValueHolder(T = 
int) is used as a type without instantiation; to instantiate it 
use ValueHolder!(arguments)


Re: Resolve dub dependency

2020-09-21 Thread JN via Digitalmars-d-learn

On Monday, 21 September 2020 at 19:38:12 UTC, Paul Backus wrote:

On Monday, 21 September 2020 at 19:16:17 UTC, JN wrote:
I am trying to use bindbc-sdl and bindbc-wgpu at the same 
time. The error is:


Unresolvable dependencies to package bindbc-loader:
  bindbc-sdl 0.19.1 depends on bindbc-loader ~>0.3.0
  bindbc-sdl 0.19.1 depends on bindbc-loader ~>0.3.0
  bindbc-wgpu 0.1.0-alpha8 depends on bindbc-loader ~>0.2.1

What is the cleanest way to resolve this? I don't understand 
why can't -sdl and -wgpu use different versions of the loader 
library.


You can't use different versions of a library in the same 
library in the same program because library version isn't 
included in name mangling, so you'll get link errors for having 
multiple definitions of the same symbol.


Ahh ok, that makes sense. I patched bindbc-wgpu locally to use 
loader ~>0.3.0 and it's working now.


Resolve dub dependency

2020-09-21 Thread JN via Digitalmars-d-learn
I am trying to use bindbc-sdl and bindbc-wgpu at the same time. 
The error is:


Unresolvable dependencies to package bindbc-loader:
  bindbc-sdl 0.19.1 depends on bindbc-loader ~>0.3.0
  bindbc-sdl 0.19.1 depends on bindbc-loader ~>0.3.0
  bindbc-wgpu 0.1.0-alpha8 depends on bindbc-loader ~>0.2.1

What is the cleanest way to resolve this? I don't understand why 
can't -sdl and -wgpu use different versions of the loader library.


Autodecode?

2020-08-16 Thread JN via Digitalmars-d-learn
Related to this thread: 
https://forum.dlang.org/post/xtjzhkvszdiwvrmry...@forum.dlang.org


I don't want to hijack it with my newbie questions. What is 
autodecode and why is it such a big deal? From what I've seen 
it's related to handling Unicode characters? And D has the wrong 
defaults?


Re: What would be the advantage of using D to port some games?

2020-07-21 Thread JN via Digitalmars-d-learn

On Wednesday, 24 June 2020 at 18:53:34 UTC, matheus wrote:
Hi, I currently use D for small CLI/Batch apps, before that I 
used to program in C.


Despite of using D I usually program like C but with the 
advantage of: GC, AA, CTFE and a few classes here and there.


As we can see there are a lot of old classic games source 
available like: DOOM, Duke Nukem 3D, Red Alert and most them 
written originally in C/C++.


What I'd like to know from the experts is: What would be the 
advantage of using D to port such games?


Thanks in advance,

Matheus.


The advantage is that you have a fun programming project and a 
challenge. And you don't have to worry about being stuck on the 
code or art side, because all those are ready for you, you just 
have to rewrite it in a different language.


Also, when finished, it makes for a fun blog post about 
challenges of porting C/C++ code to D and which parts were 
simplified using D features.


I was thinking of porting something like Doom to D also (DooD?), 
but never got around to it. I guess one could start with a 
betterC port too.


Re: Send empty assoc array to function

2020-07-10 Thread JN via Digitalmars-d-learn

On Friday, 10 July 2020 at 03:59:37 UTC, Mike Parker wrote:
Meh. You could say the same about foo(int[]), or 
foo(SomeClass). AAs are reference types. Reference type 
instances can be null.


Oh, that actually makes sense. I always thought assoc arrays are 
value types.


Anyway, even if they are reference type, I still would consider 
[] and null different types of values. [] conveys to me that the 
object exists, but is empty. null conveys to me that the object 
exists and cannot be used.


int[int] a = null;
a[5] = 6;

This kind of code just looks weird... yes, I know the " = null " 
part is excessive, but still.


Re: Send empty assoc array to function

2020-07-09 Thread JN via Digitalmars-d-learn
On Thursday, 9 July 2020 at 20:24:11 UTC, Steven Schveighoffer 
wrote:

On 7/9/20 4:04 PM, JN wrote:

On Thursday, 9 July 2020 at 19:53:42 UTC, JN wrote:

void foo(int[int] bar)
{
    // ...
}



Is it possible to send an empty array literal?

foo( [ 0 : 2 ] ) works
foo( [] ) doesn't

int[int] empty;
foo(empty);
works but it's two lines


Hmm, foo(null) seems to work, but is it correct way to do it?



Yes, that is correct.

-Steve


Interesting. Often in D discussion, an argument pops up that the 
language should be protecting against hidden breakages from API 
changes. This would be an example of that happening.


void foo(int[int] bar), someone calls it with a null, suddenly 
the signature changes to void foo(int* bar) and you will be 
sending a null pointer and possibly breaking the app.


Re: Send empty assoc array to function

2020-07-09 Thread JN via Digitalmars-d-learn

On Thursday, 9 July 2020 at 19:53:42 UTC, JN wrote:

void foo(int[int] bar)
{
// ...
}



Is it possible to send an empty array literal?

foo( [ 0 : 2 ] ) works
foo( [] ) doesn't

int[int] empty;
foo(empty);
works but it's two lines


Hmm, foo(null) seems to work, but is it correct way to do it?



Send empty assoc array to function

2020-07-09 Thread JN via Digitalmars-d-learn

void foo(int[int] bar)
{
// ...
}



Is it possible to send an empty array literal?

foo( [ 0 : 2 ] ) works
foo( [] ) doesn't

int[int] empty;
foo(empty);
works but it's two lines


Re: Why is this allowed

2020-07-01 Thread JN via Digitalmars-d-learn

On Wednesday, 1 July 2020 at 15:57:24 UTC, Nathan S. wrote:

On Tuesday, 30 June 2020 at 16:22:57 UTC, JN wrote:
Spent some time debugging because I didn't notice it at first, 
essentially something like this:


int[3] foo = [1, 2, 3];
foo = 5;
writeln(foo);   // 5, 5, 5

Why does such code compile? I don't think this should be 
permitted, because it's easy to make a mistake (when you 
wanted foo[index] but forgot the []). If someone wants to 
assign a value to every element they could do foo[] = 5; 
instead which is explicit.


What's your opinion on using that syntax in the initial 
declaration, like `float[16] foo = 0`?


I don't like it. I'd prefer:

float[16] foo = [ 0 ];

or

float[16] foo = { 0 };

or

float[16] foo(0);


Re: Print only part of a stack trace

2020-07-01 Thread JN via Digitalmars-d-learn

On Wednesday, 1 July 2020 at 18:30:15 UTC, Dennis wrote:
I have a function that checks a global error constant of a C 
library (OpenGL) like this:

```
void assertNoOpenGLErrors() {
if (glGetError() != GL_NO_ERROR) {
assert(0); // stack trace points to here instead of 
caller

}
}


Bit off-topic, but if you can use them, debug contexts offer much 
better OpenGL error-checking experience. 
https://www.khronos.org/opengl/wiki/Debug_Output . Instead of 
checking glGetError() after each call, you can setup a C callback 
that will trigger whenever an error occurs. It also offers some 
vendor-specific performance warnings.


Re: Why is this allowed

2020-06-30 Thread JN via Digitalmars-d-learn
On Tuesday, 30 June 2020 at 16:37:12 UTC, Steven Schveighoffer 
wrote:
That's a feature. I don't think it's going away. The problem of 
accidental assignment is probably not very common.


-Steve


What is the benefit of this feature? I feel like D has quite a 
few of such "features". I like my code to be explicit, even at a 
cost of some extra typing, rather than get bitten by some 
unexpected implicit behavior.


Why is this allowed

2020-06-30 Thread JN via Digitalmars-d-learn
Spent some time debugging because I didn't notice it at first, 
essentially something like this:


int[3] foo = [1, 2, 3];
foo = 5;
writeln(foo);   // 5, 5, 5

Why does such code compile? I don't think this should be 
permitted, because it's easy to make a mistake (when you wanted 
foo[index] but forgot the []). If someone wants to assign a value 
to every element they could do foo[] = 5; instead which is 
explicit.


Use classes as keys in associative array

2020-06-06 Thread JN via Digitalmars-d-learn
Is it possible to use different class instances as keys for 
associative array, but compare them by the contents? I tried to 
override opEquals but it doesn't seem to work. Basically I'd like 
this code to work. I know structs would work but I can't use 
structs for this):


import std.stdio;

class Name
{
string s;

this(string s)
{
this.s = s;
}
}

void main()
{
Name n1 = new Name("John");
Name n2 = new Name("John");

int[Name] ages;
ages[n1] = 50;

assert(ages[n2] == 50);
}


Re: Determining @trusted-status

2020-05-29 Thread JN via Digitalmars-d-learn

On Friday, 29 May 2020 at 00:09:56 UTC, Clarice wrote:
It seems that @safe will be de jure, whether by the current 
state of DIP1028 or otherwise. However, I'm unsure how to 
responsibly determine whether a FFI may be @trusted: the type 
signature and the body. Should I run, for example, a C library 
through valgrind to observe any memory leaks/corruption? Is it 
enough to trust the authors of a library (e.g. SDL and OpenAL) 
where applying @trusted is acceptable?
There's probably no one right answer, but I'd be very thankful 
for some clarity, regardless.


I think most C FFI should be @system, even if it's for popular 
libraries like SDL. Whenever you have API that takes a pointer 
and a size of array, you are risking buffer overflows and similar 
issues. It's very easy to mess up and send array length instead 
of array length * element.sizeof. A @trusted API would only 
accept a slice, which is much safer than raw pointers.


Alternatively you could just use @trusted blocks. Unsafe blocks 
are a common practice in languages like C# or Rust when it comes 
to calling unsafe code. @safe isn't about 100% bulletproof 
safety. @safe is (should be) about not having memory related 
errors outside of @trusted code, minimizing the surface area for 
errors.


Re: How to include my own library in my d program with dub ?

2020-05-14 Thread JN via Digitalmars-d-learn

On Thursday, 14 May 2020 at 12:53:43 UTC, Vinod K Chandran wrote:

Hi all,
I just build a skeleton of a Gui library(win32 based) for my 
own purpose. How do i use this in my d programs with dub ? Now, 
all files are located in a folder called "GuiLib".
Side note : Why i started making a gui library instead of 
learning language ?
Answer : By this way, i can learn the language and i will have 
my own gui library. Otherwise, i would have struggle with 
learning a third party library.


I don't know if it's up-to-date, but this should work:

https://github.com/dlang/dub/wiki/Cookbook#working-with-submodules-or-packages-that-are-not-in-the-registry

I am assuming your GUI library uses dub already for building?


Re: Is there an exception for access violation on LDC/win64?

2020-04-13 Thread JN via Digitalmars-d-learn

On Monday, 13 April 2020 at 10:18:17 UTC, realhet wrote:

Hi,

import std.stdio, std.exception;

[...]


Running under the debugger should show you the location of the 
crash.


Re: Discord bot written in D

2020-04-07 Thread JN via Digitalmars-d-learn

On Monday, 6 April 2020 at 21:23:22 UTC, Quantium wrote:
Are there any libraries to creade a simple discord bot using D? 
And if you know these libraries, could you day me their pros 
and cons?


There are four Discord API related libraries on code.dlang.org. 
Have you checked those?


Re: Vibe.d navigation

2020-03-31 Thread JN via Digitalmars-d-learn

On Tuesday, 31 March 2020 at 18:57:51 UTC, GreatSam4sure wrote:
I am playing with the vibe.d for some days now. One thing I am 
struggling with is move from one page to another using web 
interface. The naming of the functions and proper navigation 
from one page to another is not clear to me.


How to move from one page to another. I will appreciate any 
help.


https://vibed.org/api/vibe.web.web/redirect


Cool name for Dub packages?

2020-03-07 Thread JN via Digitalmars-d-learn

Do we have any cool name for Dub packages?

Rust has 'crates'
Crystal has 'shards'
Python has 'wheels'
Ruby has 'gems'


Re: in not working for arrays is silly, change my view

2020-03-02 Thread JN via Digitalmars-d-learn

On Saturday, 29 February 2020 at 21:56:51 UTC, Ali Çehreli wrote:
Because you mentioned canFind, I think you want the semantics 
to be "is there an element with this value." If so, it would be 
confusing to use the same operator for two different things: 
For associative arrays, it means "is there an element 
accessible with this key."


Does it? I always viewed it as "is this value in list of keys"

Unless 'in' works with arrays to mean "is this index valid", 
then I don't see the benefit. If we had it, I think more people 
would ask "why does 'in' work differently for arrays?"
Are there other languages that support this semantic? 
Checking... Ok, Python has it, highly likely because they don't 
have arrays to begin with.




Well, Python lists are for most purposes equivalent to arrays and 
it hasn't really been confusing for people.




in not working for arrays is silly, change my view

2020-02-29 Thread JN via Digitalmars-d-learn

assert(1 in [1, 2, 3]);

Error: incompatible types for (1) in ([1, 2, 3]): int and int[

Yes, I know about .canFind(), but this is something that trips 
people over and over.


I think it would be better if "in" worked for both assoc arrays 
and normal arrays, or didn't work at all, for added consistency.


Re: Where are the GSOC 2020 ideas?

2020-02-27 Thread JN via Digitalmars-d-learn

On Thursday, 27 February 2020 at 08:16:32 UTC, mark wrote:
On https://wiki.dlang.org I can find GSOC ideas 2011-2019, but 
not 2020.


I know the 2020 one's haven't been accepted, but I'd like to 
know what they are in case I feel like having a go at one as 
part of learning D.


I don't know where is the official list, but this list may have 
been used for thinking up GSOC 2020 projects:


https://github.com/dlang/projects/issues?q=is%3Aissue+is%3Aopen+label%3Agsoc2020


Re: Lambda capture by value

2020-02-24 Thread JN via Digitalmars-d-learn

On Monday, 24 February 2020 at 20:00:20 UTC, Adam D. Ruppe wrote:

On Monday, 24 February 2020 at 19:50:23 UTC, JN wrote:

foreach (i; iota(5))
{
printers[i] = () { write(i); };


I know it looks silly but if you make that:

 printers[i] = (int i) { return () { write(i); }; }(i);

it will do what you want.

This is something that used to be common in javascript, write a 
little function that passes the capture-by-value args and 
returns the lambda you actually want and call it immediately.


That extra layer causes the compiler to create a new copy of 
the capture variables snapshotted in time.


D'oh! I am actually familiar with the pattern from Javascript, 
used it many times, but somehow got it mixed up with something 
else and couldn't make it work.


Thanks.


Lambda capture by value

2020-02-24 Thread JN via Digitalmars-d-learn

import std.range;
import std.stdio;

alias NumberPrinter = void delegate();

NumberPrinter[int] printers;

void main()
{
foreach (i; iota(5))
{
printers[i] = () { write(i); };
}

foreach (i; iota(5))
{
printers[i]();
}
}

This prints 4 4 4 4 4.

How to make it so that it prints 0 1 2 3 4? Is it possible 
without changing the delegate definition to void delegate(int)?


Default value for member class

2020-02-10 Thread JN via Digitalmars-d-learn

class IntValue
{
int x = 5;
}

class Foo
{
IntValue val = new IntValue();
}

void main()
{
Foo f1 = new Foo();
Foo f2 = new Foo();

assert(f1.val == f2.val);
}


Is this expected? Or should each Foo have their own IntValue 
object? They're equal right now, changing one changes the other. 
When exactly is the "new IntValue" happening? On program init, or 
when calling new Foo() for the first time?


Re: total newbie + IDE

2020-02-09 Thread JN via Digitalmars-d-learn

On Sunday, 9 February 2020 at 13:22:56 UTC, solnce wrote:
I really enjoy Pascal having Lazarus. Although it is not 
perfected, it provides very good start for beginners - native 
IDE, RAD, easy to setup and adjust, integrated debugger. All 
that beginners need to have for good start at no time cost. It 
is just language doesn't evolve itself.




There isn't anything comparable to RAD for D. There was one being 
developed in the days od D1 for the DFL UI library - 
http://www.dprogramming.com/entice.php , but it's been long dead.


You can use GLADE to design an interface and then load it in a 
GtkD.


And it is after 13 years of in active development and being 
successor (as it claims so) to C++. ADA has it, Eiffel has it, 
FPC, Gambino many niche and small languages have it, why D, 
which has much wider application,  cannot have it? I think that 
is natural further evolution of any programming language.


I think the text editor/IDE landscape changed a little in last 
decade or so. Editors such as Sublime Text or Ultraedit lost 
their popularity, so did small language specific IDEs such as 
Dev-C++ or Code::blocks. Most of users of these IDEs migrated to 
the big projects like VSCode, Visual Studio or IntelliJ. Also, 
the introduction of language servers allows working on IDE 
support, without being bound to a specific IDE.


Editors/IDEs such as VSCode have a massive ecosystem. Why not 
take advantage of it, rather than start from scratch.


Re: GtkD on Windows: notes + question

2020-02-09 Thread JN via Digitalmars-d-learn

On Sunday, 9 February 2020 at 13:28:59 UTC, mark wrote:
I found a much easier way to get GtkD working on windows than 
that described in 
https://gtkdcoding.com/2019/01/11/-introduction-to-gtkDcoding.html


1. I downloaded and installed the Gtk3 runtime (the link is on 
https://gtkdcoding.com/2019/01/11/-introduction-to-gtkDcoding.html)


2. I downloaded and unzipped the GtkD3 zip to C:\bin\GtkD3

3. Since I'd already installed LDC I just had to run:

dub add-path C:\bin\GtkD3

Now I'm able to build and run on windows using dub. And again, 
I get static builds so have deployable .exes.


However, when I double-click a GtkD .exe it pops up a console 
window, then the GUI window, and the console window stays until 
I close the GUI.


Is there a way to avoid the console Window, at least for 
release builds?


https://forum.dlang.org/thread/xkvdpdsfzevanucrg...@forum.dlang.org


Re: total newbie + IDE

2020-02-07 Thread JN via Digitalmars-d-learn

On Friday, 7 February 2020 at 17:02:18 UTC, solnce wrote:

Hi guys,

I am total newbie and trying to learn a little bit of 
programming for personal purposes (web scrapping, small 
databases for personal use etc.). I've been trying to install 
any of IDE available, but had no success.


[...]


Try Visual Studio Code with Code-D extension.


Re: Empty string vs null

2020-02-03 Thread JN via Digitalmars-d-learn

On Tuesday, 4 February 2020 at 07:44:08 UTC, mark wrote:
Just found this post by Mark Parker that explains: 
https://forum.dlang.org/post/gvveit$10i5$1...@digitalmars.com


I recommend using Nullable from 
https://dlang.org/phobos/std_typecons.html#Nullable if you want 
to explicitly allow a non-value. I think it's cleaner and shows 
the intent better.





Assoc array init

2020-02-03 Thread JN via Digitalmars-d-learn

int[int] a = [5: 7];

void main()
{
}


This fails because apparently [5: 7] is a "non-const expression". 
How? Why?


Yes, I know I can just init in a static this() section, but that 
feels like a bad workaround.


Re: Is there a std.zip.ZipArchive isDir or isFile method?

2020-02-03 Thread JN via Digitalmars-d-learn

On Monday, 3 February 2020 at 13:26:38 UTC, mark wrote:

I'm using std.zip.ZipArchive to read zip files, e.g.:

auto zip = new ZipArchive(read(filename));
// ...
foreach (name, member; zip.directory) {
if (name.endsWith('/')) // skip dirs
continue;
mkdirRecurse(dirName(name));
zip.expand(member);
write(name, member.expandedData());
}

As you can see, I am detecting directories with a crude test.

I really wish there was a method for this: and if there is, 
could you give me the link 'cos I can't see one in the docs?


(BTW The code above is slightly simplified: the real code won't 
unzip if there's an absolute path or .. present and also 
ensures that all members are unzipped into a subdir even if the 
zip has top-level names.)


ArchiveMember has "flags" field, perhaps it stores if it's a 
directory?


If not, fileAttributes will have it but it looks it's OS specific.


Re: bindbc-opengl: Now drawing triangle

2020-01-25 Thread JN via Digitalmars-d-learn

On Saturday, 25 January 2020 at 19:52:25 UTC, Luhrel wrote:

Hello,

I made a simple OpenGL file using bindbc-opengl and glfw 
(https://pastebin.com/ehmcHwxj) based on 
https://github.com/SonarSystems/Modern-OpenGL-Tutorials/blob/master/%5BGETTING%20STARTED%5D/%5B1%5D%20Triangle/main.cpp


The cpp project compiles and runs fine (g++ main.cpp -lGL 
-lglfw -o gl_test && ./gl_test), but my d-translated file not: 
the triangle isn't shown.


Do you have any idea ?


I assume it's working now?

For future, learn to use RenderDoc:

https://renderdoc.org/

it allows you to debug your OpenGL application and see what kind 
of data is sent by your app.


lambda alias import

2020-01-17 Thread JN via Digitalmars-d-learn

stuff.d:

alias doStuff = () {};

main.d:

import stuff;

void main()
{
  doStuff();
}


DMD throws compile error:

 Error 42: Symbol Undefined __D5stuff9__lambda3FNaNbNiNfZv

Is this expected behavior? It tripped me while trying to use 
DerelictVulkan :(


Re: How to parse epub content

2020-01-11 Thread JN via Digitalmars-d-learn

On Saturday, 11 January 2020 at 12:38:38 UTC, Adnan wrote:
How would someone approach parsing epub files in D? Is there 
any libraries to parse XHTML?


XHTML is XML. There are libraries to parse XML, from std.xml in 
the standard library to libraries like dxml in the package 
repository.


Re: How load icon from resource using LoadImage?

2020-01-05 Thread JN via Digitalmars-d-learn

On Sunday, 5 January 2020 at 13:33:35 UTC, Marcone wrote:
I am using this code to load icon from local directory, but I 
want to load icon from resource.res file:


wndclass.hIcon  = LoadImage( NULL, "icon.ico", IMAGE_ICON, 0, 
0, LR_LOADFROMFILE| LR_SHARED | LR_LOADTRANSPARENT);


https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-loadimagea

According to the docs, the first argument is NULL only for 
standalone images, otherwise you have to provide a valid 
HINSTANCE.


By the way, have you managed to add the res file into the binary? 
My understanding is that the res file should be added into the 
exe file by the rc command before it can be used.


Re: Unfold string array

2020-01-05 Thread JN via Digitalmars-d-learn

On Sunday, 5 January 2020 at 08:21:54 UTC, Teo wrote:

All advises are welcome
Thank you!


For some reason I can't get run.dlang.io to shorten a link... 
hmm... I'll use ideone.


https://ideone.com/EjbhIs

It's kind of a naive implementation, there probably is room for 
improvement but should work for start.


Re: Finding position of a value in an array

2019-12-30 Thread JN via Digitalmars-d-learn

On Sunday, 29 December 2019 at 08:31:13 UTC, mipri wrote:


int i = a.countUntil!(v => v == 55);
assert(i == 2);


I also had to ask because I couldn't find it. In other languages 
it's named "index()", "indexOf()" or "find()". D is the only 
language I know which uses the "countUntil" scheme. And even so 
it's not obvious from the name if it's the index of the element 
or number of preceding elements.




Re: Default values in derived class

2019-12-28 Thread JN via Digitalmars-d-learn
On Saturday, 28 December 2019 at 22:12:38 UTC, Johan Engelen 
wrote:
What Mike is saying is that `Base` has one `b` member variable, 
but `Derived` has two (!).


```
writeln(d.b); // false
writeln(d.Base.b); // true (the `b` member inherited from Base)
```

-Johan


That makes sense. I think the compiler/linter should be warning 
against such cases though, because it's easy to make mistakes 
this way.


Default values in derived class

2019-12-28 Thread JN via Digitalmars-d-learn

import std.stdio;

class Base
{
bool b = true;
}

class Derived : Base
{
bool b = false;
}

void main()
{
// 1
Base b = new Derived();
writeln(b.b); // true
// 2
Derived d = new Derived();
writeln(d.b); // false
}


Expected behavior or bug? 1) seems like a bug to me.


Re: What kind of Editor, IDE you are using and which one do you like for D language?

2019-12-23 Thread JN via Digitalmars-d-learn

On Sunday, 22 December 2019 at 17:20:51 UTC, BoQsc wrote:
There are lots of editors/IDE's that support D language: 
https://wiki.dlang.org/Editors


What kind of editor/IDE are you using and which one do you like 
the most?


This list could use some cleaning up. Some of the IDEs haven't 
been maintained in a while, and most of them are some obscure 
editors with basic D syntax highlighting. There should be a link 
o n the main webpage to a list of recommended IDEs, and the 
common ones, the ones people are looking for - IntelliJ D Plugin, 
VisualD, VSCode.


Personally I use code-d. Haven't had much luck with the other D 
VSCode extension.


Re: How use Resedit Dialogs + Dlang?

2019-12-15 Thread JN via Digitalmars-d-learn

On Sunday, 15 December 2019 at 04:00:14 UTC, Marcone wrote:

There's a way to create simple GUI for Dlang using Resedit? How?


Do you know how to do it with C++? It should work the same in D, 
just use the WinApi bindings for calls.


Re: Dmd install to new Windows 10 system can't run app.d

2019-11-21 Thread JN via Digitalmars-d-learn

On Thursday, 21 November 2019 at 09:26:39 UTC, zoujiaqing wrote:

On Thursday, 21 November 2019 at 08:42:39 UTC, Seb wrote:


Note this line:


Running .\myproject.exe
Program exited with code -1073741515


Your compiled program is crashing. Could you run the compiled 
binary manually and obtain a stack trace?


Install msvcr100.dll for x64 the question is solved, thanks!

https://download.microsoft.com/download/3/2/2/3224B87F-CFA0-4E70-BDA3-3DE650EFEBA5/vcredist_x64.exe


I had the same issue a while ago and reported it here 
https://issues.dlang.org/show_bug.cgi?id=20061


Re: Saving and loading large data sets easily and efficiently

2019-10-01 Thread JN via Digitalmars-d-learn

On Monday, 30 September 2019 at 20:10:21 UTC, Brett wrote:
So it much more difficult than POD but would still be a little 
more work to right... hoping that there is something already 
out there than can do this. It should be


I'm afraid there's nothing like this available. Out of 
serialization libraries that I know, msgpack-d and cerealed don't 
store references and instead duplicate the pointed-to content. 
Orange does it, but it doesn't support binary output format, only 
XML, so it isn't a good fit for your data.


Re: Help playing sounds using arsd.simpleaudio

2019-09-29 Thread JN via Digitalmars-d-learn

On Saturday, 28 September 2019 at 03:21:38 UTC, Murilo wrote:
Can anyone just please show me how to play a background 
sound(like those in games) using arsd.simpleaudio? I'd like 
something simple with a code snippet please.


I recommend SoLoud - bindings are available here 
http://code.dlang.org/packages/bindbc-soloud . It's more powerful 
than simpleaudio, supports multiple formats, 3D audio, etc.


Interfaces and templates

2019-09-20 Thread JN via Digitalmars-d-learn

import std.stdio;

interface IWriter
{
void write(U)(U x);
}

class Foo : IWriter
{
void write(U)(U x, int y)
{
writeln(x);
}
}



void main()
{
}

Does this code make sense? If so, why doesn't it throw an error 
about unimplemented write (or incorrectly implemented) method?


Re: Sort Associative Array by Key

2019-08-25 Thread JN via Digitalmars-d-learn

On Sunday, 25 August 2019 at 17:01:23 UTC, a11e99z wrote:

On Sunday, 25 August 2019 at 16:54:33 UTC, Samir wrote:
Is there a way to output the values of an associative array 
based on the lexicographic order of the keys?


For example, if foo = ["VXE":8, "BZP":5, "JLC":2], I'd like to 
output something like:


5
2
8




auto foo = ["VXE":8, "BZP":5, "JLC":2];
foo.byPair.array.sort!"a[0]

I think normal lambdas are better than these string ones:

foo.byPair.array.sort!((a, b) => a[0] < b[0]).map!(a => 
a[1]).writeln;


Re: Can I remove an element from a global associative array from within a class destructor?

2019-08-03 Thread JN via Digitalmars-d-learn

On Friday, 2 August 2019 at 23:13:10 UTC, realhet wrote:
Today I read the documentation about structs, unions and 
classes, but I haven't find any restrictions for the ~this() 
destructors.


Is there some extra rules regarding the GC and what I must not 
do in the destructors?


Class destructors are similar to Java's finalizers in behavior. D 
doesn't give you a guarantee when the class destructor is called 
and it doesn't give you a guarantee if it will be called at all, 
so it doesn't really work for RAII-like resource management. If 
you want RAII-like behavior, either use structs (struct 
destructors are deterministic), or wrap your class inside a 
scoped/refCounted wrapper from std.typecons.


Re: Help me decide D or C

2019-08-01 Thread JN via Digitalmars-d-learn

On Thursday, 1 August 2019 at 09:43:20 UTC, Kagamin wrote:

On Wednesday, 31 July 2019 at 22:30:52 UTC, Alexandre wrote:

1) Improve as a programmer
2) Have fun doing programs

Thats it basically. I am planning to study all "free" time I 
have. I am doing basically this since last year.


Try Basic. It has builtin graphics, seeing you program draw is 
quite fascinating.


What variant of Basic? Visual Basic?

I think https://processing.org/ is the best if you want to "code 
with drawing"


D on ARM laptops?

2019-07-03 Thread JN via Digitalmars-d-learn
Does anyone know if and how well D works on ARM laptops (such as 
Chromebooks and similar)?


For example this one https://www.pine64.org/pinebook/ . Can it 
compile D? Obviously DMD is out because it doesn't have ARM 
builds. Not sure about GDC. How about LDC?


Re: What is iota function full name

2019-06-21 Thread JN via Digitalmars-d-learn

On Friday, 21 June 2019 at 09:18:49 UTC, Jonathan M Davis wrote:
So, iota is
the name of the function, and it doesn't stand for anything. 
It's just the name of the Greek letter that was used for a 
similar function in another language that most programmers 
these days have probably never heard of.


- Jonathan M Davis


I don't even understand why get so much inspiration from C++. Why 
not just name it seq or sequence?


Re: Using python in D

2019-06-07 Thread JN via Digitalmars-d-learn

On Friday, 7 June 2019 at 05:04:30 UTC, rnd wrote:

On Friday, 7 June 2019 at 04:39:14 UTC, rikki cattermole wrote:

On 07/06/2019 3:54 PM, rnd wrote:


How should I 'initialize python' ?


The example is probably a good place to begin.

https://github.com/ariovistus/pyd/blob/master/examples/simple_embedded/hello.d


Thanks for the link. After putting in missing statements, it 
started running but reported:


 exceptions.ImportError: No module named pandas

I believe pyd is working on Python2 while I have pandas 
installed in Python3.


How can I specify Python version 3 in pyd?


https://github.com/ariovistus/pyd

"To use with dub, either specify the relevant subConfiguration 
for your python version, or run source pyd_set_env_vars.sh python> on linux or pyd_set_env_vars.bat  on windows 
to set the relevant environment variables and use the env 
subConfiguration."


Static struct?

2019-04-24 Thread JN via Digitalmars-d-learn
I noticed a construct I haven't seen before in D when reading the 
description for automem - https://github.com/atilaneves/automem


 static struct Point {
int x;
int y;
}


What does "static" do in this case? How does it different to a 
normal struct?


Re: Unexpected behaviour in associative array

2019-04-19 Thread JN via Digitalmars-d-learn

On Friday, 19 April 2019 at 12:37:10 UTC, Arredondo wrote:
Here's a reasonably-sized code fragment that demonstrates the 
issue. I hope the comments along the way are descriptive enough


Hmm. Have you tried using a different compiler or 32/64 bit? I 
had a weird "null out of nowhere" bug going on with associative 
array some time ago - 
https://issues.dlang.org/show_bug.cgi?id=19662


Re: What Does @ Mean?

2019-04-08 Thread JN via Digitalmars-d-learn

On Monday, 8 April 2019 at 14:19:04 UTC, XavierAP wrote:
The only other example of language using @, in an almost but 
not quite completely different way, is C#. It's also a prefix 
that allows you to define names that would collide with 
reserved words, for example string @class = "menu"; Of course 
you should never do this unless you absolutely need for interop.


Java uses @ for annotations too. Pascal uses @ for "address of", 
like & in D.


Re: Where is GDC being developed?

2019-03-21 Thread JN via Digitalmars-d-learn

On Thursday, 21 March 2019 at 08:19:56 UTC, Per Nordlöw wrote:

At

https://github.com/D-Programming-GDC/GDC/commits/master

there's the heading

"This repository has been archived by the owner. It is now 
read-only."


Where will the development of GDC continue?


I am not exactly sure, but if GDC got merged into GCC, doesn't 
that mean that any new development will be done on the GCC 
repository?


Re: Setting the GtkD Include Path in dexed?

2019-03-12 Thread JN via Digitalmars-d-learn

On Tuesday, 12 March 2019 at 17:39:06 UTC, Ron Tarrant wrote:

Another way of asking this, I suppose, would be:

How do I pass command line arguments to dmd from within dexed?


How about Project -> Project editor -> Categories -> Other -> 
dmdOtherOptions ?


Struct destructor

2019-03-02 Thread JN via Digitalmars-d-learn

Compare this D code:

import std.stdio;

struct Foo
{
~this()
{
writeln("Destroying foo");
}
}

void main()
{
Foo[string] foos;

foos["bar"] = Foo();
writeln("Preparing to destroy");
foos.remove("bar");
writeln("Ending program");
}

and equivalent C++ code:

#include 
#include 
#include 

using namespace std;

struct Foo
{
~Foo()
{
cout << "Destroying foo" << endl;
}
};

int main()
{
map foos;

foos["bar"] = Foo();
cout << "Preparing to destroy" << endl;
foos.erase("bar");
cout << "Ending program" << endl;
}


C++ results in:

Destroying foo
Preparing to destroy
Destroying foo
Ending program

D results in:

Preparing to destroy
Ending program
Destroying foo

Is this proper behavior? I'd imagine that when doing 
foos.remove("bar"), Foo goes out of scope and should be 
immediately cleaned up rather than at the end of the scope? Or am 
I misunderstanding how should RAII work?


Re: Using arsd.simpledisplay module

2019-02-25 Thread JN via Digitalmars-d-learn

On Monday, 25 February 2019 at 23:35:24 UTC, Murilo wrote:
I need help with the arsd.simpledisplay module. Is there anyone 
there who knows about it? I have doubts concerning 
SimpleWindow.eventLoop().


I'm pretty sure Adam D. Ruppe knows about it since he's the 
author :)


What exactly is the question, what doubts are you having?


Re: How to setup dub to use x86 and x64 dll's when appropriate?

2019-02-25 Thread JN via Digitalmars-d-learn

On Tuesday, 26 February 2019 at 04:20:27 UTC, Michelle Long wrote:
On Tuesday, 26 February 2019 at 04:17:04 UTC, Michelle Long 
wrote:
e.g., using sdl for different versions and have it 
automatically switch.


What would be nice is if one could stick all the files for x86 
in one dir and x64 in the others and they will be used 
depending on the build(and copied)


Ideally one can do it for debug and release versions too.


It seems also that dub is shit for swapping between different 
archs... I added the -m64 flag and then get build errors for 
lib format errors, compiles fine for x86...


Why add -m64 rather than --arch=x86_64?

Also: 
https://github.com/dlang/dub/wiki/Cookbook#creating-windows-package-that-has-32-and-64-bit-dlls


Re: How to call other variadic function with the same arguments?

2019-02-24 Thread JN via Digitalmars-d-learn

On Sunday, 24 February 2019 at 13:09:15 UTC, Victor Porton wrote:

Let f be a variadic function:

Result f(...);

How to implement variadic function g which calls f with the 
same arguments as one it receives?


Result g(...) {
  // ...
}


void f(A...)(A a)
{
foreach(t; a)
writeln(t);
}

void g(A...)(A a)
{
f(a);
}

g(1, 2, 3);


Re: Windows Defender won't let me install DMD

2019-02-19 Thread JN via Digitalmars-d-learn

On Monday, 18 February 2019 at 16:32:26 UTC, belkin wrote:
Additional question as a beginner. What do I need to install to 
get started.
Obviously I need a compiler (which one is best ). But I also 
want an IDE and so far it seems Visual D would be a best choice.


Ideas?


Visual D works well, as does Visual Studio Code with code-d 
plugin.


Re: Why -I flag does not work?

2019-02-09 Thread JN via Digitalmars-d-learn

On Saturday, 9 February 2019 at 08:15:36 UTC, Victor Porton wrote:

Why does -I flag in DFLAGS does not work? (Ubuntu Linux)


I'm no expert on dub, but it's possible that it's overriding the 
import path anyway. One of the main points of dub is that you 
shouldn't have to handle the import paths yourself.


I think what could work is adding a librdf in dub.json 
dependencies section, and then using "dub add-local" command to 
point to the library. Something like:


dub add-local /usr/local/include/d/librdf ~master

and then in dependencies section:

"dependencies": {
"librdf": "~master"
}


Re: Tricky DMD bug, but I have no idea how to report

2019-02-08 Thread JN via Digitalmars-d-learn

On Friday, 8 February 2019 at 23:30:44 UTC, H. S. Teoh wrote:
On Fri, Feb 08, 2019 at 10:45:39PM +, JN via 
Digitalmars-d-learn wrote: [...]
Anyway, I reduced the code further manually. It's very hard to 
reduce it any further. For example, removing the assignments 
in fromEulerAngles static method hides the bug.  Likewise, 
replacing writeln with assert makes it work properly too.


Pity we couldn't get rid of std.stdio.  It's a pretty big piece 
of code, and there are plenty of places where it may go wrong 
inside, even though we generally expect that the bug lies 
elsewhere.  Oh well.  Hopefully somebody else can dig into this 
and figure out what's going on.


Hmm. I just glanced over the std.stdio code... it appears that 
somebody has added @trusted all over the place, probably just 
to get it to compile with @safe.  That's kinda scary... 
somebody needs to vet this code carefully to make sure nothing 
fishy's going on in there!



T


I can replace it with core.stdc.stdio if it's any better. Looks 
like any attempt to do a check for "x is null" hides the bug. I 
tried assert(), also tried if (x is null) throw new Exception(...)


Re: Tricky DMD bug, but I have no idea how to report

2019-02-08 Thread JN via Digitalmars-d-learn

On Friday, 8 February 2019 at 22:11:31 UTC, H. S. Teoh wrote:
Pity I still can't reproduce the problem locally. Otherwise I 
would reduce it even more -- e.g., eliminate std.stdio 
dependency and have the program fail on assert(obj != null), 
and a bunch of other things to make it easier for compiler devs 
to analyze -- and perhaps look at the generated assembly to see 
what went wrong.  If you have the time (and patience) to do 
that, it would greatly increase the chances of this being fixed 
in a timely way, since it would narrow down the bug even more 
so that it's easier to find in the dmd source code.



T


It seems to be a Windows 64-bit only thing. Anyway, I reduced the 
code further manually. It's very hard to reduce it any further. 
For example, removing the assignments in fromEulerAngles static 
method hides the bug. Likewise, replacing writeln with assert 
makes it work properly too.


Re: Tricky DMD bug, but I have no idea how to report

2019-02-08 Thread JN via Digitalmars-d-learn

On Friday, 8 February 2019 at 21:35:34 UTC, H. S. Teoh wrote:
On Fri, Feb 08, 2019 at 09:23:40PM +, JN via 
Digitalmars-d-learn wrote: [...]
I managed to greatly reduce the source code. I have filed a 
bug with the reduced testcase 
https://issues.dlang.org/show_bug.cgi?id=19662 .


Haha, you were right!  It's a compiler bug, another one of 
those nasty -O -inline bugs.  Probably a backend codegen bug.  
Ran into one of those before; was pretty nasty.  Fortunately it 
got fixed soon(ish) after I made noise about it in the forum. 
:-P



T


Luckily it's not a blocker for me, because it doesn't trigger on 
debug builds, and for release builds I can always use LDC, but 
still it's bugging me (pun intended).


Re: Tricky DMD bug, but I have no idea how to report

2019-02-08 Thread JN via Digitalmars-d-learn
On Friday, 8 February 2019 at 09:30:12 UTC, Vladimir Panteleev 
wrote:

On Friday, 8 February 2019 at 09:28:48 UTC, JN wrote:
I will try. However, one last thing - in the example test 
scripts, it runs first with one compiler setting (or D 
version) and the second time with the other compiler setting 
(or D version). But it looks like the exit code of the first 
run is ignored anyway, so why run it?


With "set -e", the shell interpreter will exit the script with 
any command that fails (returns with non-zero status), unless 
it's in an "if" condition or such. I'll update the article to 
clarify it.


I see. Dustmite helped. I had to convert it to windows batch, so 
my testscript ended up to be:


dmd -O -inline -release -boundscheck=on -i app.d -m64
@IF %ERRORLEVEL% EQU 0 (ECHO No error found) ELSE (EXIT /B 1)
@app | FINDSTR /C:"Object"
@IF %ERRORLEVEL% EQU 0 (ECHO No error found) ELSE (EXIT /B 1)
dmd -O -inline -release -boundscheck=off -i app.d -m64
@IF %ERRORLEVEL% EQU 0 (ECHO No error found) ELSE (EXIT /B 1)
@app | FINDSTR /C:"null"
@IF %ERRORLEVEL% EQU 0 (EXIT /B 0) ELSE (EXIT /B 1)

I managed to greatly reduce the source code. I have filed a bug 
with the reduced testcase 
https://issues.dlang.org/show_bug.cgi?id=19662 .


Re: Tricky DMD bug, but I have no idea how to report

2019-02-08 Thread JN via Digitalmars-d-learn
On Friday, 8 February 2019 at 07:30:41 UTC, Vladimir Panteleev 
wrote:

On Thursday, 7 February 2019 at 22:16:19 UTC, JN wrote:

Does it also work for dub projects?


It will work if you can put all the relevant D code in one 
directory, which is harder for Dub, as it likes to pull 
dependencies from all over the place. When "dub dustmite" is 
insufficient (as in this case), the safest way to proceed would 
be to build with dub in verbose mode, take note of the compiler 
command lines it's using, then put them in a shell script and 
all mentioned D files in one directory, then pass that to 
Dustmite.


I will try. However, one last thing - in the example test 
scripts, it runs first with one compiler setting (or D version) 
and the second time with the other compiler setting (or D 
version). But it looks like the exit code of the first run is 
ignored anyway, so why run it?


Re: Tricky DMD bug, but I have no idea how to report

2019-02-07 Thread JN via Digitalmars-d-learn
On Thursday, 7 February 2019 at 03:50:32 UTC, Vladimir Panteleev 
wrote:

On Monday, 17 December 2018 at 21:59:59 UTC, JN wrote:
while working on my game engine project, I encountered a DMD 
codegen bug. It occurs only when compiling in release mode, 
debug works.


Old thread, but FWIW, such bugs can be easily and precisely 
reduced with DustMite. In your test script, just compile with 
and without the compiler option which causes the bug to 
manifest, and check that one works and the other doesn't.


I put together a short article on the DustMite wiki describing 
how to do this:

https://github.com/CyberShadow/DustMite/wiki/Reducing-a-bug-with-a-specific-compiler-option


Does it also work for dub projects?

Anyway, I managed to reduce the source code greatly manually:

https://github.com/helikopterodaktyl/repro_d_release/

unfortunately I can't get rid of the dlib dependency. When built 
with debug, test outputs [0: Object], with release it outputs [0: 
null].


commenting this line out:
f.rotation = Quaternionf.fromEulerAngles(Vector3f(0.0f, 0.0f, 
0.0f));

or changing it to:
f.rotation = Quaternionf.identity();

is enough to make release output [0: Object] as well. I guess 
dlib is doing something dodgy with memory layout, but I can't see 
anything suspicious :(


Re: Tricky DMD bug, but I have no idea how to report

2019-02-06 Thread JN via Digitalmars-d-learn

On Wednesday, 6 February 2019 at 22:22:26 UTC, H. S. Teoh wrote:
Of course, I've no clue whether this is the cause of your 
problems -- it's just one of many possibilities.  Pointer bugs 
are nasty things to debug, regardless of whether or not they've 
been abstracted away in nicer clothing.  I still remember 
pointer bugs that took literally months just to get a clue on, 
because it was nigh impossible to track down where they 
happened -- the symptoms are too far removed from the cause.  
You pretty much have to take a wild guess and get lucky.


They are just as bad as race condition bugs. (Once, a race 
condition bug took me almost half a year to fix, because it 
only showed up in the customer's live environment and we could 
never reproduce it locally. We knew there was a race somewhere, 
but it was impossible to locate it. Eventually, by pure 
accident, an unrelated code change subtly altered the timings 
of certain things that made the bug more likely to manifest 
under certain conditions -- and only then were we finally able 
to reliably reproduce the problem and track down its root 
cause.)



T


I am not sure if it's a pointer bug. What worries me is that it 
breaks at the start of the program, but uncommenting code at the 
end of the program influences it. Unless there's some crazy 
reordering going on, this shouldn't normally have an effect. I 
still believe the bug is on the compiler side, but it's a bit of 
code in my case, and if I try to minimize the case, the issue 
disappears. Oh well.


Re: Tricky DMD bug, but I have no idea how to report

2019-02-06 Thread JN via Digitalmars-d-learn

On Tuesday, 18 December 2018 at 22:56:19 UTC, H. S. Teoh wrote:
Since no explicit slicing was done, there was no compiler error 
/ warning of any sort, and it wasn't obvious from the code what 
had happened. By the time doSomething() was called, it was 
already long past the source of the problem in buggyCode(), and 
it was almost impossible to trace the problem back to its 
source.


Theoretically, -dip25 and -dip1000 are supposed to prevent this 
sort of problem, but I don't know how fully-implemented they 
are, whether they would catch the specific instance in your 
code, or whether your code even compiles with these options.



T


No luck. Actually, I avoid in my code pointers in general, I 
write my code very "Java-like" with objects everywhere etc. I 
gave up on the issue actually, perhaps I am encountering this bug 
https://issues.dlang.org/show_bug.cgi?id=16511 in my own code. 
Anyway, 32-bit and 64-bit debug work, so does LDC. That's good 
enough for me.


Re: crashing with no stack trace, why?

2019-02-01 Thread JN via Digitalmars-d-learn

On Thursday, 31 January 2019 at 11:09:56 UTC, DanielG wrote:
However it was simply crashing with an exit code (-1073740771 / 
‭0xC41D‬), and I was having a heck of a time trying to 
debug on Windows. (Shoutout to the revamped WinDbg Preview, 
couldn't get anything else to work!)


For Windows, you can try VisualD and VSCode with C++ debugger. I 
had good experience using those, at least to determine which line 
crashes in my code when stacktrace is not provided.




Re: How to disable/hide constructor when using factory method?

2019-01-24 Thread JN via Digitalmars-d-learn

On Thursday, 24 January 2019 at 12:52:47 UTC, Arafel wrote:
You are declaring the constructor, but not defining it, i.e. 
you're telling the compiler that it's in some other compilation 
unit.


The compiler won't complain, but the linker will.

If you replace:


[...]


with:


[...]


it should work.

A.

On 1/24/19 1:48 PM, JN wrote:

[...]


Doh. Of course. I feel so dumb. I just had it at @disable 
this();, then replaced @disable with private without thinking to 
add {}


Re: How to disable/hide constructor when using factory method?

2019-01-24 Thread JN via Digitalmars-d-learn

On Wednesday, 23 January 2019 at 19:41:44 UTC, Alex wrote:

On Wednesday, 23 January 2019 at 19:26:37 UTC, JN wrote:

class Foo
{
static Foo makeFoo()
{
Foo f = new Foo();
return f;
}
}

void main() {
Foo f = Foo.makeFoo();
}

For a code like this. I'd like all users of the class to be 
forced to create instances using the static method makeFoo. I 
want to disallow "new Foo()". But I don't know if it's 
possible to disable the constructor, while still making it 
available in the makeFoo static method.


@disable this doesn't work, private this(); doesn't work 
either.


private should work, if the class and the main are in different 
modules, no?


I expected that too, but it doesn't even work in the same module.

class Foo
{
private this();

static Foo makeFoo()
{
Foo f = new Foo();
return f;
}
}

void main() {
}

fails with:

onlineapp.o:onlineapp.d:_D9onlineapp3Foo7__ClassZ: error: 
undefined reference to '_D9onlineapp3Foo6__ctorMFZCQzQr'
onlineapp.d:7: error: undefined reference to 
'_D9onlineapp3Foo6__ctorMFZCQzQr'

collect2: error: ld returned 1 exit status
Error: linker exited with status 1

I don't understand why is this a linker problem. My understanding 
is that for some reason static methods don't have access to the 
private constructor (they're not considered same module?). But 
even though, it should error with something like "Foo.makeFoo() 
cannot access private Foo.this()" rather than fail at linking.


How to disable/hide constructor when using factory method?

2019-01-23 Thread JN via Digitalmars-d-learn

class Foo
{
static Foo makeFoo()
{
Foo f = new Foo();
return f;
}
}

void main() {
Foo f = Foo.makeFoo();
}

For a code like this. I'd like all users of the class to be 
forced to create instances using the static method makeFoo. I 
want to disallow "new Foo()". But I don't know if it's possible 
to disable the constructor, while still making it available in 
the makeFoo static method.


@disable this doesn't work, private this(); doesn't work either.


Re: Debugging a dub build

2019-01-21 Thread JN via Digitalmars-d-learn

On Monday, 21 January 2019 at 11:16:31 UTC, Per Nordlöw wrote:

Correction should be

dub build --build=unittest

or

dub build --build=debug

followed by

gdb PATH_TO_APP_BINARY


Does using an IDE count? Some D IDEs should be able to assist in 
debugging.


Re: Is there a nice syntax to achieve optional named parameters?

2019-01-16 Thread JN via Digitalmars-d-learn

On Tuesday, 15 January 2019 at 11:14:54 UTC, John Burton wrote:


auto window = Window();
window.title = "My Window";
window.width = 1000;
window.create();



You can slightly modify it to the way APIs like DirectX or Vulkan 
do it.


auto windowinfo = WindowInfo();
windowinfo.title = "My Window";
windowinfo.width = 1000;

auto window = Window(windowinfo);


Re: Reversing a string

2019-01-11 Thread JN via Digitalmars-d-learn

On Friday, 11 January 2019 at 11:15:05 UTC, Mike James wrote:

Check out the origin :-)

https://forum.dlang.org/thread/hl8345$2b1q$1...@digitalmars.com?page=1



I guess something like iterReverse, reverseIter, backIterator 
would be too simple...




Re: Reversing a string

2019-01-11 Thread JN via Digitalmars-d-learn
On Friday, 11 January 2019 at 08:15:01 UTC, rikki cattermole 
wrote:
Note the immutable, it means you cannot modify individual 
values. Which is a problem for reverse because it modifies in 
place.




The error message is kind of unfortunate. This is a simple 
usecase and the error message is undecipherable already. It'd be 
cool if the compiler could try to strip immutability, and if the 
type matches then, throw an error something like "Cannot pass 
immutable char[] to reverse, did you mean char[]?".


Re: Tricky DMD bug, but I have no idea how to report

2018-12-18 Thread JN via Digitalmars-d-learn

On Monday, 17 December 2018 at 22:22:05 UTC, H. S. Teoh wrote:
A less likely possibility might be an optimizer bug -- do you 
get different results if you add / remove '-O' (and/or 
'-inline') from your dmd command-line?  If some combination of 
-O and -inline (or their removal thereof) "fixes" the problem, 
it could be an optimizer bug. But those are rare, and usually 
only show up when you use an obscure D feature combined with 
another obscure corner case, in a way that people haven't 
thought of.  My bet is still on a pointer bug somewhere in your 
code.




I played around with dmd commandline. It works with -O. Works 
with -O -inline. As soon as I add -boundscheck=off it breaks.


As I understand it, out of bounds access is UB. Which would fit 
my problems because they look like UB. But if I run without 
boundscheck=off, shouldn't I get a RangeError somewhere?


Tricky DMD bug, but I have no idea how to report

2018-12-17 Thread JN via Digitalmars-d-learn

Hey guys,

while working on my game engine project, I encountered a DMD 
codegen bug. It occurs only when compiling in release mode, debug 
works. Unfortunately I am unable to minimize the code, since it's 
quite a bit of code, and changing the code changes the bug 
occurrence. Basically my faulty piece of code looks like this


class Texture2D {}

auto a = new Texture2D();
auto b = new Texture2D();
auto c = new Texture2D();
Texture2D[int] TextureBindings;
writeln(a, b, c);
textureBindings[0] = a;
textureBindings[1] = b;
textureBindings[2] = c;
writeln(textureBindings);

and the output is:

Texture2DTexture2DTexture2D
[0:null, 2:null, 1:null]

I'd expect it to output:

Texture2DTexture2DTexture2D
[0:Texture2D, 2:Texture2D, 1:Texture2D]

depending on what I change around this code, for example changing 
it to


writeln(a, " ", b, " ", c);

results in output of:

Texture2D Texture2D Texture2D
[0:Texture2D, 2:null, 1:null]

It feels completely random. Removing, adding calls completely 
unrelated to these changes the result. My guess is that the 
compiler somehow reorders the calls incorrectly, changing the 
semantics. Trick is, LDC works correctly and produces the 
expected result, both when compiling in debug and release mode.


I tried to play around with assoc arrays on run.dlang.io but 
could never reproduce it. It has to do something with the way my 
code works and possibly interacts with other C libraries. Does 
anyone have an idea what could it be and how to reproduce it so 
that it can be reported and fixed? For now, I'll just switch to 
LDC, but I feel bad leaving a possible bug intact and unreported.


This is with DMD32 D Compiler v2.083.1, on Windows, x86_64 
compilation target.


Re: Native PDB Error

2018-12-15 Thread JN via Digitalmars-d-learn

On Saturday, 15 December 2018 at 20:54:03 UTC, JN wrote:


Bump. Encountering the same issue. Just reinstalled Windows and 
having the same error on

DMD32 D Compiler v2.083.1 .


OK, fixed it. Since it's the first hit from Google, here's a 
solution:


https://www.reddit.com/r/roguelikedev/comments/8s5x5n/roguelikedev_does_the_complete_roguelike_tutorial/e11p66q/

"What I did to fix it was install Visual Studio 2017 Community, 
then go into the VS installer and add both the "Desktop 
Development With C++" and "Game Development With C++" workloads. 
It is not enough to just install Visual Studio, and the C++ Build 
Tools do not have the sufficient .lib files to build the game."


The Game development pack is probably unnecessary, since it's 
DirectX and stuff, but I installed it just to be safe.


  1   2   >