Implementation Details

2024-05-27 Thread Ruby The Roobster via Digitalmars-d-learn
As of late, I have taken up an interest in learning about how the 
D language is implemented at a compiler level, specifically the 
GC implementation.  Unfortunately, the source code is poorly 
documented, and is too large to simply read all of it in a 
reasonable amount of time.  If anyone here can help me, or at 
least point me to relevant resources, I would be very grateful.


Re: dub Fetches Wrong Package Version

2023-07-30 Thread Ruby The Roobster via Digitalmars-d-learn

On Saturday, 29 July 2023 at 17:11:50 UTC, Dennis wrote:
On Saturday, 29 July 2023 at 16:47:34 UTC, Ruby The Roobster 
wrote:
Dub refuses to fetch the ~master branch of a package, even 
when dub.json tells it to.  Is there any workaround to this?


Delete dub.selections.json, which locks in dependency versions 
until you explicitly upgrade.


Thank you.  Also, editing dub.selections.json to have the right 
version also works.


dub Fetches Wrong Package Version

2023-07-29 Thread Ruby The Roobster via Digitalmars-d-learn
Dub refuses to fetch the ~master branch of a package, even when 
dub.json tells it to.  Is there any workaround to this?


Re: Thread/Task cancellation

2023-07-28 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 28 July 2023 at 18:52:59 UTC, Ruby The Roobster wrote:

On Friday, 28 July 2023 at 18:17:18 UTC, Gjiergji wrote:
I am coming from a C# background. I understood that there is 
no async/await equivalent in D (except fibers which are not 
suitable for multi threading), but if I am using threads, what 
is the D idiom to implement cancellation?


Usually a long running thread looks like this (in C#):

```csharp
try
{
   while (!cancellationToken.IsCancellationRequested)
   {
  //do some work
  await SomethingAsync(cancellationToken);
  //do some other work
  await Task.Delay(TimeSpan.FromSeconds(5000), 
cancellationToken);

   }
}
catch (OperationCancelledException e) when (e.Token == 
cancellationToken)

{
   //someone cancelled any of the await calls above, we can 
swallow it or log it

}

```

The question is how do I pass a `cancellationToken` to the 
calls from the loop in order to terminate them before 
completion. For example, I learnt about `Thread.sleep` in 
phobos, but I cannot pass a cancellation token in order to 
cancel it before the intended sleep duration.


Thx.


[SNIP]


You could use a thread to check if the token has been sent via 
message passing, and when it is sent, throw an exception, like 
this:






This does however, terminate with signal 11 upon sending the 
terminate signal, and I'm not sure why.


Ignore my above code, Here is something that should work:

```d
import std.concurrency;

void foo()
{
try
{
auto tid = spawnLinked();
ownerTid.send(tid);
// do stuff
// ...

auto c  = receiveTimeout(0.msecs, (ubyte a) {}); // Since 
bar is linked, this will throw an exception when bar terminates

}
catch(Exception e)
{
// Do whatever with the exception message, but it 
terminates the function execution.

}
}

void bar()
{
bool terminate = false;
terminate = receiveOnly!bool();
}

void main()
{
spawn();
Tid tid = receiveOnly!Tid();
// ...
if(needsToTerminateFooForSomeReason)
tid.send(true);
// ...
}
```

This is the only way I could think of doing this, since 
exceptions don't travel up the threads.


Re: Thread/Task cancellation

2023-07-28 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 28 July 2023 at 18:17:18 UTC, Gjiergji wrote:
I am coming from a C# background. I understood that there is no 
async/await equivalent in D (except fibers which are not 
suitable for multi threading), but if I am using threads, what 
is the D idiom to implement cancellation?


Usually a long running thread looks like this (in C#):

```csharp
try
{
   while (!cancellationToken.IsCancellationRequested)
   {
  //do some work
  await SomethingAsync(cancellationToken);
  //do some other work
  await Task.Delay(TimeSpan.FromSeconds(5000), 
cancellationToken);

   }
}
catch (OperationCancelledException e) when (e.Token == 
cancellationToken)

{
   //someone cancelled any of the await calls above, we can 
swallow it or log it

}

```

The question is how do I pass a `cancellationToken` to the 
calls from the loop in order to terminate them before 
completion. For example, I learnt about `Thread.sleep` in 
phobos, but I cannot pass a cancellation token in order to 
cancel it before the intended sleep duration.


Thx.



You could use a thread to check if the token has been sent via 
message passing, and when it is sent, throw an exception, like 
this:


```d
import std.concurrency;

Tid tid;

void foo()
{
try
{
tid = spawn();
// do stuff
}
catch(Exception e)
{
// ...
}
}

void bar()
{
bool terminate = false;
terminate = receiveOnly!bool();
if(terminate)
{
throw new Exception("Thread terminated");
}
}

void main()
{
spawn();
// ...
if(needsToTerminateFooForSomeReason)
tid.send(true);
// ...
}
```

This does however, terminate with signal 11 upon sending the 
terminate signal, and I'm not sure why.




Re: Perspective Projection

2023-07-28 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 28 July 2023 at 16:20:26 UTC, Dennis wrote:
On Friday, 28 July 2023 at 16:08:43 UTC, Ruby The Roobster 
wrote:
Everything displays fine (with orthographic projection, of 
course) if you leave the projection as the identity matrix, 
but setting it as I have done results in a blank screen.


How do you pass the matrix to OpenGL? Be careful that gl3n uses 
row major matrices, but OpenGL uses column major matrices, so 
you either need to transpose it yourself, or pass `true` to the 
`transpose` argument in `glUniformMatrix4fv`.


Thank you very much!  Changing GL_FALSE to GL_TRUE in all of the 
`glUniformMatrix4fv` calls resulted in something being displayed, 
though very incorrectly.  As it turns out, there is an 
inconsistency in the gl3n API, that you write a rotation matrix 
in radians, but you must write the FOV in degrees.  After that, 
it worked as it was supposed to.


Perspective Projection

2023-07-28 Thread Ruby The Roobster via Digitalmars-d-learn
I again am having issues with OpenGL, this time with the 
projection matrix.  Using gl3n, I have the following code:


```d
// model matrix
mat4 trans = mat4(0f);
trans.make_identity();
trans = trans.rotatex(radians(-55));

// view matrix:
mat4 view = mat4(0f);
view.make_identity();
view = view.translation(0f ,0f, -3f);

// projection matrix
mat4 projection;
projection.make_identity();
projection = projection.perspective(800f, 600f, radians(45f), 
.1f, 100f);

```

I am binding all of these matrices to the correct locations, and 
this seems to be the gl3n equivalent to what is given in the 
OpenGL tutorial:


```c
// create transformations
glm::mat4 model = glm::mat4(1.0f); // make sure 
to initialize matrix to identity matrix first

glm::mat4 view  = glm::mat4(1.0f);
glm::mat4 projection= glm::mat4(1.0f);
model = glm::rotate(model, glm::radians(-55.0f), 
glm::vec3(1.0f, 0.0f, 0.0f));
view  = glm::translate(view, glm::vec3(0.0f, 0.0f, 
-3.0f));
projection = glm::perspective(glm::radians(45.0f), 800f / 
600f, 0.1f, 100.0f);

```

Everything displays fine (with orthographic projection, of 
course) if you leave the projection as the identity matrix, but 
setting it as I have done results in a blank screen.  I assume it 
has to do with the values of


`(projection * view * trans * vec4(vertex, 1)).w` not being 1.  
Should I just use a different library, and if so, how to use it 
to generate a perspective matrix?


Re: Loading Textures in OpenGL

2023-07-23 Thread Ruby The Roobster via Digitalmars-d-learn

On Sunday, 23 July 2023 at 17:45:53 UTC, Ferhat Kurtulmuş wrote:
On Sunday, 23 July 2023 at 17:35:03 UTC, Ruby The Roobster 
[SNIP]


Thank you.  I'm still trying to work out how it works.  It 
seems as if the creator tried the same thing that I did, and 
then commented it out.  Perhaps for the same reason?


It is me who did it. I was getting some weirdly distorted 
images. And you see my final solution. I am writing on my mobil 
so cannot help you further.


Ah.  Anyhow, I fixed it.  I had to use .scanline to fill the 
Image data, but in the end it worked.  Thank you very much.


Re: Loading Textures in OpenGL

2023-07-23 Thread Ruby The Roobster via Digitalmars-d-learn

On Sunday, 23 July 2023 at 17:35:03 UTC, Ruby The Roobster wrote:

On Sunday, 23 July 2023 at 17:02:40 UTC, Ferhat Kurtulmuş wrote:
On Sunday, 23 July 2023 at 16:21:05 UTC, Ruby The Roobster 
wrote:
I'm currently trying to load two textures and apply them to a 
rectangle, following
[this](https://learnopengl.com/Getting-started/Textures) 
which is linked to from the README file of the bindbc OpenGL 
bindings.


[...]


DCV uses gamut for image input, and opengl for displaying 
stuff. You can take a look at the sources:


https://github.com/libmir/dcv/blob/master/source/dcv/imageio/image.d#L399

https://github.com/libmir/dcv/blob/master/source/dcv/plot/drawprimitives.d#L126


Thank you.  I'm still trying to work out how it works.  It 
seems as if the creator tried the same thing that I did, and 
then commented it out.  Perhaps for the same reason?


I think I found the problem:  It IS the flags I set.  Saving the 
image gives a blank PNG file, though it doesn't explain why I get 
noise at the bottom of the rectangle.


Re: Loading Textures in OpenGL

2023-07-23 Thread Ruby The Roobster via Digitalmars-d-learn

On Sunday, 23 July 2023 at 17:02:40 UTC, Ferhat Kurtulmuş wrote:
On Sunday, 23 July 2023 at 16:21:05 UTC, Ruby The Roobster 
wrote:
I'm currently trying to load two textures and apply them to a 
rectangle, following
[this](https://learnopengl.com/Getting-started/Textures) which 
is linked to from the README file of the bindbc OpenGL 
bindings.


[...]


DCV uses gamut for image input, and opengl for displaying 
stuff. You can take a look at the sources:


https://github.com/libmir/dcv/blob/master/source/dcv/imageio/image.d#L399

https://github.com/libmir/dcv/blob/master/source/dcv/plot/drawprimitives.d#L126


Thank you.  I'm still trying to work out how it works.  It seems 
as if the creator tried the same thing that I did, and then 
commented it out.  Perhaps for the same reason?


Loading Textures in OpenGL

2023-07-23 Thread Ruby The Roobster via Digitalmars-d-learn
I'm currently trying to load two textures and apply them to a 
rectangle, following
[this](https://learnopengl.com/Getting-started/Textures) which is 
linked to from the README file of the bindbc OpenGL bindings.


I'm using Gamut to load the files, with the file:

```d
module texture;

import gamut;
import bindbc.opengl;
import bindbc.glfw;
debug import std.stdio;

private __gshared Image[] _textures;
private __gshared char[][] texData;
public __gshared uint[] textures;

void newTexture(in string filename, out int width, out int hight, 
out int nrChannels)

{
auto k = ++_textures.length;
_textures[k-1].loadFromFile(filename);
if(_textures[k-1].isError)
throw new Exception(_textures[$-1].errorMessage.idup);
if(_textures[k-1].type != PixelType.rgb8 && 
_textures[k-1].type != PixelType.rgba8)

throw new Exception("invalid pixel type");

width = _textures[k-1].width;
hight = _textures[k-1].height;
nrChannels = 3; // May change later, we'll see
_textures[k-1].setSize(width, hight, _textures[k-1].type, 
LAYOUT_GAPLESS | LAYOUT_VERT_STRAIGHT);

auto u = ++texData.length;
texData[u-1] = cast(char[])_textures[k-1].allPixelsAtOnce;
debug writeln(texData[u-1]);
textures.length++;
glGenTextures(1, [k-1]);
glBindTexture(GL_TEXTURE_2D, textures[k-1]);
// Set wrapping & filtering options
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, 
GL_NEAREST_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, 
GL_LINEAR);

// Bind the texture;
if(texData[u-1])
{
switch(_textures[k-1].type)
{
case PixelType.rgb8:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, 
hight, 0, GL_RGB, GL_UNSIGNED_BYTE, texData[u-1].ptr);

glGenerateMipmap(GL_TEXTURE_2D);
break;
case PixelType.rgba8:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, 
hight, 0, GL_RGBA, GL_UNSIGNED_BYTE, texData[u-1].ptr);

glGenerateMipmap(GL_TEXTURE_2D);
break;
default:

}
}
else
{
throw new Exception("Failed to load texture: " ~ 
filename);

}
_textures[k-1] = Image.init;
texData[u-1] = [][];
}
```

I presume that I am messing up with reading the pixels, but I 
don't see how.
Does LAYOUT_GAPLESS | LAYOUT_VERT_STRAGIHT really have that great 
of an effect?


Re: Recommendation on plotting library

2023-07-21 Thread Ruby The Roobster via Digitalmars-d-learn

On Thursday, 20 July 2023 at 04:41:48 UTC, Chris Piker wrote:

[SNIP]

I just tried ggplotd and it was easy to make it work on Linux, 
only one external apt command needed, but on Windows, even that 
is a deal breaker.  Package management on Windows seems to be 
wild-west/nonexistent.




Try MinGW.  There should be SOME way to use GTK with it, though I 
haven't been able to get it to work.



[SNIP]




Re: How to build a static lib properly?

2023-03-05 Thread Ruby The Roobster via Digitalmars-d-learn

On Monday, 6 March 2023 at 00:55:04 UTC, ryuukk_ wrote:

Hello,

I am trying to build: https://github.com/dlang-community/DCD/ 
as a static lib


[...]


Try ```dub build --build-mode=allAtOnce```.


Re: Gneric linkedList range adaptor

2023-02-10 Thread Ruby The Roobster via Digitalmars-d-learn
On Friday, 10 February 2023 at 23:39:11 UTC, Ruby The Roobster 
wrote:




The problem is that Node.next is not, and cannot be `static`.  
Thus, there is no way for you to pass it as an alias template 
parameter, and this should be considered a compiler bug that 
this doesn't error out.


Nevermind, I'm an absolute idiot.  The first works, it uses 
Node.next in the context of this.current.  The second should also 
work, T is of type Node*.


This seems to be a bug with the compiler, it automatically infers 
function attributes by default before evaluating whether the 
function actually works with said inferred attributes.


Your __traits(child) solution doesn't work, because T is a type, 
not a variable.





Re: Gneric linkedList range adaptor

2023-02-10 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 10 February 2023 at 22:10:20 UTC, Ben Jones wrote:
I'm trying to write a range adaptor for linked list types.  The 
range type seems to work OK, but my helper function to deduce 
the node type has a compiler error.  My hunch is that 
`nextField` loses its association with T when I'm trying to 
pass it as a template parameter inside the helper method, but I 
can't use __traits(child) there to fix it.


Any idea how to fix the helper method?

Is this something that would be useful to add to std.range 
somewhere?  Or is something like it already in Phobos?


Thanks

```
import std.stdio;
import std.range;

struct LinkedListAdaptor(alias nextField, T){
T current;
@safe:
nothrow:

this(T head){
current = head;
}

bool empty() const {
return current == null;
}   

T front() {
return current;
}

void popFront() {
current = __traits(child, current, nextField);
}
}

auto linkedListAdaptor(alias nextField, T)(T head) if(is(T == 
U*, U)){

return LinkedListAdaptor!(nextField, T)(head);

//fails with:
//onlineapp.d(27): Error: symbol or expression expected as 
first argument of __traits `child` instead of `Node*`
// return LinkedListAdaptor!(__traits(child, T, nextField), 
T)(head);

}

struct Node{
int data;
Node* next;
}

void main(){
Node* head = new Node(10, new Node(20, null));

auto rng1 = LinkedListAdaptor!(Node.next, Node*)(head);
auto rng = linkedListAdaptor!(Node.next)(head);
foreach(const x; rng){
writeln(x.data);
}
}
```

This fails with:

Error: need `this` for `linkedListAdaptor` of type `pure 
nothrow @nogc @safe LinkedListAdaptor!(next, Node*)(Node* head)`


The problem is that Node.next is not, and cannot be `static`.  
Thus, there is no way for you to pass it as an alias template 
parameter, and this should be considered a compiler bug that this 
doesn't error out.


How to get the body of a function/asm statement in hexadecimal

2023-01-29 Thread Ruby the Roobster via Digitalmars-d-learn

I'm trying to do something like

```d
void main()
{
auto d = 
*d.writeln;
}

void c()
{
}
```

In an attempt to get the hexadecimal representation of the 
machine code of a function.  Of course, function pointers cannot 
be dereferenced.  What do?


Furthermore, I would like to be able to do the same for an `asm` 
statement.


Re: vibe.d + mongoDB

2023-01-20 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 20 January 2023 at 18:58:16 UTC, seany wrote:
Hi I am googling to find some vibe.d and mongoDB tutorial. Are 
their some available? Thank you


There is a nice book, titled D Web Development, that despite 
being 6 years old, is still mostly applicable to using vibe.d.  
The only archaic thing in the book is the use of the ```shared 
static this``` module constructor, which no longer works, and 
should be replaced by the main() function.


Re: Non-ugly ways to implement a 'static' class or namespace?

2023-01-20 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 20 January 2023 at 13:38:52 UTC, Hipreme wrote:
On Friday, 20 January 2023 at 11:28:23 UTC, thebluepandabear 
wrote:

...
[snip]

With a single file, you can do:
```d

final class Algo
{
@disable this();
static:
void drawLine(...){}
}
```


This also works, but it dissimilar to Java in that in Java, each 
class gets its own file.


Re: Non-ugly ways to implement a 'static' class or namespace?

2023-01-20 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 20 January 2023 at 13:38:47 UTC, evilrat wrote:
On Friday, 20 January 2023 at 13:17:05 UTC, Ruby The Roobster 
...

[snip]

Also there is various import options such as renamed import or 
static import(doesn't add module to a scope thus requiring to 
fully qualify it)


static import, can be used to somewhat mimic namespaces, more 
complex scenario would be making a module consisting of public 
imports to group things together, but I don't think it is 
common in D.

https://dlang.org/spec/module.html#static_imports

```d
static import std.stdio;

void main()
{
  // nope, this function will not be resolved, compilation error
  // wrtiteln("hello");

  // ok
  std.stdio.writeln("hello");
}
```


I never knew that there even WAS a `static import` option.  Good 
to know.


Re: Non-ugly ways to implement a 'static' class or namespace?

2023-01-20 Thread Ruby The Roobster via Digitalmars-d-learn
On Friday, 20 January 2023 at 13:03:18 UTC, thebluepandabear 
wrote:

ll
a function without instantiating said class, as functions act 
on the class object.


Ok, thanks.

I think D should implement something similar to `static class` 
but I doubt it will happen.


D isn't Java, and never will be.  If you want similar 
functionality, you put the functions in a separate file, and add 
the line to the top of it:


```d
module modulename;
```

and title the file modulename.d.  Then you can use this module as 
a .class file in java by adding


```d
import modulename;
```

to the file that uses it.


Re: Non-ugly ways to implement a 'static' class or namespace?

2023-01-20 Thread Ruby The Roobster via Digitalmars-d-learn
On Friday, 20 January 2023 at 12:55:37 UTC, Ruby The Roobster 
wrote:

On Friday, 20 January 2023 at 11:28:23 UTC, thebluepandabear ...

There is no way to implement that functionality in D.  `final` 
means that the class cannot be extended, and `abstract` 
requires that only an extension of said class can be 
instantiated.  However, unlike in Java and C#, you cannot call 
a function without instantiating said class, as functions act 
on the class object.


Also, there is a `static` keyword, but a `static class` can be 
instantiated as a member of the external class.


Re: Non-ugly ways to implement a 'static' class or namespace?

2023-01-20 Thread Ruby The Roobster via Digitalmars-d-learn
On Friday, 20 January 2023 at 11:28:23 UTC, thebluepandabear 
wrote:

Hi,

In Java/C# you can create purely static classes.

These are classes whose methods are all static, the classes 
cannot be derived from or instantiated:


```
static class Algo {
void drawLine(Canvas c, Pos from, Pos to) { .. };
}
```

Class in use:

```
Algo.drawLine(new Canvas(), new Pos(5, 3), new Pos(7, 9));
```

This type of semantics is not possible in D, which sucks.

After scouring the forums, the only workaround seems to be the 
following:


```
final abstract class Algo {
void drawLine(Canvas c, Pos from, Pos to) { .. };
}
```

This solution seems like a bit of a hack, which is why I don't 
like it.


Alternatively you could create a module, but then it would just 
be a function without a clear type.


Is anyone aware of a non-ugly way to implement a 'static' class 
or namespace?


Regards,
thebluepandabear


There is no way to implement that functionality in D.  `final` 
means that the class cannot be extended, and `abstract` requires 
that only an extension of said class can be instantiated.  
However, unlike in Java and C#, you cannot call a function 
without instantiating said class, as functions act on the class 
object.


Re: What is the 'Result' type even for?

2023-01-20 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 20 January 2023 at 03:39:48 UTC, H. S. Teoh wrote:
On Fri, Jan 20, 2023 at 03:34:43AM +, Ruby The Roobster via 
Digitalmars-d-learn wrote:
On Friday, 20 January 2023 at 03:30:56 UTC, Steven 
Schveighoffer wrote:

> On 1/19/23 10:11 PM, Ruby The Roobster wrote:
> ...
> 
> The point is to be a range over the original input, 
> evaluated lazily. Using this building block, you can create 
> an array, or use some other algorithm, or whatever you want. 
> All without allocating more space to hold an array.

[...]
I get the point that it is supposed to be lazy.  But why are 
these basic cases not implemented?  I shouldn't have to go 
write a wrapper for something as simple as casting this type 
to the original type. This is one of the things that one 
expects the standard library to do for you.


There's no need to write any wrappers.  Just tack `.array` to 
the end of your pipeline, and you're good to go.



T


Thank you.  I didn't know that there was such a property `.array`.


Re: What is the 'Result' type even for?

2023-01-19 Thread Ruby The Roobster via Digitalmars-d-learn
On Friday, 20 January 2023 at 03:30:56 UTC, Steven Schveighoffer 
wrote:

On 1/19/23 10:11 PM, Ruby The Roobster wrote:
...

The point is to be a range over the original input, evaluated 
lazily. Using this building block, you can create an array, or 
use some other algorithm, or whatever you want. All without 
allocating more space to hold an array.


-Steve


I get the point that it is supposed to be lazy.  But why are 
these basic cases not implemented?  I shouldn't have to go write 
a wrapper for something as simple as casting this type to the 
original type.  This is one of the things that one expects the 
standard library to do for you.


Re: What is the 'Result' type even for?

2023-01-19 Thread Ruby The Roobster via Digitalmars-d-learn
On Friday, 20 January 2023 at 03:11:33 UTC, Ruby The Roobster 
wrote:

Take this example:

```d
import std;
void main()
{
auto c = "a|b|c|d|e".splitter('|');
c.writeln;
string[] e = ["a", "b", "c", "d", "e"];
assert(c.equal(e));
typeof(c).stringof.writeln;
}
```

The program prints:

["a", "b", "c", "d", "e"]
Result

What is the purpose of this 'Result' type?  To serve as a 
generic range?  Because, it seems to only cause problems.  For 
example, you cannot assign or cast the result type into a 
range, even when the type has the same inherent function:


```d
string[] c = "a|b|c|d|e".splitter('|'); // fails
string[] d = cast(string[])"a|b|c|d|e".splitter('|'); // also 
fails

```

And if you need to perform a set operation?

```d
c[] ~= "lolno"; // fails, as [] isn't defined for Result.
```

Then what is the point of this type, if not to just make things 
difficult?  It cannot be casted, and vector operations cannot 
be performed, and it seems to just serve as an unnecessary 
generalization.


Furthermore, it can also be confirmed that each member of c is a 
string, further solidifying my opinion of 'Result' as just being 
a generic range template, that cannot be casted to an array of 
the original type.


What is the 'Result' type even for?

2023-01-19 Thread Ruby The Roobster via Digitalmars-d-learn

Take this example:

```d
import std;
void main()
{
auto c = "a|b|c|d|e".splitter('|');
c.writeln;
string[] e = ["a", "b", "c", "d", "e"];
assert(c.equal(e));
typeof(c).stringof.writeln;
}
```

The program prints:

["a", "b", "c", "d", "e"]
Result

What is the purpose of this 'Result' type?  To serve as a generic 
range?  Because, it seems to only cause problems.  For example, 
you cannot assign or cast the result type into a range, even when 
the type has the same inherent function:


```d
string[] c = "a|b|c|d|e".splitter('|'); // fails
string[] d = cast(string[])"a|b|c|d|e".splitter('|'); // also 
fails

```

And if you need to perform a set operation?

```d
c[] ~= "lolno"; // fails, as [] isn't defined for Result.
```

Then what is the point of this type, if not to just make things 
difficult?  It cannot be casted, and vector operations cannot be 
performed, and it seems to just serve as an unnecessary 
generalization.


MacOS Weirdness

2023-01-16 Thread Ruby The Roobster via Digitalmars-d-learn
I just fixed a bug in my personal D hobby project.  After pushing 
everything to github, I noticed that it fails to link with the 
latest LDC on MacOS.  The error I'm getting is thus:


```
ld: warning: alignment (1) of atom 'anon' is too small and may 
result in unaligned pointers
ld: warning: pointer not aligned at address 0x3D2C9 ('anon' + 
4809 from 
.dub/build/shared-debug-posix.osx.darwin-x86_64-ldc_v1.30.0-8F420C7727F3804A85668CA76BD80D4C//obj/libdutils.o)

ld: unaligned pointer(s) for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to 
see invocation)

Error: /usr/bin/cc failed with status: 1
FAIL 
.dub/build/shared-debug-posix.osx.darwin-x86_64-ldc_v1.30.0-8F420C7727F3804A85668CA76BD80D4C/ dutils dynamicLibrary

/Users/runner/hostedtoolcache/dc/ldc2-1.30.0/x64/ldc2-1.30.0-osx-universal/bin/ldc2
 failed with exit code 1.
```

This only happens when building the project as a shared library.  
It builds perfectly fine as a static library.  Any solutions?  
Thanks in advance.


Re: Proper way to exit with specific exit code?

2022-11-13 Thread Ruby The Roobster via Digitalmars-d-learn

On Sunday, 13 November 2022 at 21:16:32 UTC, mw wrote:
On Saturday, 19 September 2020 at 06:11:15 UTC, Jacob Carlborg 
wrote:

On 2020-09-17 16:58, drathier wrote:

What's the proper way to exit with a specific exit code?

I found a bunch of old threads discussing this, making sure 
destructors run and the runtime terminates properly, all of 
which seemingly concluding that it's sad that there isn't a 
way to do this easily, but hopefully things have changed in 
the last 5-10 years and I'm just missing the obvious solution.


The proper way is:

int main()
{
return 42;
}

I highly recommend against trying to terminate the application 
using `exit` or any other way. Just let the control flow 
return back to the `main` function.


I'm facing this problem to exit early from a multi threaded 
program for mem profiling purpose:


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


So what the simplest and reliable way to terminate all threads 
and exit to os?


I even tried core.stdc.stdlib.exit(-1), it does not work.


Just give the threads a killswitch, pass the killswitch method to 
all of the threads, wait for all the threads to exit, and then 
return.  If this doesn't work, than I don't know what will.


Re: Interfacing with Rust

2022-09-30 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 30 September 2022 at 06:25:33 UTC, Imperatorn wrote:
On Friday, 30 September 2022 at 00:18:42 UTC, Ruby The Roobster 
wrote:

On Thursday, 29 September 2022 at 16:07:59 UTC, mw wrote:
On Thursday, 29 September 2022 at 16:02:43 UTC, Ruby The 
Roobster wrote:
Is there any way one can interface with Rust, such as with a 
struct, or a function?


I know that rust has an extern keyword, but I can't get it 
to work.


https://code.dlang.org/packages/rust_interop_d


Read the notes on memory management:

Only pass pointers as u64 as value type.


This isn't the issue.  I can't interface anything, period.


Show an example of exactly what you're trying to do. Maybe it's 
some detail


lib.rs:

```rs
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}

impl Rectangle {
extern "cdecl" fn area() -> u32 {
self.width * self.height
}

extern "cdecl" fn can_hold(, other: ) -> 
bool {

self.width > other.width && self.height > other.height
}
}
```

main.d:

```d
struct Rectangle
{
uint width;
uint hight;
extern(C++) uint area();
extern(C++) bool can_hold(Rectangle rhs)
}

void main()
{
auto rect1 = Rectangle(1,1);
auto rect2 = Rectangle(0,0);
assert(rect1.area == 1 && rect2.area == 0 && 
rect1.canHold(rect2));

}
```

lib.rs was built as a "staticlib" using rustc, and the command I 
used was:


ldc2 -m64 main.d lib.lib

The output:

```
main.obj : error LNK2019: unresolved external symbol "public: 
unsigned int __cdecl Rectangle::area(void)" 
(?area@Rectangle@@QEAAIXZ) referenced in function _Dmain
main.obj : error LNK2019: unresolved external symbol "public: 
bool __cdecl Rectangle::can_hold(struct Rectangle)" 
(?can_hold@Rectangle@@QEAA_NU1@@Z) referenced in function _Dmain

main.exe : fatal error LNK1120: 2 unresolved externals
Error: C:\Program Files (x86)\Microsoft Visual 
Studio\2022\BuildTools\VC\Tools\MSVC\14.33.31629\bin\HostX64\x64\link.exe failed with status: 1120

```

Also, is it normal for the .lib file to be 11 megabytes?


Re: Interfacing with Rust

2022-09-29 Thread Ruby The Roobster via Digitalmars-d-learn

On Thursday, 29 September 2022 at 16:07:59 UTC, mw wrote:
On Thursday, 29 September 2022 at 16:02:43 UTC, Ruby The 
Roobster wrote:
Is there any way one can interface with Rust, such as with a 
struct, or a function?


I know that rust has an extern keyword, but I can't get it to 
work.


https://code.dlang.org/packages/rust_interop_d


Read the notes on memory management:

Only pass pointers as u64 as value type.


This isn't the issue.  I can't interface anything, period.


Interfacing with Rust

2022-09-29 Thread Ruby The Roobster via Digitalmars-d-learn
Is there any way one can interface with Rust, such as with a 
struct, or a function?


I know that rust has an extern keyword, but I can't get it to 
work.


Re: can not take const struct member address at CTFE , is this a bug?

2022-09-13 Thread Ruby The Roobster via Digitalmars-d-learn

On Tuesday, 13 September 2022 at 11:16:55 UTC, test123 wrote:

```d
struct c { uint a, b;}
__gshared const c d = { 3, 4};
__gshared const e = 
```

./test.d(4): Error: expression `(3u, 4u).a` is not a constant


I need this to work around C struct array member like this:

```c
struct c {
 uint32_t a, b;
 uint32_t[] arr;
}
```

If I can take const object member address as __gshared const, 
then the problem is fixed.



Or if I can force cast the const object pointer into other 
type, will work be able to work this around. (but not work)


```sh
Error: reinterpreting cast from 
`const(validate_KnownRegex_enum_init_type)*` to 
`const(upb_MiniTable_Enum)*` is not supported in CTFE

```


The addresses of items stored in memory are by definition not 
constant.  This isn't a bug.


Re: This code completely breaks the compiler:

2022-08-19 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 19 August 2022 at 05:50:17 UTC, Mike Parker wrote:
On Friday, 19 August 2022 at 04:25:25 UTC, Ruby The Roobster 
wrote:



[...]


If the template is never instantiated, it never makes it into 
the executable. It doesn't matter if it's in production or not, 
and has nothing to do with tests. It doesn't exist. How could 
the compiler catch any problems if it has no idea what `Mtypes` 
is?


This is true for any template parameter. Consider this:

```d
import std.stdio;

T derp(T)(T val) {
val += 10;
return val;
}

void main()
{
writeln("Hello D");
}
```

`derp` obviously isn't going to work with every type. But this 
code compiles because `derp` is never instantiated. The 
compiler can't check if the code in `derp` is valid because it 
has no idea what `T` might be. If it's `int`, then no problem. 
If it's `string` then no way:


```d
void main()
{
writeln(derp!string("No way"));
}
```

Now you'll get this:

```
onlineapp.d(4): Error: slice `val` is not mutable
onlineapp.d(10): Error: template instance 
`onlineapp.derp!string` error instantiating

```


This makes sense.  Still, in my code, where the function has the 
same return type regardless of instantiation, the compiler should 
at least check that expressions independent of the template 
parameter are valid.


Re: This code completely breaks the compiler:

2022-08-18 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 19 August 2022 at 04:16:28 UTC, JG wrote:
On Friday, 19 August 2022 at 03:13:03 UTC, Ruby The Roobster 
wrote:
On Friday, 19 August 2022 at 03:10:38 UTC, Ruby The Roobster 
wrote:
This snippet compiles.  Even if `dsds` and `sadsad` are 
defined nowhere, this code compiles.


[SNIP]

The reason why this compiles is because of the varidic 
template parameter, `Mtypes`.


Either there is something I'm missing, or the compiler 
completely breaks when it sees varidic template arguments.


The only way to get the code to not compile is to actually 
call the function.


I think it might help to post the entire code you think should 
not compile (which does). I guess you are aware that templated 
code is only "fully checked" when it is instantiated. E.g. this 
will compile.

```d
import std;

auto nonsense(T)(T t) {
return 5+"six";
}

void main() {
}
```


So that's why it compiled.  Still, I believe that stuff like this 
ought to be detected at compile time, as supposed to in a 
unittest or, if someone forgot to write the tests, in production.


Re: This code completely breaks the compiler:

2022-08-18 Thread Ruby The Roobster via Digitalmars-d-learn
On Friday, 19 August 2022 at 03:10:38 UTC, Ruby The Roobster 
wrote:
This snippet compiles.  Even if `dsds` and `sadsad` are defined 
nowhere, this code compiles.


[SNIP]

The reason why this compiles is because of the varidic template 
parameter, `Mtypes`.


Either there is something I'm missing, or the compiler 
completely breaks when it sees varidic template arguments.


The only way to get the code to not compile is to actually call 
the function.


This code completely breaks the compiler:

2022-08-18 Thread Ruby The Roobster via Digitalmars-d-learn
This snippet compiles.  Even if `dsds` and `sadsad` are defined 
nowhere, this code compiles.


```d
import std.typecons : Tuple;

sadsad executeFunction(Mtypes...)(dstring func, Tuple!(Mtypes) 
args)

{
static foreach(type; typel.keys)
{
mixin(typel[type] ~ " ret"d ~ type ~ ";");
}

dstring returnType = "Number"d;

Switch: final switch(returnType)
{
static foreach(type; typel.keys)
{
case type:
mixin("alias ret = ret"d ~ type ~ ";");
break Switch;
}
}
dsds ret;
return ret;
}
```

The reason why this compiles is because of the varidic template 
parameter, `Mtypes`.


Either there is something I'm missing, or the compiler completely 
breaks when it sees varidic template arguments.


dub-registry

2022-08-12 Thread Ruby The Roobster via Digitalmars-d-learn
I am currently trying to set up for myself a personal dub 
registry, and I have MongoDB installed.  Yet, when I run `dub 
run` in the repo directory, I get the following error message:


```
vibe.db.mongo.connection.MongoAuthException@C:\Users\User\AppData\Local\dub\packages\vibe-d-0.9.4\vibe-d\mongodb\vibe\db\mongo\connection.d(641):
 Authentication failed.
```

How can I configure MongoDB to stop this error from occurring?


Re: Array Wierdness

2022-08-10 Thread Ruby The Roobster via Digitalmars-d-learn
On Wednesday, 10 August 2022 at 15:50:45 UTC, Steven 
Schveighoffer wrote:

On 8/10/22 11:26 AM, Ruby The Roobster wrote:
[SNIP]
A related bug: https://issues.dlang.org/show_bug.cgi?id=23140

-Steve


Funnily enough, I came across this when trying to fix that same 
bug.


Re: Array Wierdness

2022-08-10 Thread Ruby The Roobster via Digitalmars-d-learn
On Wednesday, 10 August 2022 at 15:19:41 UTC, Ruby The Roobster 
wrote:

Take the following code:

```d
void main()
{
shared class C { bool opEquals(const(shared(C)) rhs) const 
shared  { return true;}}

const(C) c = new C();
const(C)[] a = [c];
const(C)[] b = [c];
assert(a[0] == b[0]);
}
```

This code (supposedly) checks whether ```a``` and ```b``` are 
equal.  The thing is, it doesn't, because C is defined as 
```shared```.  Is there anything I can do to fix this?


Wait, is this a regression?

---

Up to  2.098.1: Success and no output
Since  2.099.1: Failure with output:
-
onlineapp.d(7): Error: none of the overloads of template 
`object.opEquals` are callable using argument types 
`!()(shared(const(C)), shared(const(C)))`

/path/to/dmd.linux/dmd2/linux/bin64/../../src/druntime/import/object.d(269):Candidate is: `opEquals(LHS, RHS)(LHS lhs, RHS rhs)`

  with `LHS = shared(const(C)),
   RHS = shared(const(C))`
  must satisfy the following constraint:
`   is(LHS : const(Object))`
-


Array Wierdness

2022-08-10 Thread Ruby The Roobster via Digitalmars-d-learn

Take the following code:

```d
void main()
{
shared class C { bool opEquals(const(shared(C)) rhs) const 
shared  { return true;}}

const(C) c = new C();
const(C)[] a = [c];
const(C)[] b = [c];
assert(a[0] == b[0]);
}
```

This code (supposedly) checks whether ```a``` and ```b``` are 
equal.  The thing is, it doesn't, because C is defined as 
```shared```.  Is there anything I can do to fix this?


Re: Arbitrary precision decimal numbers

2022-08-10 Thread Ruby The Roobster via Digitalmars-d-learn

On Saturday, 6 August 2022 at 13:20:19 UTC, Sergey wrote:
On Thursday, 4 August 2022 at 13:01:30 UTC, Ruby The Roobster 
wrote:
Is there any implementation in phobos of something similar to 
BigInt but for non-integers as well?  If there isn't is there 
a dub package that does this, and if so, which one?


Also you could find usefull such projects:

http://mir-algorithm.libmir.org/mir_bignum_decimal.html

https://github.com/huntlabs/hunt-extra/blob/2d286f939193fc0cd55c799906f7657cec502dc8/source/hunt/math/BigDecimal.d


It doesn't provide for arithmetic operations though, according to 
the docs.


Re: Obscure Isssue #1

2022-08-05 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 5 August 2022 at 17:02:48 UTC, Ruby The Roobster wrote:
On Friday, 5 August 2022 at 16:58:25 UTC, Ruby The Roobster 
wrote:

On Friday, 5 August 2022 at 15:07:18 UTC, H. S. Teoh wrote:
[SNIP]
In other words, you're trying to construct a BigInt with a 
value of 10^18030 (a number with 18030 digits) and wondering 
why the computer is taking forever to compute the value. :-D

[SNIP]

T
I have no idea how the program generated a 18k+ digit number, 
but apparently changing the `+` to a `*` on line 158 solved 
the problem.


Oop.  Just realized that was because I commented out the line 
involving the bug


Turns out that using negative numbers breaks it.


Re: Obscure Isssue #1

2022-08-05 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 5 August 2022 at 16:58:25 UTC, Ruby The Roobster wrote:

On Friday, 5 August 2022 at 15:07:18 UTC, H. S. Teoh wrote:
[SNIP]
In other words, you're trying to construct a BigInt with a 
value of 10^18030 (a number with 18030 digits) and wondering 
why the computer is taking forever to compute the value. :-D

[SNIP]

T
I have no idea how the program generated a 18k+ digit number, 
but apparently changing the `+` to a `*` on line 158 solved the 
problem.


Oop.  Just realized that was because I commented out the line 
involving the bug


Re: Obscure Isssue #1

2022-08-05 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 5 August 2022 at 15:07:18 UTC, H. S. Teoh wrote:
[SNIP]
In other words, you're trying to construct a BigInt with a 
value of 10^18030 (a number with 18030 digits) and wondering 
why the computer is taking forever to compute the value. :-D

[SNIP]

T
I have no idea how the program generated a 18k+ digit number, but 
apparently changing the `+` to a `*` on line 158 solved the 
problem.




Re: Arbitrary precision decimal numbers

2022-08-05 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 5 August 2022 at 14:11:10 UTC, frame wrote:
On Friday, 5 August 2022 at 14:03:36 UTC, Ruby The Roobster 
wrote:


Also, what about division and exponentiation.  You can't just 
forward them to BigInt and get a good result, BigInt will just 
round to an integer for these two.


There are divMod() and powmod() for BigInt but I have no idea 
how precise they really are.


I'm currently working on an arbitrarily precise division 
algortihm based off of the done-by-hand standard algorithm, but I 
need to get it to work for complex numbers, [which it's just 
not](https://forum.dlang.org/post/czidpbdywsohstyvi...@forum.dlang.org).


Re: Obscure Isssue #1

2022-08-05 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 5 August 2022 at 14:11:09 UTC, H. S. Teoh wrote:
On Fri, Aug 05, 2022 at 01:56:40PM +, Ruby The Roobster via 
Digitalmars-d-learn wrote: [...]

public import dutils.math.core;


Is the imported module available anywhere?  I'm trying to run 
your code sample to determine what's going on, but it's not 
compiling because you didn't post the code to dutils.math.core.



T


You can cut that and the Number class out.  They're not relevant 
to the bug.  Sorry for not mentioning that.


Re: Arbitrary precision decimal numbers

2022-08-05 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 5 August 2022 at 14:00:32 UTC, frame wrote:
On Thursday, 4 August 2022 at 13:01:30 UTC, Ruby The Roobster 
wrote:
Is there any implementation in phobos of something similar to 
BigInt but for non-integers as well?  If there isn't is there 
a dub package that does this, and if so, which one?


We have this:

https://code.dlang.org/search?q=decimal

I end up using BigInt instead on a custom wrapper that stores 
the precision hint. To calculate with any number, it need to 
convert each value to the same base (eg. storing 10.234 simply 
results in a BigInt with value 10234 and the precision hint of 
3) and then forward the operation to BigInt.


I'm already trying to make one, and I have a similar idea, but I 
ewant it extended to complex numbers.


Also, what about division and exponentiation.  You can't just 
forward them to BigInt and get a good result, BigInt will just 
round to an integer for these two.


Obscure Isssue #1

2022-08-05 Thread Ruby The Roobster via Digitalmars-d-learn

My code (as seen below) is failing due to a single line.

That line is:
```d
this.ival += (this.val * rhs.ival);
```

I kid you not, this is the reason why running unittests results 
in a program that just hangs.  And no, replacing unittest with 
void main() doesn't fix the problem.


```d
module dutils.math.number;

version(DLL)
{
export:
}

version(Standard)
{
public:
}

public import dutils.math.core;
public import std.bigint;

class Number : Mtype!NumberContainer
{
this(NumberContainer num)
{
this.contained = val;
}

override dstring toDstring() const @property pure @safe
{
return this.contained.toDstring;
}

override void fromDstring(dstring from) pure @safe
{
this.contained.fromDstring(from);
}

bool applyOp(W)(dstring op, Mtype!W rhs) pure @safe
in
{
assert(is(W == NumberContainer));
assert((op == "+"d) ^ (op == "-"d) ^ (op == "*"d) ^ (op 
== "/"d) ^ (op == "^^"d));

}
do
{
mixin("this.contained " ~ op ~ "= rhs.contained;");
return true; //We assume that the contract hasn't been 
violated.

}
}

struct NumberContainer
{
this(BigInt val, BigInt ival = 0, long pow10 = 0, ulong 
precision = 18) pure @safe nothrow @nogc

{
this.val = val;
this.pow10 = pow10;
this.ival = ival;
this.precision = precision;
}

dstring toDstring() const @property pure @safe
{
return ""d; //Placeholder
}

void fromDstring(dstring from) pure @safe
{
//Placeholder
}

void opOpAssign(string op)(NumberContainer rhs) pure @safe
{
import std.algorithm : max;
if(op == "/") //This section is where the line that hangs 
leads us to.

{
//Because BigInt is strictly an integer type, it is 
easier to code A/B as A*1/B, because the * operator is a piece of 
cake, and 1 over a BigInt is easier than an arbitrary BigInt

//over another arbitrary BigInt
immutable BigInt den = rhs.val ^^ 2 + rhs.ival ^^ 2;
NumberContainer store = 
NumberContainer(cast(BigInt)0);

auto istore = store;
long count = 0;
ubyte count2 = 9;
rhs *= NumberContainer(rhs.val, -rhs.ival, rhs.pow10, 
rhs.precision); //This line leads directly to the cause of hang.

for(ulong i = 0; i < precision; ++i) //Real part
{
if(rhs.val == BigInt(0))
break;
//Play around with the multiplier so the 
denominator actually fits in the numerator.

while(den > (BigInt(10) ^^ count) * rhs.val)
{
++count;
}
//Remove excess.
while(den < (BigInt(10) ^^ (count - 1L) * 
rhs.val))

{
--count;
}

for(; count2 * den > (BigInt(10) ^^ count) * 
rhs.val; --count2)

{
if(count2 < -9) //Remember, negative 
numbers exist too!
throw new Exception("ERROR: Division 
by 0");

}

rhs.val *= (BigInt(10) ^^ count); //`rhs` is a 
copy, so this isn't an issue.
rhs.val -= count2 * den; //Continue performing 
long division.

store.val *= 10;
store.val += count2;
store.pow10 -= count;

count = 0;
count2 = 9;
}

this.val *= store.val;
this.pow10 = store.pow10;

for(ulong i = 0; i < precision; ++i) //Imaginary part.
{
if(rhs.ival == BigInt(0))
break;
while(den > (BigInt(10) ^^ count) * rhs.ival)
{
++count;
}
//Remove excess.
while(den < (BigInt(10) ^^ (count - 1L) * 
rhs.ival))

{
--count;
}

for(; count2 * den > (BigInt(10) ^^ count) * 
rhs.ival; --count2)

{
if(count2 < -9) //Remember, negative 
numbers exist too!
throw new Exception("ERROR: Division 
by 0");

}

rhs.ival *= (BigInt(10) ^^ count); //`rhs` is a 
copy, so this isn't an issue.
rhs.ival -= count2 * den; //Continue performing 
long division.

istore.ival *= 10;
istore.ival += count2;
istore.pow10 -= count;

count = 0;
count2 = 9;
}
import std.algorithm : min, max;
this.ival *= istore.ival;
this.pow10 = min(store.pow10, istore.pow10);
if(store.pow10 > istore.pow10)
this.val *= BigInt(10) ^^ (store.pow10 - 
istore.pow10);

else
this.ival 

Re: Unittest Absurdity

2022-08-04 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 5 August 2022 at 01:51:21 UTC, Ruby The Roobster wrote:
On Friday, 5 August 2022 at 01:47:07 UTC, Ruby The Roobster 
wrote:

On Friday, 5 August 2022 at 01:42:23 UTC, jfondren wrote:

On Friday, 5 August 2022 at 01:38:48 UTC, jfondren wrote:

Here's a complete example that passes tests:

```d
struct S {
int n;
void opOpAssign(string op)(S rhs) if (op == "/") {
n++;
}
}

unittest {
auto a = S(1), b = S(2);
a /= b;
b /= a;
assert(a.n == 2);
assert(b.n == 3);
}
```


I found the issue:  opOpAssign isn't getting called at all.  I 
have no idea why, though.


Even then, I still have a bug, but that is completely unrelated 
to this issue.


Nevermind.  I have to remove the trailing equals sign.


Re: Unittest Absurdity

2022-08-04 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 5 August 2022 at 01:47:07 UTC, Ruby The Roobster wrote:

On Friday, 5 August 2022 at 01:42:23 UTC, jfondren wrote:

On Friday, 5 August 2022 at 01:38:48 UTC, jfondren wrote:

Here's a complete example that passes tests:

```d
struct S {
int n;
void opOpAssign(string op)(S rhs) if (op == "/") {
n++;
}
}

unittest {
auto a = S(1), b = S(2);
a /= b;
b /= a;
assert(a.n == 2);
assert(b.n == 3);
}
```


I found the issue:  opOpAssign isn't getting called at all.  I 
have no idea why, though.


Even then, I still have a bug, but that is completely unrelated 
to this issue.


Re: Unittest Absurdity

2022-08-04 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 5 August 2022 at 01:42:23 UTC, jfondren wrote:

On Friday, 5 August 2022 at 01:38:48 UTC, jfondren wrote:

Here's a complete example that passes tests:

```d
struct S {
int n;
void opOpAssign(string op)(S rhs) if (op == "/") {
n++;
}
}

unittest {
auto a = S(1), b = S(2);
a /= b;
b /= a;
assert(a.n == 2);
assert(b.n == 3);
}
```


I found the issue:  opOpAssign isn't getting called at all.  I 
have no idea why, though.


Re: Unittest Absurdity

2022-08-04 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 5 August 2022 at 01:23:40 UTC, Ruby The Roobster wrote:

[SNIP]
Any function other than an operator overload seems to work fine.


Also, this isn't mentioned in the spec.

Additional Information:

Fails for both DMD and LDC on Windows x86_64 for dmd v2.100.1


Unittest Absurdity

2022-08-04 Thread Ruby The Roobster via Digitalmars-d-learn

How do I get unittests to actually execute operator overloads?

E.g.:

```d
struct Struct
{
void opOpAssign(string op)(Struct rhs) //Assume that the 
operator `/=` is implemented here

{
//...
}
}

unittest
{
   Struct a = Struct(1);

   Struct b = Struct(2);

   a /= b;

   assert(a == Struct(5, 0, -1));
}
```

The unittest completely ignores the `a /= b`.

Unittests also ignore swapping `a` for `a/b` in the `assert` 
statement, and even if I force the operator overloads to give me 
the correct answers, the `assert` still fails.


Any function other than an operator overload seems to work fine.


Arbitrary precision decimal numbers

2022-08-04 Thread Ruby The Roobster via Digitalmars-d-learn
Is there any implementation in phobos of something similar to 
BigInt but for non-integers as well?  If there isn't is there a 
dub package that does this, and if so, which one?


Re: BigInt.toString

2022-08-03 Thread Ruby The Roobster via Digitalmars-d-learn

On Thursday, 4 August 2022 at 01:32:15 UTC, Salih Dincer wrote:


I guess I wrote the following anything like that you want.

```d
void main()
{
  import std.bigint,
 std.string : representation;

  BigInt i = 1001;
  auto val = i.to!(dchar[]);
  assert(val.representation == [49, 48, 48, 49]);
}
```

Is that what you want?

SDB@79


Not exactly.  Anyways, it has already been solved.


Re: BigInt.toString

2022-08-03 Thread Ruby The Roobster via Digitalmars-d-learn

On Thursday, 4 August 2022 at 01:05:31 UTC, H. S. Teoh wrote:


Don't call .toString directly. Instead, use std.format.format:

```d
import std;
void main() {
auto x = BigInt("123123123123123123123123123123123123");
	string s = format("%s", x); // this gives you the string 
representation

writeln(s); // prints "123123123123123123123123123123123123"

// If you need to convert to dchar[]:
dstring ds = s.to!(dchar[]);

	// Or if you want a direct formatting into dchar[] without 
going

// through a string intermediate:
auto app = appender!(dchar[]);
app.formattedWrite("%s", x");
dchar[] dcharArray = app.data; // now you have your dchar[]
}
```

Hope this is clear.


T


Thank you.  This worked.


BigInt.toString

2022-08-03 Thread Ruby The Roobster via Digitalmars-d-learn
How exactly can one store the string representation of a BigInt?  
The seemingly obvious


```d
//...
dchar[] ret; //dchar[] is necessary for my project
//Assume that val is a BigInt with a value set earlier:
val.toString(ret, "%d");
//...
```

doesn't work.  I am using x86_64 windows with -m64, and 
v2.100.1(LDC2 1.30.0).


Re: Obsecure problem 2

2022-08-03 Thread Ruby The Roobster via Digitalmars-d-learn

On Wednesday, 3 August 2022 at 19:11:51 UTC, pascal111 wrote:

On Wednesday, 3 August 2022 at 18:53:35 UTC, jfondren wrote:

On Wednesday, 3 August 2022 at 18:33:37 UTC, pascal111 wrote:

I changed it to "x=notfunny(x);" and has the same result.


Now you are changing the value of the temporary loop variable 
that is still immediately discarded afterwards.


You should return a new range that has the values you want, 
not try to mutate the range you're given.


You should provide a code instead of describing my mistakes!!


No need for a code.  See, there is a keyword called `ref`, that 
can be used both in function parameters and in foreach loops, and 
it is the equivalent of a pointer to the type specified, but it 
is automatically dereferenced. As arrays are themselves reference 
types, you don't need to change the parameter from `Range range` 
to `ref Range range`.


On the other hand, `int` in it of itself isn't a reference type, 
meaning that to modify the actual value, you need to change the 
foreach loop to be:


```d
foreach(ref x; range)
x = notfunny(x);
```

Proof:  I tested it, and it works.


Re: How to cast away shared?

2022-08-03 Thread Ruby The Roobster via Digitalmars-d-learn

On Wednesday, 3 August 2022 at 13:00:05 UTC, Paul Backus wrote:
On Wednesday, 3 August 2022 at 12:50:17 UTC, Ruby The Roobster 
wrote:

Any way to 'cast away' shared for an unknown type T?


There's actually an `Unshared` template for this in 
`std.traits`, but for some reason it's `private`, so you can't 
use it directly. Fortunately, it's only two lines:


```d
alias Unshared(T) = T;
alias Unshared(T: shared U, U) = U;
```

Once you have this, you can write `cast(Unshared!T)`.


Thank you.  This really helped.


How to cast away shared?

2022-08-03 Thread Ruby The Roobster via Digitalmars-d-learn

Any way to 'cast away' shared for an unknown type T?


Re: How to call a function from a dll created with d ?

2022-07-07 Thread Ruby The Roobster via Digitalmars-d-learn

On Saturday, 2 July 2022 at 20:43:41 UTC, Vinod KC wrote:

On Saturday, 2 July 2022 at 14:32:11 UTC, apz28 wrote:


dmd -of=dimedll.dll dimedll.d dimedll.def
dmd dime.d dimedll.di


Thanks for the reply. Well, I am sorry to say that your 
suggestions resulted in failure.
First of all, when I used this command -- ` dmd -of=dimedll.dll 
dimedll.d dimedll.def` I got this error message-

`Error: unrecognized file extension dll`.
So I avoided the `-of=dimedll.dll` part.
Then I compiled it with this command - `dmd -H dimedll.d 
dimedll.def`

And I got some warnings. Here are they.
```d
dimedll.def(2) : warning LNK4017: EXETYPE statement not 
supported for the target platform; ignored
dimedll.def(3) : warning LNK4017: SUBSYSTEM statement not 
supported for the target platform; ignored
dimedll.def(4) : warning LNK4017: CODE statement not supported 
for the target platform; ignored
dimedll.def(4) : warning LNK4017: DATA statement not supported 
for the target platform; ignored

   Creating library dimedll.lib and object dimedll.exp
```
I know all of them are from my `def` file. Anyways, I stepped 
forward and tried to run the main file with this dll & lib.
So I ran this command. - `dmd dime.d dimedll.di`. But I got 
this error message.

```d
dime.obj : error LNK2001: unresolved external symbol 
__D7dimedll12__ModuleInfoZ

dime.exe : fatal error LNK1120: 1 unresolved externals
Error: linker exited with status 1120
```


First issue - you're using dmd on windows.  Dmd gives me errors 
about the ModuleInfo, while LDC doesn't. [This is the LDC 
download 
link.](https://github.com/ldc-developers/ldc/releases/download/v1.29.0/ldc2-1.29.0-windows-multilib.exe)  Next, change dimedll.d to the following:


```d
module dimedll;
export void testFunc()
{
import std.stdio;
writeln("Lets build our own ime.");
}
```

and dime.d to the following:

```d
import dimedll; //In case you ever write more functions for 
dimedll.d;


pragma(lib, "dimedll.lib");

void main()
{
testFunc();
}
```

Then run ```ldc2 -shared dimedll.d``` and right after that 
```ldc2 dime.d```.  If I didn't make a mistake in writing this (I 
tested it on my own system), it should output a working program 
that prints the expected output when ran.


Re: How to call a function from a dll created with d ?

2022-07-01 Thread Ruby The Roobster via Digitalmars-d-learn
The solution is to remove the extern declaration.  That does it 
for me, and it prints the expected output.  No need for a .def 
file, unless you are using optlink as your linker (which, as a 
matter of principle, you should use lld or ld instead.)


Any way to define variables from one scope in another scope?

2022-06-20 Thread Ruby The Roobster via Digitalmars-d-learn
Is there any way to define variables in an outer scope from an inner 
scope?  I was thinking


```d
void main()
{
int .y = 3;
}
```
would work, but it doesn't.


Re: Conpile-Time module constructor

2022-06-19 Thread Ruby The Roobster via Digitalmars-d-learn

On 6/19/2022 11:55 AM, Paul Backus wrote:

On Sunday, 19 June 2022 at 15:34:48 UTC, Ruby The Roobster wrote:

On 6/19/2022 11:19 AM, Paul Backus wrote:

On Sunday, 19 June 2022 at 14:51:26 UTC, Ruby The Roobster wrote:
Is it possible to make a module constructor run at compile-time?  If 
so, how?


No, it's not.

What are you trying to accomplish that lead you to ask this question? 
There is probably a different way to do it without involving module 
constructors.


What I was trying to accomplish was to change a compile time array 
whenever a certain module was included.  The value of the array needs 
to be known at compile time.


You can do this with a `static if` check:

     static if (__traits(compiles, { import mymodule; }))
     {
     // mymodule is included
     enum compileTimeArray = ...;
     }


Curious - how exactly does this determine if the module is included?  I 
thought __traits(compiles, ...) only checks if an expression is 
SEMANTICALLY correct.




Re: Conpile-Time module constructor

2022-06-19 Thread Ruby The Roobster via Digitalmars-d-learn

On 6/19/2022 11:19 AM, Paul Backus wrote:

On Sunday, 19 June 2022 at 14:51:26 UTC, Ruby The Roobster wrote:
Is it possible to make a module constructor run at compile-time?  If 
so, how?


No, it's not.

What are you trying to accomplish that lead you to ask this question? 
There is probably a different way to do it without involving module 
constructors.


What I was trying to accomplish was to change a compile time array 
whenever a certain module was included.  The value of the array needs to 
be known at compile time.


Conpile-Time module constructor

2022-06-19 Thread Ruby The Roobster via Digitalmars-d-learn
Is it possible to make a module constructor run at compile-time?  
If so, how?


Re: Anybody have any idea on how to do shared operator overloads?

2022-06-01 Thread Ruby The Roobster via Digitalmars-d-learn

On Thursday, 2 June 2022 at 01:29:39 UTC, Ruby The Roobster wrote:

On Thursday, 2 June 2022 at 01:00:57 UTC, Ali Çehreli wrote:

On 6/1/22 17:36, Ruby The Roobster wrote:
> A stripped down version of some code I have:

Not much experience here but I made two changes:

1) Added 'shared':

>  this(Complex!real num = Complex!real(0,0)) shared
>  {
>  this.num = num;
>  }
>  this(shared Complex!real num = cast(shared
> Complex!real)Complex!real(0,0))
>  {
>  this.num.re = num.re;
>  this.im.re = im.re;

2) Fixed apparent typos:

  this.num.im = num.im;

>  }

I can't guarantee that correct functions are called. It just 
compiles with 2.100.0. :)


Ali


Yes, those were typos.  However, when making this post, I forgot 
to mark ```this(shared Complex!real num = cast(shared 
Complex!real)Complex!real(0,0))``` as shared.  The other 
constructor is not marked as shared in my code, considering as 
shared classes have all of their members marked as shared.


I also have a bug:  __traits(compiles) only checks if the 
expressions are SEMANTICALLY correct, not if they actually 
compile, which they don't.


Interestingly, this code compiles between 2.063 and 2.066.1, if 
you were to put it into run.dlang.io, given the above changes 
(including the p1 + p2!), and set to all compilers.


Re: Anybody have any idea on how to do shared operator overloads?

2022-06-01 Thread Ruby The Roobster via Digitalmars-d-learn

On Thursday, 2 June 2022 at 01:00:57 UTC, Ali Çehreli wrote:

On 6/1/22 17:36, Ruby The Roobster wrote:
> A stripped down version of some code I have:

Not much experience here but I made two changes:

1) Added 'shared':

>  this(Complex!real num = Complex!real(0,0)) shared
>  {
>  this.num = num;
>  }
>  this(shared Complex!real num = cast(shared
> Complex!real)Complex!real(0,0))
>  {
>  this.num.re = num.re;
>  this.im.re = im.re;

2) Fixed apparent typos:

  this.num.im = num.im;

>  }

I can't guarantee that correct functions are called. It just 
compiles with 2.100.0. :)


Ali


Yes, those were typos.  However, when making this post, I forgot 
to mark ```this(shared Complex!real num = cast(shared 
Complex!real)Complex!real(0,0))``` as shared.  The other 
constructor is not marked as shared in my code, considering as 
shared classes have all of their members marked as shared.


Anybody have any idea on how to do shared operator overloads?

2022-06-01 Thread Ruby The Roobster via Digitalmars-d-learn

A stripped down version of some code I have:

```d
public import std.complex;

public interface Mtype
{
// ...
}

public class Number : Mtype
{
public:
this(Complex!real num = Complex!real(0,0))
{
this.num = num;
}
this(shared Complex!real num = cast(shared 
Complex!real)Complex!real(0,0))

{
this.num.re = num.re;
this.im.re = im.re;
}
Number opBinary(string op)(Number rhs) //Standard opBinary
{
mixin("return new Number(this.num " ~ op ~ " 
rhs.num);");

}
shared(Number) opBinary(string op)(shared Number rhs) 
shared

{
return new shared Number(); //Placeholder untill I 
can get the code to work

}
package:
Complex!real num;
}

bool isMtype(T)()
{
bool ret = true;
// ...
shared T p = new shared T();
shared T p2 = new shared T();
ret &= __traits(compiles, T, p + p2);
return ret;
}

static assert(isMtype!Number); //This fails.
```

Upon adding the line shared T c = p + p2 to isMtype,  I get the 
following error:




source\dutils\math\core.d(138,22): Error: function call through 
null class reference `null`
source\dutils\math\core.d(142,15):called from here: 
`isMtype()`
source\dutils\math\core.d(142,1):while evaluating: 
`static assert(cast(int)isMtype() == 1)`


Anybody know how to get a working shared operator overload and 
fix this mess?


Re: Interface wierdness

2022-05-06 Thread Ruby The Roobster via Digitalmars-d-learn

On Saturday, 7 May 2022 at 00:48:20 UTC, Ruby The Roobster wrote:
Define an interface that has a function that returns an object 
of the same type:

..

Nevermind.  I was being stupid and made a naming error.


Interface wierdness

2022-05-06 Thread Ruby The Roobster via Digitalmars-d-learn
Define an interface that has a function that returns an object of 
the same type:


```d
interface I
{
I foo();
}
```

Now define a class that inherits that interface:

```d
class M : I
{
this(int i)
{
this.i = i;
}
M foo()
{
return new M(42);
}
int i;
}
```

Given this example, the following main function fails to compile:

```d
void main()
{
M m = new M(3);
M c = m.foo();
import std.stdio;
writeln(c.i);
}
```

The error message is the following:

```
Error: need `this` for `foo` of type `M()`
```

Why does this happen and how to fix it?


Unittests being broken

2022-05-04 Thread Ruby The Roobster via Digitalmars-d-learn

Some code I have:

```d
alias Operator = dstring function(dstring input);

//List of all operations.
package Operator[dstring] opList;

//List of all functions.
package dstring[dstring] funcList;

//Functions that may not be deleted.
package dstring[dstring] noTouch;

//Initialize the basic arithmetic operations to null: these will 
be handled by operator overloading.

shared static this()
{
opList["+"d] = null;
opList["-"d] = null;
opList["*"d] = null;
opList["/"d] = null;
opList["^^"d] = null;
}

//Add the neccessary functions to noTouch.
shared static this()
{
noTouch["ln(x) = num(num)"d] = null;
noTouch["sin(x) = num(num)"d] = null;
noTouch["cos(x) = num(num)"d] = null;
noTouch["tan(x) = num(num)"d] = null;
noTouch["csc(x) = num(num)"d] = null;
noTouch["sec(x) = num(num)"d] = null;
noTouch["cot(x) = num(num)"d] = null;
noTouch["Γ(x) = num(num)"d] = null;
noTouch["δ(x) = num(num)"d] = null;
assert("δ(x) = num(num)"d in noTouch);
}

//CUT

//CUT END

bool removeFunction(dstring funcdef) @safe @nogc nothrow
{
if(funcdef !in funcList || funcdef in noTouch) //Make sure 
that the function acutally exists and isn't non-removable.

return false;
funcList.remove(funcdef);
return true;
}

///
unittest
{
dstring func = "x + 1"d;
assert(!removeFunction("a(x) = num(num)"d));
funcList["δ(x) = num(num)"d] = null;
assert("δ(x) = num(num)"d in noTouch);
assert(!removeFunction("δ(x) = num(num)"d));
funcList.remove("δ(x) = num(num)");
//registerFunction("a(x) = num(num)"d, func);
//assert(removeFunction("a(x) = num(num)"d));
}
```

Running dub test (with silly) returns no errors.

Now, comment out the following line of code:

```d
assert("δ(x) = num(num)"d in noTouch);
```

Running dub test fails, with the removal of this line being the 
culprit.


However, this code (plus an added main function) passes when 
pasted into run.dlang.io.


I have tried building both with dmd 2.099.1 and ldc 1.029.0 on 
Windows 10 x86_64 with -m64, and it fails.


What can I do to fix this?




Re: Dub says that there is an invalid semVer format, but I don't see how.

2021-11-20 Thread Ruby The Roobster via Digitalmars-d-learn
On Saturday, 20 November 2021 at 01:01:05 UTC, rikki cattermole 
wrote:


Don't use ~> for branches.
...


Thank you very much.  I edited the dub.json, and that fixed the 
problem(anyways, there is no longer a "testing" branch, so that 
would have also been an issue.)





Re: Dub says that there is an invalid semVer format, but I don't see how.

2021-11-19 Thread Ruby The Roobster via Digitalmars-d-learn
On Friday, 12 November 2021 at 21:22:32 UTC, Ruby The Roobster 
wrote:
On Thursday, 11 November 2021 at 01:57:10 UTC, rikki cattermole 
wrote:


On 11/11/2021 2:13 PM, Ruby The Roobster wrote:

Branch ~master: Invalid SemVer format: testing.0.0
Branch ~testing: Invalid SemVer format: testing.0.0
Version 0.1.2: Invalid SemVer format: testing.0.0


testing is a branch.

You are using ~>testing for it.

To use a branch in the SEMVER is ~branch.

https://dub.pm/package-format-json.html#version-specs


This was not causing me issues before. It worked until I added 
the v0.1.2 tag.


This seems to be a dead thread, but I always get these errors:

Branch ~master: Invalid SemVer format: testing.0.0
Branch ~stable: Invalid SemVer format: stable.0.0


Re: Dub says that there is an invalid semVer format, but I don't see how.

2021-11-12 Thread Ruby The Roobster via Digitalmars-d-learn
On Thursday, 11 November 2021 at 01:57:10 UTC, rikki cattermole 
wrote:


On 11/11/2021 2:13 PM, Ruby The Roobster wrote:

Branch ~master: Invalid SemVer format: testing.0.0
Branch ~testing: Invalid SemVer format: testing.0.0
Version 0.1.2: Invalid SemVer format: testing.0.0


testing is a branch.

You are using ~>testing for it.

To use a branch in the SEMVER is ~branch.

https://dub.pm/package-format-json.html#version-specs


This was not causing me issues before. It worked until I added 
the v0.1.2 tag.


Dub says that there is an invalid semVer format, but I don't see how.

2021-11-10 Thread Ruby The Roobster via Digitalmars-d-learn
# Dub says that there is an invalid semVer format, but I don't 
see how.


[Relevant Package:](https://code.dlang.org/packages/dutils)

Recently, I added a new tag: v0.1.2 to the github repo, as well 
as v0.1.2-rc.1(this was later removed.) Now whenever updating the 
package, dub gives me this:


Branch ~master: Invalid SemVer format: testing.0.0
Branch ~testing: Invalid SemVer format: testing.0.0
Version 0.1.2: Invalid SemVer format: testing.0.0

Any explanation why this happens so I can fix it and avoid it in 
the future?


Note: This is a duplicate of a post on the dub forums, just in 
case nobody there sees it.




Re: Strange multithreading error

2021-10-29 Thread Ruby The Roobster via Digitalmars-d-learn
On Friday, 29 October 2021 at 23:32:38 UTC, Steven Schveighoffer 
wrote:
On Friday, 29 October 2021 at 22:02:53 UTC, Ruby The Roobster 
wrote:
I am currently writing a test program for a collision 
function, that involves multithreading so I can simultaneously 
check for collisions and move a skeleton at the same time.  
Because of this, I had to use ```shared``` objects.  The 
specific objects I was using were declared in a file called 
"skeleton.d."  In a function I wrote for moving the skeletons, 
it uses operator overloading, which produces the following 
output:


[...]


In order for a member function to be called on a shared object, 
the function has to be marked shared. Typically done like


```d
void opAssign(shared Skeleton rhs) shared
```

-Steve


Thank you, this solved my problem.


Strange multithreading error

2021-10-29 Thread Ruby The Roobster via Digitalmars-d-learn
I am currently writing a test program for a collision function, 
that involves multithreading so I can simultaneously check for 
collisions and move a skeleton at the same time.  Because of 
this, I had to use ```shared``` objects.  The specific objects I 
was using were declared in a file called "skeleton.d."  In a 
function I wrote for moving the skeletons, it uses operator 
overloading, which produces the following output:


```d
physics.d(85): Error: none of the `opOpAssign` overloads of 
`Point` are callable for `j` of type `shared(Point)`
physics.d(87): Error: none of the `opOpAssign` overloads of 
`Point` are callable for `k.start` of type `shared(Point)`
physics.d(88): Error: none of the `opOpAssign` overloads of 
`Point` are callable for `k.stop` of type `shared(Point)`
physics.d(90): Error: none of the `opOpAssign` overloads of 
`Point` are callable for `i.center` of type `shared(Point)`
physics.d(92): Error: none of the `opOpAssign` overloads of 
`Point` are callable for `tomove.center` of type `shared(Point)`
physics.d(112): Error: none of the `opOpAssign` overloads of 
`Point` are callable for `k` of type `shared(Point)`
physics.d(114): Error: none of the `opOpAssign` overloads of 
`Point` are callable for `j.start` of type `shared(Point)`
physics.d(115): Error: none of the `opOpAssign` overloads of 
`Point` are callable for `j.stop` of type `shared(Point)`
physics.d(117): Error: none of the `opOpAssign` overloads of 
`Point` are callable for `i.center` of type `shared(Point)`
physics.d(119): Error: none of the `opOpAssign` overloads of 
`Point` are callable for `ori.center` of type `shared(Point)`
physics.d(120): Error: none of the overloads of `opAssign` are 
callable using a `shared` object
skeleton.d(81):Candidates are: 
`skeleton.Skeleton.opAssign(Skeleton rhs)`
skeleton.d(88):
`skeleton.Skeleton.opAssign(shared(Skeleton) rhs)`
physics.d(136): Error: mixin `physics.move.__mov__general__!"n"` 
error instantiating

```

This is clearly wrong, as type ```Point``` is not the same as 
type ```Skeleton```.


For reference, here are the files:

test.d:
```d
import physics;
void main() {
Skeleton cube;
Face[] cubefaces;
cubefaces.length = 1;
	cubefaces[0].lines ~= Line([Point(0,0.25,0), Point(0,0.5,0), 
Point(0,0.75,0)], Point(0,0,0), Point(0,1,0));
	cubefaces[0].lines ~= Line([Point(0.25,0,0), Point(0.5,0,0), 
Point(0.75,0,0)], Point(0,0,0), Point(1,0,0));
	cubefaces[0].lines ~= Line([Point(1,0.25,0), Point(1,0.5,0), 
Point(1,0.75, 0)], Point(1,0,0), Point(1,1,0));
	cubefaces[0].lines ~= Line([Point(0.25,1,0), Point(0.5,1,0), 
Point(0.75,1,0)], Point(0,1,0), Point(1,1,0));

cubefaces[0].center = Point(0.5,0.5,0);
cube.faces = cubefaces.dup;
cube.center = Point(0.5,0.5,0);
auto cube2 = cube;
move(Point(99,0,0), 0, cast(shared(Skeleton))cube, 99);
import std.stdio;
import std.concurrency;
	spawn(, cast(shared(Skeleton))cube2, 
cast(shared(Skeleton))cube);

spawn(,Point(-99,0,0), 5, cast(shared(Skeleton))cube, 1);
bool b = receiveOnly!bool;
writeln(b);
}
void test1(shared ref Skeleton cube2, shared ref Skeleton cube) {
import std.concurrency;
	if(detectCollision(cast(shared(Skeleton[]))[cube2], 
cast(shared(Skeleton))cube, real.infinity))

send(ownerTid(), true);
}
```

skeleton.d:

```d
/*skeleton.d by Ruby The Roobster*/
/*Version 1.0 Release*/
/*Module for representing skeletons in the D Programming Language 
2.0*/
/*This program is free software: you can redistribute it and/or 
modify
it under the terms of the GNU General Public License as published 
by

the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see 
.*/

/** Copyright: 2021, Ruby The Roobster*/
/**Author: Ruby The Roobster, michaeleverest...@gmail.com*/
/**Date: October 1, 2021*/
/** License:  GPL-3.0*/
module skeleton;
/**Struct for representing a point.*/
public struct Point { //Point structure...
///Point.x is the 'x' coordinate of the point.
real x;
///Point.y is the 'y' coordinate of the point.
real y;
///Point.z is the 'z' coordinate of the point.
real z;
this(real x, real y, real z){
this.x = x;
this.y = y;
this.z = z;
}
void opAssign(Point rhs){
this.x = rhs.x;
this.y = rhs.y;
this.z = rhs.z;
}
void opAssign(shared Point rhs) {
this.x = rhs.x;
 

Re: Dub failing to use the linker correctly.

2021-10-22 Thread Ruby The Roobster via Digitalmars-d-learn
On Friday, 22 October 2021 at 21:57:02 UTC, Ruby The Roobster 
wrote:

On Friday, 22 October 2021 at 21:21:41 UTC, jfondren wrote:
On Friday, 22 October 2021 at 19:56:37 UTC, Ruby The Roobster 
wrote:
I have a simple vibe-d project built with dub.  Running the 
command, dub build --force returns the following output:


I'd start by running `dub -v build --force` instead, to see 
the exact commands that dub is running.


Nevermind.  I edited the source and it seems to work for some 
reason.


For better context, changing ``` shared static this()```  to ``` 
void main()``` fixed the problem.


Re: Dub failing to use the linker correctly.

2021-10-22 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 22 October 2021 at 21:21:41 UTC, jfondren wrote:
On Friday, 22 October 2021 at 19:56:37 UTC, Ruby The Roobster 
wrote:
I have a simple vibe-d project built with dub.  Running the 
command, dub build --force returns the following output:


I'd start by running `dub -v build --force` instead, to see the 
exact commands that dub is running.


Nevermind.  I edited the source and it seems to work for some 
reason.


Dub failing to use the linker correctly.

2021-10-22 Thread Ruby The Roobster via Digitalmars-d-learn
I have a simple vibe-d project built with dub.  Running the 
command, dub build --force returns the following output:


Performing "debug" build using 
E:\Programs\D\dmd2\windows\bin\dmd.exe for x86_64.

mir-linux-kernel 1.0.1: building configuration "library"...
taggedalgebraic 0.11.22: building configuration "library"...
eventcore 0.9.18: building configuration "winapi"...
stdx-allocator 2.77.5: building configuration "library"...
vibe-core 1.21.0: building configuration "winapi"...
vibe-d:crypto 0.9.4: building configuration "library"...
vibe-d:utils 0.9.4: building configuration "library"...
vibe-d:data 0.9.4: building configuration "library"...
diet-ng 1.8.0: building configuration "library"...
vibe-d:stream 0.9.4: building configuration "library"...
vibe-d:textfilter 0.9.4: building configuration "library"...
vibe-d:inet 0.9.4: building configuration "library"...
vibe-d:tls 0.9.4: building configuration "openssl-mscoff"...
vibe-d:http 0.9.4: building configuration "library"...
vibe-d:mail 0.9.4: building configuration "library"...
vibe-d:mongodb 0.9.4: building configuration "library"...
vibe-d:redis 0.9.4: building configuration "library"...
vibe-d:web 0.9.4: building configuration "library"...
vibe-d 0.9.4: building configuration "vibe-core"...
web ~master: building configuration "application"...
Compiling Diet HTML template caccount.dt...
Linking...
lld-link: error: subsystem must be defined
Error: linker exited with status 1


Does anybody know why this happens?  I am on the latest version 
of the dmd compiler(2.098.0.)  Thanks in advance.


Linker error

2021-10-11 Thread Ruby The Roobster via Digitalmars-d-learn

So, I have the following two files:

skeleton.d:
```d
/*skeleton.d by Ruby The Roobster*/
/*Version 1.0 Release*/
/*Module for representing skeletons in the D Programming Language 
2.0*/
/*This program is free software: you can redistribute it and/or 
modify
it under the terms of the GNU General Public License as published 
by

the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see 
.*/

/** Copyright: 2021, Ruby The Roobster*/
/**Author: Ruby The Roobster, michaeleverest...@gmail.com*/
/**Date: October 1, 2021*/
/** License:  GPL-3.0*/
module dutils.skeleton;
/**Struct for representing a point.*/
public struct Point { //Point structure...
///Point.x is the 'x' coordinate of the point.
real x;
///Point.y is the 'y' coordinate of the point.
real y;
///Point.z is the 'z' coordinate of the point.
real z;
void opAssign(Point rhs){
this.x = rhs.x;
this.y = rhs.y;
this.z = rhs.z;
}
void opOpAssign(string op)(Point rhs)   {
mixin("this.x " ~ op ~ "= rhs.x;");
mixin("this.y " ~ op ~ "= rhs.y;");
mixin("this.z " ~ op ~ "= rhs.z;");
}
}
/**Struct for representing a face of a skeleton that is made out 
of lines.*/

public struct Face  { //Face(of a 3D shape) structure...
	///Face.lines is an array of all the lines that connect to form 
the face.

Line[] lines;
///Face.center is the center point of the face.
Point center;
void opAssign(Face rhs) {
this.lines.length = rhs.lines.length;
foreach(i;0 .. this.lines.length)   {
this.lines[i] = rhs.lines[i];
}
}
}
/**Struct for representing a 3D skeleton.*/
public struct Skeleton  { //Skeleton of a 3D structure...
	///Skeleton.faces is an array of the faces that make up the 
Skeleton.

Face[] faces;
///Skeleton.center is the center point of the skeleton.
Point center;
void opAssign(Skeleton rhs) {
this.faces.length = rhs.faces.length;
foreach(i;0 .. this.faces.length)   {
this.faces[i] = rhs.faces[i];
}
this.center = rhs.center;
}
}

/**Struct for representing a line composed of at least a starting 
point and an end point.

  *Notes:
  *This struct doesn't check to make sure that the line made is 
an actual line and assumes the user knows what they are doing.

*/
public struct Line  { //Line struct...
	///Line.mid_points is an array containing all of the points that 
are neither start nor end points.

Point[] mid_points;
///Line.start is the start point of the line.
Point start;
///Line.end is the end point of the line.
Point stop;
void opAssign(Line rhs) {
this.start = rhs.start;
this.stop = rhs.stop;
this.mid_points.length = rhs.mid_points.length;
foreach(i;0 .. this.mid_points.length)  {
this.mid_points[i] = rhs.mid_points[i];
}
}
}
```

physics.d:
```d
/*physics.d by Ruby The Roobster*/
/*Version 0.35 testing*/
/*Module for basic physics in the D Programming Language 2.0*/
/*This program is free software: you can redistribute it and/or 
modify
it under the terms of the GNU General Public License as published 
by

the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see 
.*/

/** Copyright: 2021, Ruby The Roobster*/
/**Author: Ruby The Roobster, michaeleverest...@gmail.com*/
/**Date: October 11, 2021*/
/** License: GPL-3.0*/
module dutils.physics;
public import dutils.skeleton;

package mixin template move__() {
	pragma(inline) package void mv(Point moveby, ref Skeleton 
tomove)	{

foreach(i;tomove.faces) {
foreach(k;i.lines)  {
foreach(j;k.mid_points) {
j += moveby;
}
k.start += 

Re: foreach(ubyte j;0 .. num) is bugging out

2021-09-22 Thread Ruby The Roobster via Digitalmars-d-learn

On Thursday, 23 September 2021 at 00:17:49 UTC, jfondren wrote:
On Thursday, 23 September 2021 at 00:06:42 UTC, Ruby The 
Roobster wrote:

So, I have the following function:
```d
	writeln(tempcolor); //For this matter, the program 
correctly reports tempcolor as 1...
		for(ubyte j = 0;j < tempcolor; j++ /*trying ++j has same 
effect*/ )	{ //tempcolor is 1, yet this sloop gets executed 
twice...

writeln();
			posfunc(ftext, main, exp, temp, i, j, points , x);  
  //Orignally foreach loop, but 
switching to for loop has same effect...

}
```


Needs more print in your print debugging:

```d
writeln("tempcolor: ", tempcolor);
...
writeln("in tempcolor with j: ", j);
```

output:

```
tempcolor: 1
in tempcolor with j: 0
...
... numbers
...
tempcolor: 0
tempcolor: 0
tempcolor: 0
tempcolor: 0
tempcolor: 0
tempcolor: 0
tempcolor: 0
tempcolor: 0
tempcolor: 0
tempcolor: 1
in tempcolor with j: 0
```



I figured out something weird. The variable 'i' is passed by 
reference, yet the variable 'i' of the loop isn't being 
incremented by posfunc.  I assume foreach creates a new i 
variable at the start of each new loop. Swapping the original 
loop with a while loop fixes the problem.  Thank you very much 
for trying to help.




foreach(ubyte j;0 .. num) is bugging out

2021-09-22 Thread Ruby The Roobster via Digitalmars-d-learn

So, I have the following function:
```d
	public Sprite ReadSpriteFromFile(immutable(char)[] filename)	{ 
//Reads a sprite in my made up .spr format(trash, why does this 
even exist)

ubyte[] ftext;
Color[] colors;
Point[][] points;
import std.file;
import std.stdio;
ftext = cast(ubyte[])read(filename);
foreach(i;0 .. cast(uint)ftext.length)  { //Parse the file...
long main;
short exp;
uint x = 0;
++colors.length;
++points.length;
colors[x].r = ftext[i]; //Set r color...
++i;
colors[x].g = ftext[i];
++i;
colors[x].b = ftext[i];
++i;
ubyte tempcolor = ftext[i];
++i;
long temp;
	writeln(tempcolor); //For this matter, the program 
correctly reports tempcolor as 1...
		for(ubyte j = 0;j < tempcolor; j++ /*trying ++j has same 
effect*/ )	{ //tempcolor is 1, yet this sloop gets executed 
twice...

writeln();
			posfunc(ftext, main, exp, temp, i, j, points , x); 
   //Orignally foreach loop, but 
switching to for loop has same effect...

}
}
return Sprite(colors, points);
}
```

Here is the rest of the source:

```d
/*sprite.d by Ruby The Roobster*/
/*Version 0.3.5 Release*/
/*Last Update: 08/23/2021*/
/*Module for sprites in the D Programming Language 2.0*/
module dutils.sprite;
import skeleton : Point;

version(USE_BUILT_IN_SPRITES)	{ //Use built in sprites(garbage 
.spr format coded by me, that still needs an editor: Editor using 
GtKD for .spr comes out later this year, if I can get myself to 
do it)...

public struct Color {
ubyte r = 0;
ubyte g = 0;
ubyte b = 0;
void opAssign(Color rhs){
this.r = rhs.r;
this.g = rhs.g;
this.b = rhs.b;
}
}

public struct Sprite{
Color[] colors;
Point[][] points;
invariant() {
			assert(colors.length == points.length, "Assertion failure: 
Sprite.colors.length and Sprite.points.length must always be 
equal...");

}
void opAssign(Sprite rhs)   {
this.colors.length = rhs.colors.length;
this.points.length = rhs.points.length;
foreach(i;0 .. this.colors.length)  {
this.colors[i] = rhs.colors[i];
}
foreach(i;0 .. this.points.length)  {
this.points[i].length = rhs.points[i].length;
foreach(j;0 .. this.points[i].length)   {
this.points[i][j] = rhs.points[i][j];
}
}
}
		package void ChangeLengths(uint c)	{ //Change both lengths so 
invariant doesn't get triggered...

this.colors.length = c;
this.points.length = c;
}
}

//ReadSpriteFromFile was here...

	package void posfunc(const ubyte[] ftext, ref long main, ref 
short exp, ref long temp, ref uint i, const ubyte j, ref 
Point[][] points, ref uint x)	{

++points[x].length;
import std.stdio;
writeln(__LINE__);
foreach(z;0 .. 3)   {
short shift = 56;
main = ftext[i];
main <<= shift;
++i;
shift -= 8;
while(shift >= 0){
writeln(shift);
writeln(i);
temp = ftext[i];
main = (main <= (-0)) ? (main - temp) : (main + 
temp);
++i;
shift -= 8;
}
exp = ftext[i];
exp <<= 8;
++i;
exp += ftext[i];
if(i+1 == ftext.length) {
}
else{
++i;
}
switch(z)   {
case 0:
points[x][j].x = (main * 10^^exp);
break;
case 1:
  

Re: std.stdio.File is throwing with the message of: "Access Violation"

2021-08-21 Thread Ruby The Roobster via Digitalmars-d-learn

On Saturday, 21 August 2021 at 06:08:17 UTC, evilrat wrote:
First parameter for CreateWindow should be window class string 
that you used in



wndclass.lpszClassName = appName.toUTF16z;


Fix:
wndclass.lpszClassName = "Test"; //May need casting...


Re: std.stdio.File is throwing with the message of: "Access Violation"

2021-08-21 Thread Ruby The Roobster via Digitalmars-d-learn
On Saturday, 21 August 2021 at 23:50:08 UTC, Ruby The Roobster 
wrote:

On Saturday, 21 August 2021 at 06:08:17 UTC, evilrat wrote:
First parameter for CreateWindow should be window class string 
that you used in



wndclass.lpszClassName = appName.toUTF16z;


Fix:
wndclass.lpszClassName = "Test"; //May need casting...


Anyways, this isn't an issue anymore. I'm just not gonna use 
Win32 API.


Re: std.stdio.File is throwing with the message of: "Access Violation"

2021-08-20 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 20 August 2021 at 05:22:20 UTC, nov wrote:

On Friday, 20 August 2021 at 04:27:34 UTC, Jesse Phillips wrote:
For me, this code generates the Message Box. Does this happen 
for you?


no errors
https://run.dlang.io/is/4tlm3p
```D
void main() {
try {
   import std.stdio: File;
   File file = File(__FILE__,"r");
   file.close();
   }
   catch(Throwable e) {
   import std.stdio: writefln;
   writefln("err=%s", e.msg);
   }
}
```


This is not a console App. It's a Win32 one. Also, it turns out 
to be a bug.  If I compile my application(with a couple of 
'imports' removed under dmd 2.060), it works just fine, with no 
Access Violation Error.  Try the following on dmd 2.060:

```d
import core.runtime;

pragma(lib, "gdi32.lib");

import core.sys.windows.windows;
import std.stdio;

extern(Windows)
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR 
lpCmdLine, int iCmdShow)

{
int result;

try
{
Runtime.initialize();
result = myWinMain(hInstance, hPrevInstance, lpCmdLine, 
iCmdShow);

Runtime.terminate();
}
catch(Throwable o)
{
MessageBoxA(null, o.msg, "Error", MB_OK | MB_ICONERROR);
result = 1;
}

return result;
}

int myWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR 
lpCmdLine, int iCmdShow)

{
HWND hwnd;
MSG  msg;
WNDCLASSA wndclass;

wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc   = 
wndclass.cbClsExtra= 0;
wndclass.cbWndExtra= 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIconA(NULL, IDI_APPLICATION);
wndclass.hCursor   = LoadCursorA(NULL, IDC_ARROW);
wndclass.hbrBackground = 
cast(HBRUSH)GetStockObject(WHITE_BRUSH);

wndclass.lpszMenuName  = NULL;
wndclass.lpszClassName = appName.toUTF16z;

if(!RegisterClassA())
{

return 0;
}

hwnd = CreateWindowA( "Test",
 "Test",
 WS_OVERLAPPEDWINDOW,
 CW_USEDEFAULT,
 CW_USEDEFAULT,
 CW_USEDEFAULT,
 CW_USEDEFAULT,
 NULL,
 NULL,
 hInstance,
 NULL);

ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);

while (GetMessageA(, NULL, 0, 0))
{
TranslateMessageA();
DispatchMessage();
}

return msg.wParam;
}

extern(Windows)
LRESULT WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM 
lParam) nothrow

{
switch (message)
{
case WM_CREATE:
try
{
   File file = File("test","r");
   file.close();
}
catch(Throwable e)
{
   MessageBoxA(null, "Error", 
cast(char)[])e.msg,MB_OK | ICON_ERROR);

   PostQuitMessage(1);
}
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;

default:
}

return DefWindowProcA(hwnd, message, wParam, lParam);
}
```
Sorry if I misnamed(forgot an 'A' at the end of the function 
name) something in above code.


Now, edit above code(provided that it has been fixed if 
necessary) by adding:

```d
import core.sys.windows.wingdi;
```
And remove:
```d
import core.sys.windows.windows;
```
And compile it with dmd 2.080.0 or later.

See the results(what matters is if you get the "Access Violation" 
error or not, everything else is irrelevant).


Re: std.stdio.File is throwing with the message of: "Access Violation"

2021-08-19 Thread Ruby The Roobster via Digitalmars-d-learn

On Thursday, 19 August 2021 at 03:25:31 UTC, Jesse Phillips wrote:
 tell me what went wrong.  I am using DMD 2.097.2


This is an error message you'll get from Windows if the file is 
locked (open by another application).
Odd.  This works if I use a console application. It also works if 
I use C standard library functions. The file is always closed.  I 
think it's just Win32 being buggy.  For example, create a base 
Win32 application in D.  Then put this in WM_CREATE:


```d
case WM_CREATE: //Executed on creation of the window...
   try   {
  import core.stdc.stdio;
  FILE* file;
  file = fopen("file","r"); //NOTE: Replace 'file' with any 
file on the system...

  fclose(file);
   }
   catch(Throwable e)   {
  MessageBoxA(null,cast(const(char)*)e.msg,"ERROR",MB_OK | 
MB_ICONERROR);

   }
```
This works, no Message Box should be displayed(Note: use 2.097.2, 
this is the version I am using, and I don't know about if this 
same bug happens on earlier versions).


Now do this:

```d
case WM_CREATE:
   try   {
  import std.stdio;
  File file = File("file","r");  //NOTE: Again, replace 
'file' with any file on the system...

  file.close();
   }
   catch(Throwable e)   {
  MessageBoxA(null, cast(const(char)*)e.msg, "ERROR", MB_OK | 
MB_ICONERROR);

}
```

For me, this code generates the Message Box. Does this happen for 
you?


Re: std.stdio.File is throwing with the message of: "Access Violation"

2021-08-18 Thread Ruby The Roobster via Digitalmars-d-learn

On Wednesday, 18 August 2021 at 17:54:47 UTC, Paul Backus wrote:
On Wednesday, 18 August 2021 at 17:42:53 UTC, Ruby The Roobster 
wrote:
  Output(Given to me by a message box that display's 
Throwable.msg in it's body):

 Access Violation

  Is this a bug, or me being stupid? If it's the latter, than 
tell me what went wrong.  I am using DMD 2.097.2


It's a bug in your code. "Access Violation" means your program 
tried to access out-of-bounds memory.


In addition, I figured out that if I moved the code outside of 
WndProc() everything worked fine, so I think it's a Win32 issue.


Re: std.stdio.File is throwing with the message of: "Access Violation"

2021-08-18 Thread Ruby The Roobster via Digitalmars-d-learn

On Wednesday, 18 August 2021 at 17:54:47 UTC, Paul Backus wrote:
On Wednesday, 18 August 2021 at 17:42:53 UTC, Ruby The Roobster 
wrote:
  Output(Given to me by a message box that display's 
Throwable.msg in it's body):

 Access Violation

  Is this a bug, or me being stupid? If it's the latter, than 
tell me what went wrong.  I am using DMD 2.097.2


It's a bug in your code. "Access Violation" means your program 
tried to access out-of-bounds memory.


When I removed those two lines of code, the program ran perfectly 
without displaying any error or throwing any exception...


std.stdio.File is throwing with the message of: "Access Violation"

2021-08-18 Thread Ruby The Roobster via Digitalmars-d-learn
  All I did was try to access a file with a self-made library.  
It didn't work.  I tried again directly from the main file. This 
is the code:


  ```d
  File file = 
File("E:\\Users\\User\\Desktop\\dutils\\test.spr","r"); //This 
file exists on my system, so it should work...

  file.close();
  ```

  Output(Given to me by a message box that display's 
Throwable.msg in it's body):

 Access Violation

  Is this a bug, or me being stupid? If it's the latter, than 
tell me what went wrong.  I am using DMD 2.097.2


Re: Help with Win32: PostQuitMessage(0) doesn't post WM_QUIT apparently, because the message loop is not exited.

2021-08-13 Thread Ruby The Roobster via Digitalmars-d-learn
On Friday, 13 August 2021 at 21:10:38 UTC, Steven Schveighoffer 
wrote:

On 8/13/21 3:59 PM, Mike Parker wrote:
On Friday, 13 August 2021 at 16:18:06 UTC, Ruby The Roobster 
wrote:

...

...

...


Well, subtracting the length doesn't do much, you aren't 
actually accessing the array block, you are just changing the 
reference (which lives in thread-local storage). I kind of feel 
like the whole entity table thing is not correct anyway. Did 
you (Mike) also comment out the `did` call? Because that looks 
more suspicious to me. What it is doing is going through all 
the entities from the removed one on and setting their id to 1 
less. HOWEVER, it's not actually *moving* the entities down in 
the array.


However, you will NEVER have an entity be destroyed, because 
there is always a reference to it in the table! They will only 
get destroyed at the end, via `terminate` where things are 
destroyed deterministically.



-Steve



Okay. I removed the destructors and the 'did' function. Instead 
of those, I created a destruct(Entity op) function that works 
without causing an error.  The entitytable array is for the 
purpose of it being easier to search by id, because the index 
used to access the array is the same as the id. It's also(IMO) 
easier on my end to have every Entity object in a single array.





Re: Help with Win32: PostQuitMessage(0) doesn't post WM_QUIT apparently, because the message loop is not exited.

2021-08-13 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 13 August 2021 at 19:59:46 UTC, Mike Parker wrote:
You aren't supposed to be manipulating GC-managed memory via 
class destructors. You can not rely on that memory being valid 
at the time that it's accessed in the destructor---the object 
may already have been destroyed. Nondeterministic destruction 
is the price you pay for letting the GC manager your object 
memory.


Of course, in this case, the problem will only crop up at 
termination since the array is declared at module scope so will 
be live up until the GC shuts down. But still, not something 
you should be doing.

...


Thank you very much.  The program runs successfully now.


Re: Help with Win32: PostQuitMessage(0) doesn't post WM_QUIT apparently, because the message loop is not exited.

2021-08-13 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 13 August 2021 at 03:05:22 UTC, Mike Parker wrote:
On Friday, 13 August 2021 at 00:30:59 UTC, Ruby The Roobster 
wrote:




When I run the program and close the window, the program still 
runs in background mode.  I don't know why this happens nor 
how to fix it.  Does anybody know what's going on?


frame beat me to it, but it may well be that you're getting -1. 
[The documentation][1] says that a window that has already been 
destroyed will result in the `hWnd` parameter being invalid, 
which will cause the function to return -1.



[1]: 
https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessage#return-value


After rewriting the program, I figured out that the bug was still 
there. Here is the function that causes it:

```d
public class Entity {
package:
ulong id;
wchar[] name;
static ulong nextid;
Point centre;
Skeleton skeleton;
public:
		this(ulong id, inout(wchar)[] name,Point centre, Skeleton 
skeleton)	{
			assert(init == true, "Error: dutils.entity has not been 
initialized yet. Call dutils.entity.initialize() to initialize 
the library.");

this.id = id;
this.name.length = name.length;
for(uint i = 0; i < name.length; i++){
this.name[i] = name[i];
}
this.nextid = this.id + 1;
this.centre = centre;
if(!skeleton.init)  {
this.skeleton = skeleton;
}
entitytable.length +=1;
entitytable[cast(uint)id] = this;
}

~this() {
entitytable.length -= 1;
this.nextid -=1;
did(cast(uint)this.id);
}

debug immutable(char)[] f() @property   {
import std.format : format;
			return format("ID: %s, Name: %s, NextID: %s, Centre: %s, 
Skeleton: %s", this.id, this.name, this.nextid, this.centre, 
this.skeleton);

}

ulong Id() @property{
return id;
}
}
```

Context for this: I am creating a module of my  own, and this is 
a class contained in the module.  You will notice that after 
calling this class' constructor anywhere in a Win32 API program, 
that the program doesn't close after the window is closed.


Here are the files:

entity.d:
```d
module dutils.entity;

debug { package import core.sys.windows.winuser; } //For 
MessageBoxA in debug messages...


public struct Skeleton  {
public Face[] faces;
package bool init = false;
public this(Face[] faces)   {
this.faces.length = faces.length;
for(uint i = 0; i < faces.length; i++)   {
this.faces[i] = faces[i];
}
}
package this(bool init) {
this.init = init;
}
public void opAssign(Skeleton rhs)  {
this.faces.length = rhs.faces.length;
for(uint i; i < rhs.faces.length; i++)   {
this.faces[i] = rhs.faces[i];
}
this.init = rhs.init;
}
}

public struct Face  {
Point[] points;
Point centre;
void opAssign(Face rhs) {
this.points.length = rhs.points.length;
for(uint i = 0; i < rhs.points.length; i++)  {
this.points[i] = rhs.points[i];
}
this.centre = rhs.centre;
}
}

public struct Point {
real x;
real y;
real z;
void opAssign(Point rhs){
this.x = rhs.x;
this.y = rhs.y;
this.z = rhs.z;
}
}

public class Entity {
package:
ulong id;
wchar[] name;
static ulong nextid;
Point centre;
Skeleton skeleton;
public:
		this(ulong id, inout(wchar)[] name,Point centre, Skeleton 
skeleton)	{
			assert(init == true, "Error: dutils.entity has not been 
initialized yet. Call dutils.entity.initialize() to initialize 
the library.");

this.id = id;
this.name.length = name.length;
for(uint i = 0; i < name.length; i++){
this.name[i] = name[i];
}
this.nextid = this.id + 1;
this.centre = centre;
if(!skeleton.init) 

Re: Help with Win32: PostQuitMessage(0) doesn't post WM_QUIT apparently, because the message loop is not exited.

2021-08-13 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 13 August 2021 at 03:05:22 UTC, Mike Parker wrote:
On Friday, 13 August 2021 at 00:30:59 UTC, Ruby The Roobster 
wrote:




When I run the program and close the window, the program still 
runs in background mode.  I don't know why this happens nor 
how to fix it.  Does anybody know what's going on?


frame beat me to it, but it may well be that you're getting -1. 
[The documentation][1] says that a window that has already been 
destroyed will result in the `hWnd` parameter being invalid, 
which will cause the function to return -1.



[1]: 
https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessage#return-value


Nevermind. I am just redoing the LRESULT function. Seems to work 
now.


Re: Help with Win32: PostQuitMessage(0) doesn't post WM_QUIT apparently, because the message loop is not exited.

2021-08-13 Thread Ruby The Roobster via Digitalmars-d-learn

On Friday, 13 August 2021 at 03:05:22 UTC, Mike Parker wrote:
On Friday, 13 August 2021 at 00:30:59 UTC, Ruby The Roobster 
wrote:




When I run the program and close the window, the program still 
runs in background mode.  I don't know why this happens nor 
how to fix it.  Does anybody know what's going on?


frame beat me to it, but it may well be that you're getting -1. 
[The documentation][1] says that a window that has already been 
destroyed will result in the `hWnd` parameter being invalid, 
which will cause the function to return -1.



[1]: 
https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessage#return-value


So I edited the message loop:
```d
while((b = GetMessage(,hwnd,0,0)) != 0) {
if(exit || b == -1) {
return msg.wParam;
}
TranslateMessage();
DispatchMessage();
}
```
And some of the WndProc:
```d
extern(Windows)
LRESULT WndProc(HWND hwnd, UINT msg, WPARAM wparam, 
LPARAM lparam) nothrow	{

switch(msg) {
case WM_CREATE:
//...
return 0;
break;
case WM_CLOSE:
DestroyWindow(hwnd);
try {
entity.terminate();
exit = true;
}
catch(Throwable e){
}
break;
case WM_DESTROY:
try {
entity.terminate();
exit = true;
}
catch(Throwable e)  {
PostQuitMessage(1);
}
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd,msg,wparam,lparam);
}
return 0;
}
```

It still produces the same result(the program never exits), so it 
doesn't look like GetMessage() is returning -1...


Help with Win32: PostQuitMessage(0) doesn't post WM_QUIT apparently, because the message loop is not exited.

2021-08-12 Thread Ruby The Roobster via Digitalmars-d-learn

Here is the message loop:
```d
while(GetMessage(, hwnd,0,0))   {
   if(msg.message == WM_QUIT)
  break;
   TranslateMessage();
   DispatchMessage();
}
```
The WndProc(LRESULT CALLBACK):
```d
extern(Windows)
LRESULT WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM 
lparam) nothrow	{

switch(msg) {
case WM_CREATE:
//...
return 0;
break;
case WM_DESTROY:
try {
entity.terminate();
}
catch(Throwable e)  {
PostQuitMessage(1);
}
PostQuitMessage(0);
break;
default:
}
return DefWindowProc(hwnd,msg,wparam,lparam);
}
```

When I run the program and close the window, the program still 
runs in background mode.  I don't know why this happens nor how 
to fix it.  Does anybody know what's going on?


Re: Range Error

2021-04-12 Thread Ruby The Roobster via Digitalmars-d-learn
On Monday, 12 April 2021 at 01:22:12 UTC, Steven Schveighoffer 
wrote:

On 4/11/21 4:41 PM, Bastiaan Veelo wrote:
On Sunday, 11 April 2021 at 19:45:30 UTC, Ruby The Roobster 
wrote:

What am I doing wrong here? Is it the 'for' loop?


Yes, there is a `7` where there should be an `i` on this line:
```d
   for(int i=7;7>=0;i--)
```
This will go on forever, so you get a range error as soon as 
`i < 0`.

...


I fixed the code now. It works. Thanks for your help.


Re: Range Error

2021-04-12 Thread Ruby The Roobster via Digitalmars-d-learn

On Sunday, 11 April 2021 at 20:41:35 UTC, Bastiaan Veelo wrote:
On Sunday, 11 April 2021 at 19:45:30 UTC, Ruby The Roobster 
wrote:

What am I doing wrong here? Is it the 'for' loop?


Yes, there is a `7` where there should be an `i` on this line:
```d
   for(int i=7;7>=0;i--)
```
This will go on forever, so you get a range error as soon as `i 
< 0`.


—Bastiaan.


I have fixed this.


Re: Range Error

2021-04-11 Thread Ruby The Roobster via Digitalmars-d-learn

On Sunday, 11 April 2021 at 19:45:30 UTC, Ruby The Roobster wrote:

What am I doing wrong here? Is it the 'for' loop?
Nevermind. I messed up what line it was. It was actually this 
line:



```d
square[i][j] = new Square(Color.none, sColor.white);
```




  1   2   >