Re: Deprecation: foreach: loop index implicitly converted from size_t to int
A horrible alternative would be to use `alias` on `size_t` to make up a new pseudo-type that is more aligned with the code logic. ``` alias integer = size_t; import std.stdio : writefln; void main() { auto arr = [ [5, 15], // 20 [2, 3, 2, 3], // 10 [3, 6, 2, 9], // 20 ]; foreach (integer i, row; arr) { double total = 0.0; foreach (e; row) total += e; auto avg = total / row.length; writefln("AVG [row=%d]: %.2f", i, avg); } } ```
Re: Deprecation: foreach: loop index implicitly converted from size_t to int
Well all these proposals to `int` index like `size_t` and `const typeof(arr.length)` are cryptic and less readable and less straightforward in comparison to how it used to be. Feels like horrible decision if the language is suppose to be somewhat futureproof. The `int` was simple, straighforward and great. These suggestions feel like some `C++` all over again.
Re: Deprecation: foreach: loop index implicitly converted from size_t to int
On Friday, 3 May 2024 at 13:18:02 UTC, user1234 wrote: On Friday, 3 May 2024 at 10:50:03 UTC, BoQsc wrote: Why am I forced to visit this D Lang thread, why this deprecation warning still appears in my console window in the latest version of DMD. Does not make any sense from the developer's perspective to show this warning and pollute the already polluted logging entries of the compiler. How am I suppose to program anything effectively if half of the screen are some nonsensical deprecation warnings without guidance or sane explanations. This is not better ``` foreach (i, row; arr) ``` than ``` foreach (int i, row; arr) ``` Hides the datatype and makes the D language appear in-explicit and annoying. What is this language becoming. A completely weak typed language or something? I would use JavaScript if I would want that. How are we suppose to make whole sane Operating Systems with such syntaxes. Do everyone just enjoy having bugs with some implicit size_t, or do everyone just enjoy deprecation warnings in their logging systems when there are way more important problems to solve, that are actually project related. **You can specify the index type, just choose the right one.** For now there's a deprecation message but after some while you'll get a proper error message, e.g _"index type for arr must be of type T because arr.length type is T"_. What's is happening now is to help people updating their code and prevent abrupt breakages. So how would you update this example, what is the right index type here to choose? ``` import std.stdio : writefln; void main() { auto arr = [ [5, 15], // 20 [2, 3, 2, 3], // 10 [3, 6, 2, 9], // 20 ]; foreach (i, row; arr) { double total = 0.0; foreach (e; row) total += e; auto avg = total / row.length; writefln("AVG [row=%d]: %.2f", i, avg); } } ``` Example taken from https://tour.dlang.org/tour/en/basics/foreach
Re: Deprecation: foreach: loop index implicitly converted from size_t to int
Why am I forced to visit this D Lang thread, why this deprecation warning still appears in my console window in the latest version of DMD. Does not make any sense from the developer's perspective to show this warning and pollute the already polluted logging entries of the compiler. How am I suppose to program anything effectively if half of the screen are some nonsensical deprecation warnings without guidance or sane explanations. This is not better ``` foreach (i, row; arr) ``` than ``` foreach (int i, row; arr) ``` Hides the datatype and makes the D language appear in-explicit and annoying. What is this language becoming. A completely weak typed language or something? I would use JavaScript if I would want that. How are we suppose to make whole sane Operating Systems with such syntaxes. Do everyone just enjoy having bugs with some implicit size_t, or do everyone just enjoy deprecation warnings in their logging systems when there are way more important problems to solve, that are actually project related.
How to add a character literal to a string without ~ operator?
I'm looking for more readable standard function to add a **character** literal to a **string**. The `~` operator is clearly not great while reading a source code. I'm not here to discuss that. I'm looking for a function inside standard library. The function should be straightforward, up to two words. Here is what I expect from a programming language: Pseudo example: ``` import std; void main(){ string word = hello; join(word, 'f', " ", "World"); writeln(word); // output: hellof World } ```
Re: Reading .txt File into String and Matching with RegEx
Matches function declarations and captures function names from `.d` Source Code file **regexcapture.d** ``` import std.stdio : writeln; import std.regex : matchAll, regex; import std.file : read; void main(){ string input = cast(string)read("sourcecode.d"); foreach(match; matchAll(input, regex(r"\b([A-Za-z_]\w*)\s*\([^)]*\)\s*", "g"))){ writeln(match.captures()[1]); } } ``` **Input(sourcecode.d)** ``` BOOL WaitNamedPipeA(LPCSTR, DWORD); BOOL WaitNamedPipeW(LPCWSTR, DWORD); BOOL WinLoadTrustProvider(GUID*); BOOL WriteFile(HANDLE, PCVOID, DWORD, PDWORD, LPOVERLAPPED); BOOL WriteFileEx(HANDLE, PCVOID, DWORD, LPOVERLAPPED, LPOVERLAPPED_COMPLETION_ROUTINE); BOOL WritePrivateProfileSectionA(LPCSTR, LPCSTR, LPCSTR); BOOL WritePrivateProfileSectionW(LPCWSTR, LPCWSTR, LPCWSTR); BOOL WritePrivateProfileStringA(LPCSTR, LPCSTR, LPCSTR, LPCSTR); BOOL WritePrivateProfileStringW(LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR); ``` Note: This small input excerpt was taken from a real source code file: https://github.com/dlang/dmd/blob/master/druntime/src/core/sys/windows/winbase.d#L2069-L2078 **Output** ``` C:\Users\Windows10\Documents\matchtest>rdmd regexcapture.d WaitNamedPipeA WaitNamedPipeW WinLoadTrustProvider WriteFile WriteFileEx WritePrivateProfileSectionA WritePrivateProfileSectionW WritePrivateProfileStringA WritePrivateProfileStringW ``` --- Relevant links: https://dlang.org/phobos/std_regex.html#regex https://dlang.org/phobos/std_regex.html#.RegexMatch.captures https://regexr.com/
Re: Reading .txt File into String and Matching with RegEx
On Monday, 11 December 2023 at 05:18:45 UTC, thinkunix wrote: BoQsc via Digitalmars-d-learn wrote: This is something I've searched on the forum and couldn't find exact answer. TLDR: `r"^."` is matching the very first two character in the `input` string. Don't you need two dots to match two characters? Each dot being the regex to match a single character, so `r"^.."` instead of `r"^."` to get the first two characters. When I run your program (on linux with rdmd from DMD 2.106.0), I get: [["H"]] Yeah, that's true, my mistake, forgot to update the snippet and note properly. Thanks! ``` import std.stdio : writeln; import std.regex : matchAll; import std.file : read; void main(){ string input = cast(string)read("example.txt"); writeln(matchAll(input, r"^..")); } ```
Reading .txt File into String and Matching with RegEx
This is something I've searched on the forum and couldn't find exact answer. TLDR: `r"^."` is matching the very first two character in the `input` string. **matchtest.d** ``` import std.stdio : writeln; import std.regex : matchAll; import std.file : read; void main(){ string input = cast(string)read("example.txt"); writeln(matchAll(input, r"^.")); } ``` **Input(example.txt)** ``` HelloWorld ``` **Output** ``` rdmd matchtest.d [["He"]] ``` https://dlang.org/phobos/std_regex.html#matchAll https://dlang.org/library/std/file/read.html
Re: D Snippet: Reading a file to standard output on Windows Operating System. (FileScan.d)
`switch` statement to match a text line While outputing to the standard stream, it is also possible to use `switch` statement to **match a text line to a text line in a file.** I personally think it improve readability and maintainability in some applications. ``` import std; void main(){ foreach (line; File("example.txt").byLine(No.keepTerminator, "\r\n")){ switch(line) { case " HelloWorld" : writeln("|"~line~"|"); writeln("^This Line is here."); break; default : writeln("|"~line~"|"); } } } ``` Reading file, matching line, changing the line, outputting to both: to a standard stream and another file; line by line In this snippet, we are not only reading a file, editing its output and outputting to the standard output stream, but also try to save changes on another file: filling it with the edited output. ``` import std; void main(){ File edit = File("example2.txt", "w"); foreach (line; File("example.txt").byLine(No.keepTerminator, "\r\n")){ switch(line) { case " HelloWorld": edit.write("RandomWord\n"); writeln("|"~"RandomWord"~"|"); break; default : edit.write(line ~ "\n"); writeln("|" ~ line ~ "|"); } } edit.close; } ``` **Inputs:** **Example.txt** ``` test s HelloWorld t ff ``` **Outputs:** **stdout:** ``` |test| | s| | | |RandomWord| |t| |ff| ``` **Example2.txt** ``` test s RandomWord t ff ```
Re: D Snippet: Reading a file to standard output on Windows Operating System. (FileScan.d)
On Wednesday, 6 December 2023 at 14:56:50 UTC, BoQsc wrote: As of recent observation the `line` in the previous implementation seem to recognise **\r** as default terminator. Making `writeln("|" ~ line ~ "|");` not possible. By correcting terminator and disabling it on `byLine` function it is possible to achieve following output to standard stream: **Output** ``` |test| | s| | | | HelloWorld| ^This Line is here. |t| |ff| ``` **Input (example.txt)** ``` test s HelloWorld t ff ``` **Source code** ``` import std; void main(){ foreach (line; File("example.txt").byLine(No.keepTerminator, "\r\n")){ writeln("|"~line~"|"); if (line == " HelloWorld") { writeln("^This Line is here."); } } } ``` [`strip();`](https://dlang.org/library/std/string/strip.html) can be used to achieve same result as `No.keepTerminator, "\r\n"` of `.byLine` ``` import std; void main(){ foreach (line; File("example.txt").byLine()){ writeln("|" ~ strip(line) ~ "|"); if (line == " HelloWorld") { writeln("^This Line is here."); } } } ```
Re: D Snippet: Reading a file to standard output on Windows Operating System. (FileScan.d)
As of recent observation the `line` in the previous implementation seem to recognise **\r** as default terminator. Making `writeln("|" ~ line ~ "|");` not possible. By correcting terminator and disabling it on `byLine` function it is possible to achieve following output to standard stream: **Output** ``` |test| | s| | | | HelloWorld| ^This Line is here. |t| |ff| ``` **Input (example.txt)** ``` test s HelloWorld t ff ``` **Source code** ``` import std; void main(){ foreach (line; File("example.txt").byLine(No.keepTerminator, "\r\n")){ writeln("|"~line~"|"); if (line == " HelloWorld") { writeln("^This Line is here."); } } } ```
D Phobos Library Documentation: What is the Internal API for?
This is pretty basic question. If you open [D Library Reference](https://dlang.org/phobos/index.html) you are bound to see the **Internal API** section in the table of content. What is the **Internal API** (internal.core, dmd, rt) for and when, how and where to use it? ![](https://i.imgur.com/WyemZsG.png)
D: Convert/parse uint integer to string. (@nogc)
I tried to look into https://dlang.org/phobos/std_conv.html Most of the functions inside `std.conv` seem to be dependant on [Garbage Collection](https://dlang.org/spec/garbage.html). And I couldn't find a straightforward way to produce a `string` value out of `uint` value. How to convert or parse `uint` value to a `string` in `@nogc` way?
Re: D: Declaring empty pointer variables that return address inside function calls?
On Thursday, 23 November 2023 at 20:00:31 UTC, H. S. Teoh wrote: On Thu, Nov 23, 2023 at 07:22:22PM +, BoQsc via Digitalmars-d-learn wrote: Is it possible to declare empty pointer variable inside function calls and pass its address to the function? These are sometimes required while using Win32 - Windows Operating System API. * Empty pointer variables are used by functions to return information after the function is done. My own horrible **suggestion** of empty pointer declaration inside function call: `someFunction(uint & passingEmptyVariableForWrite);` What it would do: * A new variable is declared inside function call. * Address of that variable is passed to the function. * After function is done, you can refer to it for returned value. What's wrong with: uint* result; someFunction(&result); // use *result ? T Nothing wrong. It would be just a more concise compact way to do the same. Also I mostly wanted to know if something like that is already possible in D language. It's not a huge loss if it is not possible.
D: Declaring empty pointer variables that return address inside function calls?
Is it possible to declare empty pointer variable inside function calls and pass its address to the function? These are sometimes required while using Win32 - Windows Operating System API. * Empty pointer variables are used by functions to return information after the function is done. My own horrible **suggestion** of empty pointer declaration inside function call: `someFunction(uint & passingEmptyVariableForWrite);` What it would do: * A new variable is declared inside function call. * Address of that variable is passed to the function. * After function is done, you can refer to it for returned value.
Re: D: How do I pipe (|) through three programs using std.process?
Latest iteration on this thread. Limitations: * pipes through two programs. * very verbose, hard to use. ``` import std; import std.process; version (Windows) { enum Find = "find"; } version (Posix) { enum Find = "grep"; } void pipeTo(Pipe p, string nextprogram){ spawnShell(nextprogram, p.readEnd, stdout); } auto program(string name){ Pipe p = std.process.pipe; spawnShell(name, stdin, p.writeEnd); return p; } void main() { program("echo HelloWorld").pipeTo(nextprogram: Find ~ ` "HelloWorld"`); } ```
D: How to check if a function is chained? a().b().c();
Let's say we have a chain of functions. ``` a().b().c(); ``` I would like to have a behaviour in `a()` that would check if there is `b()` or `c()` chained to it. If `a();`is not chained: do a `writeln("You forgot to chain this function!");` A function that executes a program For me syntactically it is important. One real world application would be: `program("someProgramName").pipe("someOtherProgramName");` Executes and pipes output to another program. `program();` - Only executes the program.
Re: D: How do I pipe (|) through three programs using std.process?
To make this thread more complete, here is the final version. ``` import std.stdio; import std.process; version (Windows) { enum Find = "find"; } version (Posix) { enum Find = "grep"; } int main (string [] args) { auto p1 = pipe; auto p2 = pipe; auto pid1 = spawnShell("echo HelloWorld", stdin, p1.writeEnd); auto pid2 = spawnShell(Find ~ " \"HelloWorld\"", p1.readEnd, p2.writeEnd); auto pid3 = spawnShell(Find ~ " \"HelloWorld\"", p2.readEnd, stdout); wait (pid1); wait (pid2); wait (pid3); return 0; } ``` It is equal to: * Windows: `echo HelloWorld | find "HelloWorld | find "HelloWorld"` * Linux: `echo HelloWorld | grep "HelloWorld | grep "HelloWorld"`
Re: D: How do I pipe (|) through three programs using std.process?
Using `spawnShell` it all seem to work. However the question of why `spawnProcess(["find", "string to find"]` is not working and produces error is still unresolved. Works with `spawnShell`: ``` import std.stdio; import std.process; version (Windows) { enum Find = "find"; } version (Posix) { enum Find = "grep"; } int main (string [] args) { auto p1 = pipe; auto p2 = pipe; auto pid1 = spawnShell("echo HelloWorld", stdin, p1.writeEnd); auto pid2 = spawnShell("find \"HelloWorld\"", p1.readEnd, p2.writeEnd); auto pid3 = spawnShell("find \"HelloWorld\"", p2.readEnd, stdout); wait (pid1); wait (pid2); wait (pid3); return 0; } ```
Re: D: How do I pipe (|) through three programs using std.process?
On Windows: While trying to use `spawnshell` I discovered that I can not use any alphabetical letters inside the `spawnProcess([Find, "Hello"])` it all works when they are numerical `[Find, "6515"]`. As of recent testing `[Find, "df123"]` also is acceptable, but not when letter is on the right `[Find, "df123d"]` Unable to figure why this is the case and how to resolve it. **Working example without problems:** ``` import std.stdio; import std.process; version (Windows) { enum Find = "find"; } version (Posix) { enum Find = "grep"; } int main (string [] args) { auto p1 = pipe; auto p2 = pipe; auto pid1 = spawnShell("echo 123", stdin, p1.writeEnd); auto pid2 = spawnProcess([Find, "123"], p1.readEnd, p2.writeEnd); auto pid3 = spawnProcess([Find, "123"], p2.readEnd, stdout); wait (pid1); wait (pid2); wait (pid3); return 0; } ``` **Output:** ``` 123 ``` **Immediate issue if alphabetical letters are used:** ``` import std.stdio; import std.process; version (Windows) { enum Find = "find"; } version (Posix) { enum Find = "grep"; } int main (string [] args) { auto p1 = pipe; auto p2 = pipe; auto pid1 = spawnShell("echo HelloWorld", stdin, p1.writeEnd); auto pid2 = spawnProcess([Find, "HelloWorld"], p1.readEnd, p2.writeEnd); auto pid3 = spawnProcess([Find, "HelloWorld"], p2.readEnd, stdout); wait (pid1); wait (pid2); wait (pid3); return 0; } ``` **Output:** ``` FIND: Parameter format not correct FIND: Parameter format not correct The process tried to write to a nonexistent pipe. ```
D: How would one make a shared dynamically linked D library?
I would like to export some functionality as external shared dynamically linked D library. Is it possible to do that in D Language and what are limitations? A simple `writeln` example would be great. What I expect is an executable that uses functions, variables, classes, modules from compiled external shared D dynamic library. Example of shared dynamic libraries depending on other shared dynamic libraries would be great as well.
Re: DUB: Sometimes generates .di file and sometimes do not.
To test the behaviour of static library. **program.d** ``` module program; import std.stdio; import library; void main(string[] args) { writeln("func(3) = ", library.func(3)); } ``` **Command Line:** ``` dmd "./program.d" "./builds/library.di" "./builds/library.lib" -ofProgram.exe Program.exe ``` **Output:** ``` func(3) = 4 ```
Re: DUB: Sometimes generates .di file and sometimes do not.
In summary this is what it all combined could look like. **dub.sdl** ``` name "dheaders" description "generates .di header file for a static library." authors "public domain" copyright "Public Domain. No rights reserved." license "public domain" configuration "staticLibrary" { dflags "-Hf=$PACKAGE_DIR/builds/library.di" targetName "library" targetType "library" targetPath "builds" sourceFiles "library.d" extraDependencyFiles "$PACKAGE_DIR/builds/library.di" } configuration "staticLibraryNoDIHeader" { targetName "library" targetType "library" targetPath "builds" sourceFiles "library.d" } buildType "headerFileOnly" { extraDependencyFiles "$PACKAGE_DIR/builds/library.di" dflags "-Hf=$PACKAGE_DIR/builds/library.di" dflags "-o-" sourceFiles "library.d" } ``` **library.d** ``` module library; int func(int x) { return x+1; } ``` **Command Line:** ``` dub --build=headerFileOnly dub --config=staticLibraryNoDIHeader dub --config=staticLibrary ``` First one creates only `.di` d header file Second one creates only `.lib` static library file. Third one creates both `.lib` and `.di` files.
Re: DUB: Sometimes generates .di file and sometimes do not.
Update: To allow only `.di` (D Header) output: Instead of configuration, it would be more correct to make a new `build type`. ``` buildType "headerFileOnly" { extraDependencyFiles "$PACKAGE_DIR/builds/library.di" dflags "-Hf=$PACKAGE_DIR/builds/library.di" dflags "-o-" SourceFile "library.d" } ``` Usage: ``` dub --build=headerFileOnly ``` This will produce only the `.di` D header file without `.lib` file.
Re: DUB: Sometimes generates .di file and sometimes do not.
Configuration to generate only `.di` (D Header file) ``` name "dheaders" description "generates .di header file for a static library." authors "public domain" copyright "Public Domain. No rights reserved." license "public domain" configuration "staticLibrary" { dflags "-Hf=$PACKAGE_DIR/builds/library.di" targetName "library" targetType "library" targetPath "builds" sourceFiles "library.d" extraDependencyFiles "$PACKAGE_DIR/builds/library.di" dflags "-o-" } ``` [-o- Suppress generation of object file. Useful in conjuction with -D or -H flags.](https://dlang.org/dmd-windows.html#switch-o-) Similarly [`buildOptions "syntaxOnly"`](https://dub.pm/package-format-sdl#build-options) can also be used in-place of `dflag "-o-"` they are correspondingly the same. ``` configuration "staticLibrary" { dflags "-Hf=$PACKAGE_DIR/builds/library.di" targetName "library" targetType "library" targetPath "builds" sourceFiles "library.d" extraDependencyFiles "$PACKAGE_DIR/builds/library.di" buildOptions "syntaxOnly" } ```
Re: DUB: Sometimes generates .di file and sometimes do not.
**Conclusive observation:** This can be resolved by informing `dub` of `extraDependencyFiles` to rebuild itself. `library.di` non-existance simply does not trigger rebuild of the package and instead only `library.lib` is being copied from the `cache` folder into `build` folder. Leaving `library.di` not being generated. if `cache` folder exists with a output file, it does not trigger build, only copies from the `\cache`'s `\build` folder. If build is not triggered, `.di` file is not being generated. ### Observations: * Happens with `dub.json` as well. * Mostly `.di` stops generating after the first output of `dub`. * Making any text changes to content of `dub.sdl` triggers `dub` to rebuild package and generate`.di` * Deleting the `cache` output file will trigger to rebuild the package and generate `.di` * `C:\Users\Windows10\AppData\Local\dub\cache\dheaders\~master\build` * After deleting `library.lib` inside latest cache folder `build`: The `.di` starts to generate. ### Solution: [**excludedSourceFiles**](https://dub.pm/package-format-sdl#build-settings) Files that should be removed for the set of already added source files (takes precedence over "sourceFiles" and "sourcePaths") - Glob matching can be used to pattern match multiple files at once ### Working example: **dub.sdl** ``` name "dheaders" description "generates .di header file for a static library." authors "public domain" copyright "Public Domain. No rights reserved." license "public domain" configuration "staticLibrary" { dflags "-Hf=$PACKAGE_DIR/builds/library.di" targetName "library" targetType "library" targetPath "builds" sourceFiles "library.d" extraDependencyFiles "$PACKAGE_DIR/builds/library.di" } ```
Re: DUB: Sometimes generates .di file and sometimes do not.
On Sunday, 5 November 2023 at 10:54:35 UTC, Imperatorn wrote: On Sunday, 5 November 2023 at 10:53:33 UTC, BoQsc wrote: I would like to know how to solve this problem with `dub`. **dub.sdl** ``` name "dheaders" description "generates .di header file for a static library." authors "public domain" copyright "Public Domain. No rights reserved." license "public domain" configuration "staticLibrary" { dflags "-Hf=$PACKAGE_DIR/builds/library.di" targetName "library" targetType "library" targetPath "builds" sourceFiles "library.d" } ``` **library.d** ``` module library; int func(int x) { return x+1; } ``` **Command Line:** ``` dub ``` **Problem:** After running `dub` command: `library.di` file is rarely/inconsistenly generated inside `builds` directory. Try add quotes to the Hf param Didn't help.
DUB: Sometimes generates .di file and sometimes do not.
I would like to know how to solve this problem with `dub`. **dub.sdl** ``` name "dheaders" description "generates .di header file for a static library." authors "public domain" copyright "Public Domain. No rights reserved." license "public domain" configuration "staticLibrary" { dflags "-Hf=$PACKAGE_DIR/builds/library.di" targetName "library" targetType "library" targetPath "builds" sourceFiles "library.d" } ``` **library.d** ``` module library; int func(int x) { return x+1; } ``` **Command Line:** ``` dub ``` **Problem:** After running `dub` command: `library.di` file is rarely/inconsistenly generated inside `builds` directory.
Re: DUB: Is it possible to set release as a default build for a dub package?
On Friday, 3 November 2023 at 21:57:57 UTC, Andrey Zherikov wrote: On Friday, 3 November 2023 at 19:21:42 UTC, BoQsc wrote: However I would want to try to enforce this behaviour from the `dub.json` or `dub.sdl` file. IMHO this is not something that should be enforced from package build configuration, however there can be a way to configure it on system level (like in `dub.conf` if it exists). Unsure what's `dub.conf` but I've found this additional settings file. [%ROOT_PACKAGE_DIR%\dub.settings.json](https://dub.pm/settings) As of now, unable to find a way to begin enforce release. Maybe there is no such setting.
DUB: Is it possible to set release as a default build for a dub package?
While using `dub`, you might notice that after running `dub` or `dub run` command you will end up with notice: ``` Starting Performing "debug" build using C:\D\dmd2\windows\bin64\dmd.exe for x86_64. ``` Example output: ``` C:\Users\Windows10\Documents\Dlang winsock\datatypes>dub Pre-gen Running commands for datatypes Public Domain. No rights reserved. Starting Performing "debug" build using C:\D\dmd2\windows\bin64\dmd.exe for x86_64. Building datatypes 0.0.0: building configuration [application] Linking datatypes Running builds/datatypes.exe ``` **Question:** is it possible to set it to release build in a `dub.json` or `dub.sdl` file? Yes, it is possible using command line `dub --build=release` ``` C:\Users\Windows10\Documents\Dlang winsock\datatypes>dub --build=release Pre-gen Running commands for datatypes Public Domain. No rights reserved. Starting Performing "release" build using C:\D\dmd2\windows\bin64\dmd.exe for x86_64. Building datatypes 0.0.0: building configuration [application] Linking datatypes Running builds/datatypes.exe ``` However I would want to try to enforce this behaviour from the `dub.json` or `dub.sdl` file.
Re: Keyword "package" prevents from importing a package module "package.d"
Well the whole thread is about importing `package.d` while being inside package to provide runnable working example which contains debug information of the package. Sidenote: This is essentially useful when distributing over many machines/platforms via `dub` package manager. You would want to have a source file inside the project that imports package.d and is runnable with well tested example behaviour. Therefore the need to import `package.d` is needed and I can't see a solution, which means that D Language might have to introduce a way to import `package.d` from inside the package, if there is a need to further improve experience of having a self-testing packages in both `dub` and `package modules`.
Re: Keyword "package" prevents from importing a package module "package.d"
On Thursday, 2 November 2023 at 11:32:40 UTC, Imperatorn wrote: On Thursday, 2 November 2023 at 11:12:58 UTC, BoQsc wrote: On Thursday, 2 November 2023 at 10:53:12 UTC, Arafel wrote: On 02.11.23 11:45, BoQsc wrote: Edit incorrect link to example: [Extensive run.dlang.io example](https://run.dlang.io/is/f3jURn) Correct link: https://run.dlang.io/is/Zbrn75 ```d --- waffles/program.d import waffles; void main() { import std; writeln(num); } --- waffles/package.d module waffles; public import waffles.testing1; public import waffles.testing2; --- waffles/testing1.d int num = 5; --- waffles/testing2.d int num2 = 9; ``` `num` and `num2` was never a problem. The current major problem is that it does not work on Windows operating system with either `rdmd` or `dmd`. While it does work on run.dlang.io.
Re: Keyword "package" prevents from importing a package module "package.d"
On Thursday, 2 November 2023 at 10:53:12 UTC, Arafel wrote: On 02.11.23 11:45, BoQsc wrote: Edit incorrect link to example: [Extensive run.dlang.io example](https://run.dlang.io/is/f3jURn) Correct link: https://run.dlang.io/is/Zbrn75 ``` --- waffles/program.d import waffles; ``` See https://dlang.org/spec/module.html#package-module Weirdly enough it does not work on Windows operating system. ![](https://i.imgur.com/x47fcNF.png) ``` program.d(1): Error: unable to read module `waffles` program.d(1):Expected 'waffles.d' or 'waffles\package.d' in one of the following import paths: import path[0] = . import path[1] = C:\D\dmd2\windows\bin\..\..\src\phobos import path[2] = C:\D\dmd2\windows\bin\..\..\src\druntime\import Failed: ["C:\\D\\dmd2\\windows\\bin\\dmd.exe", "-v", "-o-", "program.d", "-I."] C:\waffles>dmd -i -run program.d program.d(1): Error: unable to read module `waffles` program.d(1):Expected 'waffles.d' or 'waffles\package.d' in one of the following import paths: import path[0] = C:\D\dmd2\windows\bin64\..\..\src\phobos import path[1] = C:\D\dmd2\windows\bin64\..\..\src\druntime\import ```
Re: Keyword "package" prevents from importing a package module "package.d"
Edit incorrect link to example: [Extensive run.dlang.io example](https://run.dlang.io/is/f3jURn) Correct link: https://run.dlang.io/is/Zbrn75
Keyword "package" prevents from importing a package module "package.d"
![](https://i.imgur.com/829CzOS.png) Source File **package.d** is a [package module][1] which contains import statements to import other modules. How would one import a **package.d** module when [**keyword "package"**][2] is preventing that? [1]: https://dlang.org/spec/module.html#package-module [2]: https://dlang.org/spec/attribute.html#visibility_attributes Example: ``` import package; ``` Error: ``` datatypes.d(1): Error: identifier expected following `import` datatypes.d(1): Error: `;` expected ``` --- [Extensive run.dlang.io example](https://run.dlang.io/is/f3jURn) Expected correct result if `package.d` was possible to import: ``` waffles/program.d(6): Error: `num` matches conflicting symbols: waffles/testing1.d(1):variable `testing1.num` waffles/testing2.d(1):variable `testing2.num` ```
Weird RDMD error when trying to import source file from subfolder.
I'm unable to import a `.d` source file from a subfolder. Now this happens only with `rdmd`. The `dmd -i -run` works perfectly. I'm currently on Windows 10 operating system. **./testimport.d**: ``` import std; import waffle.next; void main(){ writeln("test", testing); } ``` **./waffle/next.d**: ``` int testing = 5; ``` **Error:** ``` rdmd testimport.d testimport.d(2): Error: module `next` from file waffle\next.d must be imported with 'import next;' ```
Re: Define a new custom operator in D Language.
On Monday, 2 October 2023 at 18:39:41 UTC, Imperatorn wrote: On Monday, 2 October 2023 at 18:34:13 UTC, BoQsc wrote: Here is my issue: I've found a formula on Wikipedia. It's called **Hashing by division**. ![](https://i.imgur.com/UJPAWIW.png) As you can see it uses **mod** keyword to achieve the modulus operation. In D language we use modulus operator `%` and it might look more like this: ``` h(x) M % m ``` This clearly introduces confusion between the source (wikipedia) and the implementation (dlang version). I would like to know how we could define/alia ourselves a `mod` operator in D Language. ``` h(x) M mod m ``` --- **This might lead to less gaps between math formulas and the implementation.** Or at the very least would allow to define a formula in the source code for further implementation and introduce some consistency. https://dlang.org/spec/operatoroverloading.html#binary Overloading seems to only overload behaviour of existing operator, like: ``` + - * / % ^^ & | ^ <<>>>>>~ in ``` I'm unable to see how the operator overloading would allow to define a new custom operator.
Re: Associate information with a pointer address.
The package dependency `emsi_containers` that can be found in https://code.dlang.org/packages/emsi_containers might be a viable way to resolve the problem. ``` /+dub.sdl: dependency "emsi_containers" version="~>0.7" +/ import std; void main(string[] args) @nogc { import containers; DynamicArray!int arr; arr ~= 1; arr ~= 3; foreach (e; arr) printf("%i",e); } ``` https://run.dlang.io/is/zD2zKg Output ``` 13 ``` I keep on wondering if something like this would be applicable to be in the standard library of D Language in the future. `DynamicArray!int arr;` And as always, I find it frustrating to read a source code that includes `!` as template instatiation without seemingly obvious alternative way of handling it.
Re: Associate information with a pointer address.
After being very happy about associative arrays of D Language, I encountered that they are not `@nogc`friendly. Unsure if I should wait for D language to support it, or do I need to rethink everything. Error ``` onlineapp.d(20): Error: assigning an associative array element in `@nogc` function `D main` may cause a GC allocation ``` Source Code ``` import std; void outofcontext() @nogc @system { printf("Hello D ", associative); foreach (pointeraddress, information; associative){ printf("%i", *cast(int *)pointeraddress); } } static string[void*] associative; void main() @nogc @system { printf("Hello D ", associative); int variable = 6; associative[&variable] = "someinformation"; outofcontext(); } ```
Re: Associate information with a pointer address.
Out of scope access to a variable using stored pointer address, demonstration. ``` import std; void outofcontext() { writeln("Hello D ", associative); foreach (pointeraddress, information; associative) { writeln(*cast(string*)pointeraddress); } } static string[void* ] associative; void main() { writeln("Hello D ", associative); string variable = "hi"; void* pointeraddress = &variable; associative[pointeraddress] = "someinformation"; outofcontext(); } ``` https://run.dlang.io/is/QVgL1J ![](https://i.imgur.com/DZqXtj4.png)
Re: Associate information with a pointer address.
Bonus: Store hexadecimal literals in associative array of pointer addresses. ``` import std; void main() { string[void *] associative; // Store Hexadecimal as pointer address in associative array associative[cast(void *)0x7FFCD332CD60] = "someinformation"; // Store Hexadecimal literal as pointer address in a variable. // void * customPointer = cast(void *)0x7FFCD332CD60; writeln("Hello D ", associative[cast(void *)0x7FFCD332CD60]); writeln("Hello D ", associative); } ``` https://run.dlang.io/is/LamPne ![](https://i.imgur.com/Sb9EJ4m.png)
Associate information with a pointer address.
For some reason I thought this was something I wanted to achieve and share. ``` import std; void main() { string variable; void * pointeraddress = &variable; string[void *] associative; associative[pointeraddress] = "someinformation"; writeln("Hello D ", pointeraddress); writeln("Hello D ", associative[pointeraddress]); } ``` https://run.dlang.io/is/WkQ50H ![img](https://i.imgur.com/pEJT9GR.png)
Re: How to use core.vararg to print D variadic arguments and their types without using ! (template instantiation)?
Note that this doesn't work in gdc. The templated version is actually more akin to what C does. Yeah it does not seem to work in gdc when tested using https://d.godbolt.org/ The errors produced: ``` :11:12: error: none of the overloads of template 'core.stdc.stdarg.va_arg' are callable using argument types '!()(__va_list_tag[1], TypeInfo, int*)' 11 | va_arg(_argptr, typeid(i), &i); |^ /opt/compiler-explorer/gcc-trunk-20230917/lib/gcc/x86_64-linux-gnu/14.0.0/include/d/core/stdc/stdarg.d:179:7: note: Candidates are: 'va_arg(T)(ref va_list ap)' 179 | T va_arg(T)(ref va_list ap); // intrinsic | ^ /opt/compiler-explorer/gcc-trunk-20230917/lib/gcc/x86_64-linux-gnu/14.0.0/include/d/core/stdc/stdarg.d:291:10: note: 'va_arg(T)(ref va_list ap, ref T parmn)' 291 | void va_arg(T)(ref va_list ap, ref T parmn); // intrinsic | ^ :14:12: error: none of the overloads of template 'core.stdc.stdarg.va_arg' are callable using argument types '!()(__va_list_tag[1], TypeInfo, double*)' 14 | va_arg(_argptr, typeid(d), &d); |^ /opt/compiler-explorer/gcc-trunk-20230917/lib/gcc/x86_64-linux-gnu/14.0.0/include/d/core/stdc/stdarg.d:179:7: note: Candidates are: 'va_arg(T)(ref va_list ap)' 179 | T va_arg(T)(ref va_list ap); // intrinsic | ^ /opt/compiler-explorer/gcc-trunk-20230917/lib/gcc/x86_64-linux-gnu/14.0.0/include/d/core/stdc/stdarg.d:291:10: note: 'va_arg(T)(ref va_list ap, ref T parmn)' 291 | void va_arg(T)(ref va_list ap, ref T parmn); // intrinsic | ^ ASM generation compiler returned: 1 :11:12: error: none of the overloads of template 'core.stdc.stdarg.va_arg' are callable using argument types '!()(__va_list_tag[1], TypeInfo, int*)' 11 | va_arg(_argptr, typeid(i), &i); |^ /opt/compiler-explorer/gcc-trunk-20230918/lib/gcc/x86_64-linux-gnu/14.0.0/include/d/core/stdc/stdarg.d:179:7: note: Candidates are: 'va_arg(T)(ref va_list ap)' 179 | T va_arg(T)(ref va_list ap); // intrinsic | ^ /opt/compiler-explorer/gcc-trunk-20230918/lib/gcc/x86_64-linux-gnu/14.0.0/include/d/core/stdc/stdarg.d:291:10: note: 'va_arg(T)(ref va_list ap, ref T parmn)' 291 | void va_arg(T)(ref va_list ap, ref T parmn); // intrinsic | ^ :14:12: error: none of the overloads of template 'core.stdc.stdarg.va_arg' are callable using argument types '!()(__va_list_tag[1], TypeInfo, double*)' 14 | va_arg(_argptr, typeid(d), &d); |^ /opt/compiler-explorer/gcc-trunk-20230918/lib/gcc/x86_64-linux-gnu/14.0.0/include/d/core/stdc/stdarg.d:179:7: note: Candidates are: 'va_arg(T)(ref va_list ap)' 179 | T va_arg(T)(ref va_list ap); // intrinsic | ^ /opt/compiler-explorer/gcc-trunk-20230918/lib/gcc/x86_64-linux-gnu/14.0.0/include/d/core/stdc/stdarg.d:291:10: note: 'va_arg(T)(ref va_list ap, ref T parmn)' 291 | void va_arg(T)(ref va_list ap, ref T parmn); // intrinsic | ^ Execution build compiler returned: 1 ```
How to use core.vararg to print D variadic arguments and their types without using ! (template instantiation)?
https://dlang.org/phobos/core_vararg.html The common way to use **va_arg** is `va_arg!(int)(_argptr);` What would be the alternative way or syntax that behave exactly the same way, even if more verbose? `va_arg!(int)(_argptr);` is taken from an example in: https://dlang.org/spec/function.html#d_style_variadic_functions
Setting struct as default parameter of a function using struct literal?
https://docarchives.dlang.io/v2.073.0/spec/struct.html#struct-literal I would like to set function's default struct for a function in a way that it would be visible for the reader to see what options are set. Something like `Options option = {silenceErrors: false}` Here is an example of what I would hope for to work but it surely does not work: ``` import std.stdio; struct Options { bool silenceErrors = false; } void someFunction(Options option = {silenceErrors: false}){ writeln(option); } void main() { someFunction(); } ``` Is it possible to make this part work in a simple way, maybe I'm using a wrong syntax here? ``` void someFunction(Options option = {silenceErrors: false}){ writeln(option); } ```
Dlang Forum: How to Subscribe to the "Replies to your posts"
Some people might not know that it is possible to subscribe and get notifications about replies to your forum posts via email. 1. Open main forum page and click **"new replies"** link ![img1](https://i.imgur.com/HwhDCKO.png) --- 2. Scroll down to the bottom of the page ![img2](https://i.imgur.com/MPxWxsB.png) --- 3. At the bottom of the page click the button **"Edit subscription"** ![img3](https://i.imgur.com/IbvBMZJ.png) --- 4. Complete the form that includes providing your email and click **"save"** button. 5. Next time someone will reply to your post, a notification to your email will be sent. ![img4](https://i.imgur.com/dxj6w2l.png)
Is sizeof() available in D language?
I've seen everyone using **datatype**`.sizeof` property. https://dlang.org/spec/property.html#sizeof It's great, but I wonder if it differ in any way from the standard C function `sizeof()`. https://www.geeksforgeeks.org/sizeof-operator-c/ https://en.cppreference.com/w/cpp/language/sizeof I'm seeking for some speed/performance, so that's why the question. Overall I'm alright with continuing using it.
Re: Windows API: GetUserName: Retrieve the name of the user associated with the current thread.
Update: GetUserName by print to stdout Main function has been updated with `string[] args` and a new feature: ``` if (args.length > 1 && args[1] == "print") { write(username); } ``` Usage: `WindowsGetUserName.exe print` Demonstration ![img1](https://i.imgur.com/dWPlo8L.png) WindowsGetUserName.d ```d import core.sys.windows.windows; import std.conv; import std.stdio; import std.range; pragma(lib, "advapi32.lib"); /** * Retrieves the currently logged-in user's name in a safe manner. * * This function first determines the required buffer size, allocates memory for the username, * and then retrieves the username. * * Returns: * - The username as a string if successful. * - An empty string if an error occurs. */ string getSafeUsername() @system { wchar[] userName; DWORD userNameSize = 0; // First, try GetUserNameW (Unicode version) if (!GetUserNameW(null, &userNameSize)) { int error = GetLastError(); if (error != ERROR_INSUFFICIENT_BUFFER) { // Failed for a reason other than an insufficient buffer return ""; } } // Allocate memory for userName scope(exit) userName.length = 0; // Ensure memory is released if an exception occurs userName.length = userNameSize; // Retrieve the user name by calling GetUserNameW if (GetUserNameW(userName.ptr, &userNameSize)) { // Successfully retrieved the user name, convert it to a string return to!string(userName); } // If GetUserNameW fails, try GetUserNameA (ANSI version) char[] userNameA; userNameSize = 0; if (!GetUserNameA(null, &userNameSize)) { int errorA = GetLastError(); if (errorA != ERROR_INSUFFICIENT_BUFFER) { // Failed for a reason other than an insufficient buffer return ""; } } // Allocate memory for userNameA scope(exit) userNameA.length = 0; // Ensure memory is released if an exception occurs userNameA.length = userNameSize; // Retrieve the user name by calling GetUserNameA if (GetUserNameA(userNameA.ptr, &userNameSize)) { // Successfully retrieved the user name using ANSI version, convert it to a string return to!string(userNameA); } // Both GetUserNameW and GetUserNameA failed, return an empty string return ""; } /** * The entry point of the application. */ void main(string[] args) { string username = getSafeUsername(); if (args.length > 1 && args[1] == "print") { write(username); } else if (!username.empty){ writeln("Logged-in user name: ", username); } else { writeln("Failed to retrieve the user name."); } } ```
Windows API: GetUserName: Retrieve the name of the user associated with the current thread.
I'm sharing some code here. **It's not completely tested and might contain serious mistakes, repetitions, bad style and readabilty. But it seems to work.** Critique, improvements and feedback might help. Demonstration This code retrieves username of the current windows user using Windows API (Win32). ![img1](https://i.imgur.com/aNyyglu.png) **WindowsGetUserName.d** ``` import core.sys.windows.windows; import std.conv; import std.stdio; import std.range; pragma(lib, "advapi32.lib"); /** * Retrieves the currently logged-in user's name in a safe manner. * * This function first determines the required buffer size, allocates memory for the username, * and then retrieves the username. * * Returns: * - The username as a string if successful. * - An empty string if an error occurs. */ string getSafeUsername() @system { wchar[] userName; DWORD userNameSize = 0; // First, try GetUserNameW (Unicode version) if (!GetUserNameW(null, &userNameSize)) { int error = GetLastError(); if (error != ERROR_INSUFFICIENT_BUFFER) { // Failed for a reason other than an insufficient buffer return ""; } } // Allocate memory for userName scope(exit) userName.length = 0; // Ensure memory is released if an exception occurs userName.length = userNameSize; // Retrieve the user name by calling GetUserNameW if (GetUserNameW(userName.ptr, &userNameSize)) { // Successfully retrieved the user name, convert it to a string return to!string(userName); } // If GetUserNameW fails, try GetUserNameA (ANSI version) char[] userNameA; userNameSize = 0; if (!GetUserNameA(null, &userNameSize)) { int errorA = GetLastError(); if (errorA != ERROR_INSUFFICIENT_BUFFER) { // Failed for a reason other than an insufficient buffer return ""; } } // Allocate memory for userNameA scope(exit) userNameA.length = 0; // Ensure memory is released if an exception occurs userNameA.length = userNameSize; // Retrieve the user name by calling GetUserNameA if (GetUserNameA(userNameA.ptr, &userNameSize)) { // Successfully retrieved the user name using ANSI version, convert it to a string return to!string(userNameA); } // Both GetUserNameW and GetUserNameA failed, return an empty string return ""; } /** * The entry point of the application. */ void main() { string username = getSafeUsername(); if (!username.empty) { writeln("Logged-in user name: ", username); } else { writeln("Failed to retrieve the user name."); } } ``` Footnotes https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getusernamea https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getusernamew https://github.com/dlang/dmd/blob/master/druntime/src/core/sys/windows/winbase.d#L1903-L1904
Windows API: lld-link: error: undefined symbol: GetUserNameA
Today I've tried to use Windows API once again and encountered very time consuming case. It's been a long time since the last time I used Windows API. This time I've had an idea that it would be interesting to get thread associated username using Windows API. So after some time while trying to come up with something that might seemingly work. I've encountered this error: ### Error ``` C:\Users\Windows10\Desktop\interpreter>dmd WindowsGetUserName.d lld-link: error: undefined symbol: GetUserNameA referenced by WindowsGetUserName.obj:(_Dmain) Error: linker exited with status 1 ``` ### The Code ```D import std.stdio; import core.sys.windows.windows; import std.conv; void main() { char[256] userName; // Buffer to store the user name DWORD userNameSize = userName.length; // Size of the buffer // Call GetUserName to retrieve the user name if (GetUserNameA(userName.ptr, &userNameSize)) { // Successfully retrieved the user name writeln("Logged-in user name: ", to!string(userName[0 .. userNameSize])); } else { // Failed to retrieve the user name int error = GetLastError(); writeln("GetUserName failed with error code: ", error); } } ``` ### 1. Solution Remember to link **advapi32.lib** * `dmd WindowsGetUserName.d -Ladvapi32.lib` * `rdmd -Ladvapi32.lib WindowsGetUserName.d` ### 2. Solution Remember to include `pragma` into your source code and specify `advapi32.lib` ``` import std.stdio; import core.sys.windows.windows; import std.conv; pragma(lib, "advapi32.lib"); void main() { char[256] userName; // Buffer to store the user name DWORD userNameSize = userName.length; // Size of the buffer // Call GetUserName to retrieve the user name if (GetUserNameA(userName.ptr, &userNameSize)) { // Successfully retrieved the user name writeln("Logged-in user name: ", to!string(userName[0 .. userNameSize])); } else { // Failed to retrieve the user name int error = GetLastError(); writeln("GetUserName failed with error code: ", error); } } ```
DMD: Versioning compilation: generate Identifier for each compilation and writeln it.
I would like to display some identifier that is set after compilation and remains unchanged. This is to recognise and check if two binaries belong to the same compilation or it is a different compilation. I would place it into **version** command of my program. This is what I have now. **Compilation ID** is where I would like to show the identifier. ``` registerCommand("version", "Show version", { writeln("Compilation date: " ~ __DATE__ ~ " " ~ __TIME__ ~ "\n Compilation ID: "); }); ```
Which D compiler is the most maintained and future-proof? [DMD GDC and LDC]
There are three compilers present in the Dlang website: DMD GDC and LDC
[Win32 API] MessageBox Example without MSVCR120.dll dependency
This is a working Hello World example without dependency on Microsoft C Runtime Library, I couldn't find anything by searching around the forums or search engines, so I'm posting it here. Please provide improvements if you feel like something is missing or incorrect. **How to Compile:** `dmd "./MessageBox_HelloWorld.d" "user32.lib"` **Note:** This example can only be compiled with a 32 bit dmd compiler that exists in `.\dmd2\windows\bin\dmd.exe` **Observations:** * This example will generate a 208kb MessageBox_HelloWorld.exe binary * This example is independent of MSVCR120.dll * This example will open additional Command Prompt Window alongside the MessageBox_HelloWorld.exe **MessageBox_HelloWorld.d** ``` module MessageBox_HelloWorld; // A Win32 API Hello World MessageBox Example without MSVCR120.dll dependency // Tested on Windows 10, 2022.12.25 // DMD32 D Compiler v2.101.1-dirty import core.sys.windows.winuser : MessageBoxA, MB_OK; void main() { MessageBoxA(null, "Hello, World!", "My Win32 App", MB_OK); } ``` ![Screenshot](https://i.ibb.co/bvJ392k/Screenshot-1.png)
Re: How to link a msvcr120.dll in an inverse recursive way after a Windows .exe binary deployment
On Sunday, 4 September 2022 at 22:05:24 UTC, ShadoLight wrote: On Sunday, 4 September 2022 at 15:16:47 UTC, BoQsc wrote: **Folder structure** .\msvcr120.dll .\folder1\HelloWorld.exe .\folder2\HelloWorld.exe You don't need to do this. msvcr120.dll is already shipped with the DMD compiler at [DMD-install-folder]\windows\bin64\msvcr120.dll. (It is also in [DMD-install-folder]\windows\bin). You can access it directly from there. The problem is, D Language Compiler is not included along the Windows Operating System. Neither msvcr120.dll is included along the Windows Operating System. You have to download it. No other way. How can you download it, if your .exe binary that has the functionality to download it, cannot even be started due to msvcr120.dll not existing on the operating system. You can try to use pre-existing Command Line Utilities like bitsadmin (Windows 7), curl (Windows 10), but really how can you interact with them from within D Language Binary if it can't even launch. You can try to write a batch script for all that. I really do not want to write batch scripts for the rest of my life, that's why I'm here in the D Language Forum. Copy the DLL to C:\Windows\System32\ It required administrator privilegies and this is only a HelloWorld example of the D language deployed on computers, where the D language is yet to be installed.
How to link a msvcr120.dll in an inverse recursive way after a Windows .exe binary deployment
![HelloWorld](https://i.imgur.com/5BjVIU9.png) **Folder structure** .\msvcr120.dll .\folder1\HelloWorld.exe .\folder2\HelloWorld.exe Basic binaries produced by DMD.exe compiler require Microsoft Compiler Runtime DLL As you might know that a basic D Language example `HelloWorld.exe` requires `msvcr120.dll` to work. Linking inverse recursively? **To not include** `msvcr120.dll` into every `.exe` executable's `.\folder\` **and to not marginally increase the overall size of the project**: I'd like to link every `.\folder\.exe` binary to the `.\msvcr120.dll` dynamic library. **Notice** Launching the `.exe` binary with external script to change the `path` variable is not a solution. I'd like the `.exe` binary to "know" and try to search for `.\msvcr120.dll` by itself after clicking it to launch.
Importing module from the perspective of submodule.
Is it possible to import module that is not in the module's current directory's folder or subfolders? For example: I want to import `somemodule2.d` and `somemodule3.d` into a **`somemodule.d`** **.\somefolder\somemodule.d** .\somemodule2.d .\someotherfolder\somemodule3.d
What exact debugging information is added to the binary and how to parse it all?
Haven't used debuggers or debugged a lot just yet, but I've had this question in my mind and I'd like to inspect some debugging information manually. Are there some kind of documentation or specification and are there a lot of information that is hidden in a an average "debuggable" binary?
Re: DUB issues
On Monday, 18 April 2022 at 05:27:32 UTC, Danny Arends wrote: Hey All, For some reason I cannot reset my password to get into dub (https://code.dlang.org/), after trying I never receive the email to reset my password. I was unsure at first if I had signed up at all, but trying to make a new account tells me my email address is already in use. Any ideas how to get into contact/fix this issue ? I tried to look around and it seems that there are no direct contacts. There is old inactive forum. https://forum.rejectedsoftware.com/groups/rejectedsoftware.dub/ You can try this general email: i...@rejectedsoftware.com This one is for both vibe.d and dub. If no response, there will be a need to try to contact the dub authors personally about this issue. I think it's kind of frustrating. If there is a need, I can try to annoy them on the social media, maybe they'll turn up.
Collect the arguments of all the function calls at a compile time in the whole program.
Let's say I have this example program. I want to get the arguments of all the `some_function();` in the whole program. **Even if the scope of the function call is never executed.** (Ex. due to IF statement being negative.) I tried to use `__traits` but it seems to not gather any information about function calls. Or I'm missing something. ``` import std.stdio; import std.traits; void some_function(string argument){} void main(){ some_function("someargument1"); some_function("someargument2"); if (false){ some_function("someargument3"); } /* __traits allMembers does not print function calls. I tried to use allMembers of __traits, but it does not contain the function calls. Only the functions definitions/declarations inside a module. */ foreach(memberss; __traits(allMembers, mixin(__MODULE__))){ write(" ", isSomeFunction!(mixin(memberss))); writeln(" \t", fullyQualifiedName!(mixin(memberss))); } ``` ``` ```
Re: A weird example of .toUTF16z concatination side-effects in wcsncat
On Thursday, 7 April 2022 at 12:51:26 UTC, Stanislav Blinov wrote: On Thursday, 7 April 2022 at 10:50:35 UTC, BoQsc wrote: wchar_t* clang_string = cast(wchar_t *)"AA"; You're witnessing undefined behavior. "AA" is a string literal and is stored in the data segment. Mere cast to wchar_t* does not make writing through that pointer legal. Moreover, even if it was legal to write through it, that alone wouldn't be sufficient. From documentation of `wcsncat`: The behavior is undefined if the destination array is not large enough for the contents of both str and dest and the terminating null wide character. `wcsncat` does not allocate memory, it expects you to provide a sufficiently large mutable buffer. For example, like this: ```d // ... auto cls = new wchar_t[256]; cls[] = 0; cls[0..10] = 'A'; wchar_t* clang_string = cls.ptr; // ... ``` That is correct, the results are satisfying. I believe this thread is resolved. ``` import std.stdio; @system void main(){ import std.utf: toUTF16z, toUTF16; import core.stdc.wchar_ : wcsncat, wcslen, wprintf; import core.stdc.stdlib : wchar_t; import core.sys.windows.winnt : LPCWSTR; auto cls = new wchar_t[256]; cls[] = 0; cls[0..10] = 'A'; wchar_t* clang_string = cls.ptr; //wchar_t* clang_string = cast(wchar_t *)"AA"; wstring dlang_string = "BB"w; //< NEW, same results LPCWSTR winpointer_to_string = "CC"; wcsncat(clang_string, dlang_string.toUTF16z, wcslen(dlang_string.toUTF16z)); // String output: AABB wcsncat(clang_string, winpointer_to_string, wcslen(winpointer_to_string)); // String output: AABBCC // Expected string: AABBCC wprintf(clang_string); // String output: AABBCC // Expected string: AABBCC } ```
Re: A weird example of .toUTF16z concatination side-effects in wcsncat
On Thursday, 7 April 2022 at 11:03:39 UTC, Tejas wrote: On Thursday, 7 April 2022 at 10:50:35 UTC, BoQsc wrote: Here I try to concatenate three character strings using `wcsncat()`. [...] Maybe try using `wstring` instead of string? Also use the `w` postfix ```d wstring dlang_string = "BBB"w; I can't test because I'm not on my PC and I don't use Windows Exactly same results. `AA` ``` import std.stdio; @system void main(){ import std.utf: toUTF16z, toUTF16; import core.stdc.wchar_ : wcsncat, wcslen, wprintf; import core.stdc.stdlib : wchar_t; import core.sys.windows.winnt : LPCWSTR; wchar_t* clang_string = cast(wchar_t *)"AA"; wstring dlang_string = "BBB"w; //< NEW, same results LPCWSTR winpointer_to_string = "CC"; wcsncat(clang_string, dlang_string.toUTF16z, wcslen(dlang_string.toUTF16z)); // String output: AABBB wcsncat(clang_string, winpointer_to_string, wcslen(winpointer_to_string)); // String output: AA // Expected string: AABBBCC wprintf(clang_string); // String output: AA // Expected string: AABBBCC } ```
A weird example of .toUTF16z concatination side-effects in wcsncat
Here I try to concatenate three character strings using `wcsncat()`. `clang_string` AA `dlang_string` BBB `winpointer_to_string` CC ``` import std.stdio; @system void main(){ import std.utf: toUTF16z, toUTF16; import core.stdc.wchar_ : wcsncat, wcslen, wprintf; import core.stdc.stdlib : wchar_t; import core.sys.windows.winnt : LPCWSTR; wchar_t* clang_string = cast(wchar_t *)"AA"; string dlang_string = "BBB"; LPCWSTR winpointer_to_string = "CC"; wcsncat(clang_string, dlang_string.toUTF16z, wcslen(dlang_string.toUTF16z)); // String output: AABBB wcsncat(clang_string, winpointer_to_string, wcslen(winpointer_to_string)); // String output: AA // Expected string: AABBBCC wprintf(clang_string); // String output: AA // Expected string: AABBBCC } ``` **Problem:** Any *following concatenated string* after "`wcsncat()` concatenation of `dlang_string.toUTF16z` string", happen to not be printed and gets overwritten. **The Expected output:** I was expecting the `wprintf()` **result** to be `AABBBCC` The `wprintf() ` **result** I've received is this: `AA`
How to print or check if a string is "\0" (null) terminated in the D programming language?
I have a feeling that some parts of my code contains unterminated strings and they do overflow into other string that is to be combined. I'd like to take a look at strings, analyse them manually and see if any of them end up terminated or not. Please provide any relevant examples of how you do this.
Re: Check if Key exists in Associative Array using D language.
On Tuesday, 5 April 2022 at 11:53:19 UTC, Dennis wrote: On Tuesday, 5 April 2022 at 11:26:27 UTC, BoQsc wrote: I'd like to know if there is similar function: that can check if a **key** inside a [Associative Array][2] can be found. You can use the `in` operator for that: https://dlang.org/spec/hash-map.html#testing_membership This is brilliant, thank you.
Check if Key exists in Associative Array using D language.
I've found [std.algorithm: canFind][1] to be useful on a **regular arrays**. I'd like to know if there is similar function: that can check if a **key** inside a [Associative Array][2] can be found. [1]:https://dlang.org/phobos/std_algorithm_searching.html#.canFind [2]:https://dlang.org/spec/hash-map.html
Re: How to exclude function from being imported in D language?
On Tuesday, 8 March 2022 at 22:28:27 UTC, bauss wrote: On Tuesday, 8 March 2022 at 20:12:40 UTC, BoQsc wrote: I think D Language needs and lacks conditional compilation condition and attribute of "exclude". The exclude keyword or code block in the exclude, would be made sure to not be imported by any means. Now it seems all to be only workarounds. What D just needs is a way to specify the entry point, in which it just defaults to the first main function found, but could be any function given. Yeah that would be as great. Without this, the project modules feel non-interactive and always depending on other modules. Dependant modules do not feel modular, if you can't bring them to other project as a standalone module.
Re: How to exclude function from being imported in D language?
I think D Language needs and lacks conditional compilation condition and attribute of "exclude". The exclude keyword or code block in the exclude, would be made sure to not be imported by any means. Now it seems all to be only workarounds.
How to exclude function from being imported in D language?
Premise: In D language, only one main(){} function can exist in a program. Having two `main()` functions throws an error. Let's say I want to use some functionality of another program, but it has a `main(){}` function. How can I import and use functions without importing the `main(){}` function?
Re: SendMessageTimeoutW requires casting string to uint?
Update: 2022-03-04 ChangeLog: * Fixed Typos * Added Switch Statement for Command Line Interface Arguments * Added Switch Statement for Policy, intl, Environment * Added Switch Statement for Error handling: Exit status, Error level * Increased window "timeout" from 1 to 1000 https://github.com/vaido-world/WM_SETTINGCHANGE
Re: How to remove all characters from a string, except the integers?
On Thursday, 3 March 2022 at 12:14:13 UTC, BoQsc wrote: I need to check if a string contains integers, and if it contains integers, remove all the regular string characters. I've looked around and it seems using regex is the only closest solution. ``` import std.stdio; void main(string[] args){ if (args.length > 1){ write(args[1]); // Needs to print only integers. } else { write("Please write an argument."); } } ``` Regular expression solution ``` import std.stdio; import std.regex; import std.string: isNumeric; import std.conv; void main(string[] args){ if (args.length > 1){ writeln(args[1]); // Needs to print only integers. string argument1 = args[1].replaceAll(regex(r"[^0-9.]","g"), ""); if (argument1.isNumeric){ writeln(std.conv.to!uint(argument1)); } else { writeln("Invalid value: ", args[1]," (must be int integer)"); } } else { write("Please write an argument."); } } ```
Re: How to remove all characters from a string, except the integers?
On Thursday, 3 March 2022 at 13:25:32 UTC, Stanislav Blinov wrote: On Thursday, 3 March 2022 at 12:14:13 UTC, BoQsc wrote: I need to check if a string contains integers, and if it contains integers, remove all the regular string characters. I've looked around and it seems using regex is the only closest solution. ```d import std.stdio; import std.algorithm : find, filter; import std.conv : to; import std.uni : isNumber; void main(string[] args){ if (args.length > 1){ auto filtered = () { auto r = args[1].find!isNumber; // check if a string contains integers return r.length ? r.filter!isNumber.to!string // and if it does, keep only integers : args[1]; // otherwise keep original } (); filtered.writeln; } else { write("Please write an argument."); } } ``` D language should be renamed into Exclamation-mark language. It feels overused everywhere and without a better alternative.
How to remove all characters from a string, except the integers?
I need to check if a string contains integers, and if it contains integers, remove all the regular string characters. I've looked around and it seems using regex is the only closest solution. ``` import std.stdio; void main(string[] args){ if (args.length > 1){ write(args[1]); // Needs to print only integers. } else { write("Please write an argument."); } } ```
How to convert a string command line argument to an int?
I tried to use `std.conv.parse(args[2])`, ``` import std.stdio; import std.conv; void main(string[] args){ if (args.length > 1) { writeln(broadcastSettingChange(args[1])); if (args.length == 2) { // TODO: second argument needs parse to uint writeln(broadcastSettingChange(args[1], std.conv.parse(args[2]))); } } else { writeln(broadcastSettingChange()); } write(args.length > 1); } ``` ### But I'm getting this error ``` (21): Error: template `std.conv.parse` cannot deduce function from argument types `!()(string)` .\..\..\src\phobos\std\conv.d(2263):Candidates are: `parse(Target, Source, Flag doCount = No.doCount)(ref Source source)` .\..\..\src\phobos\std\conv.d(2382): `parse(Target, Source, Flag doCount = No.doCount)(ref Source s)` .\..\..\src\phobos\std\conv.d(2804): `parse(Target, Source, Flag doCount = No.doCount)(ref Source source, uint radix)` .\..\..\src\phobos\std\conv.d(2973): `parse(Target, Source, Flag doCount = No.doCount)(ref Source s)` .\..\..\src\phobos\std\conv.d(3084): `parse(Target, Source, Flag doCount = No.doCount)(ref Source source)` .\..\..\src\phobos\std\conv.d(3776): `parse(Target, Source, Flag doCount = No.doCount)(ref Source s)` .\..\..\src\phobos\std\conv.d(3833): `parse(Target, Source, Flag doCount = No.doCount)(ref Source s)` .\..\..\src\phobos\std\conv.d(3918): `parse(Target, Source, Flag doCount = No.doCount)(ref Source s)` .\..\..\src\phobos\std\conv.d(4031): `parse(Target, Source, Flag doCount = No.doCount)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar comma = ',')` .\..\..\src\phobos\std\conv.d(4218): `parse(Target, Source, Flag doCount = No.doCount)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar comma = ',')` .\..\..\src\phobos\std\conv.d(4327): `parse(Target, Source, Flag doCount = No.doCount)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar keyval = ':', dchar comma = ',')` WM_SETTINGCHANGE.d(21):All possible candidates are marked as `deprecated` or `@disable` Failed: ["C:\\Users\\Windows10\\Desktop\\dmd2\\windows\\bin\\dmd.exe", "-v", "-o-", "WM_SETTINGCHANGE.d", "-I."] ```
Declaring a reusable formula and using it in other scopes.
`bool nextArgumentDoesNotReachEndOfArray = i + 1 < args.length;` How can I declare it out of scope and reuse it in any scope that has `i` and `args.length` declared?
Re: Is this Windows Win32 fileapi.h header accessible in D language?
On Tuesday, 8 February 2022 at 18:21:46 UTC, duser wrote: On Tuesday, 8 February 2022 at 16:10:19 UTC, BoQsc wrote: Unsure where to start, so I decided to ask here how to get use of this win32 header. https://docs.microsoft.com/en-us/windows/win32/api/fileapi/ the specific module containing that is `core.sys.windows.winbase` my trick to find these is to use github search with the function you want: https://github.com/dlang/druntime/search?q=AreFileApisANSI This is great. Thanks for now.
Is this Windows Win32 fileapi.h header accessible in D language?
Unsure where to start, so I decided to ask here how to get use of this win32 header. https://docs.microsoft.com/en-us/windows/win32/api/fileapi/
Re: How to loop through characters of a string in D language?
On Wednesday, 8 December 2021 at 14:16:16 UTC, bauss wrote: On Wednesday, 8 December 2021 at 11:23:45 UTC, BoQsc wrote: Let's say I want to skip characters and build a new string. The string example to loop/iterate: ``` import std.stdio; void main() { string a="abc;def;ab"; } ``` The character I want to skip: `;` Expected result: ``` abcdefab ``` string b = a.replace(";", ""); Thanks, that's what I used to do few years ago. It's a great solution I forget about and it works. ``` import std.stdio; import std.array; void main() { string a="abc;def;ab"; string b = a.replace(";", ""); writeln(b); } ```
Re: How to loop through characters of a string in D language?
On Wednesday, 8 December 2021 at 12:49:39 UTC, Adam D Ruppe wrote: On Wednesday, 8 December 2021 at 11:23:45 UTC, BoQsc wrote: The string example to loop/iterate: foreach(ch; a) { } does the individual chars of the string you can also foreach(dchar ch; a) { } to decode the utf 8 Thanks Adam. This is how it would look implemented. ``` import std.stdio; void main() { string a = "abc;def;ab"; string b; foreach(ch; a) { if (ch != ';'){ b ~= ch; } writeln(ch); } writeln(b); } ```
Re: How to loop through characters of a string in D language?
On Wednesday, 8 December 2021 at 11:35:39 UTC, Biotronic wrote: On Wednesday, 8 December 2021 at 11:23:45 UTC, BoQsc wrote: Let's say I want to skip characters and build a new string. The string example to loop/iterate: ``` import std.stdio; void main() { string a="abc;def;ab"; } ``` The character I want to skip: `;` Expected result: ``` abcdefab ``` [..] string b = a.filter!(c => c != ';').to!string; writeln(b); } I somehow have universal cross language hate for this kind of algorithm. I'm not getting used to the syntax and that leads to poor readability. But that might be just me. Anyways, Here is what I've come up with. ``` import std.stdio; void main() { string a = "abc;def;ab"; string b; for(int i=0; i
How to loop through characters of a string in D language?
Let's say I want to skip characters and build a new string. The string example to loop/iterate: ``` import std.stdio; void main() { string a="abc;def;ab"; } ``` The character I want to skip: `;` Expected result: ``` abcdefab ```
Re: How to use std.windows.registry, there are no documentations.
On Saturday, 27 November 2021 at 19:59:24 UTC, Imperatorn wrote: On Wednesday, 24 November 2021 at 12:07:44 UTC, BoQsc wrote: On Thursday, 11 July 2019 at 08:53:35 UTC, BoQsc wrote: [...] ``` import std.stdio; import std.windows.registry; [...] You could add some examples to the documentation if you like ☀️ I'll certaintly will, as that's the only way to keep some kind of reference point and not make it all lost. It might take a while since various things going on at the same time for the next few months.
Re: Include .def definition file information for the linker into a .d source file
On Wednesday, 24 November 2021 at 20:29:36 UTC, Imperatorn wrote: On Wednesday, 24 November 2021 at 17:38:42 UTC, BoQsc wrote: On Wednesday, 24 November 2021 at 17:29:09 UTC, Adam D Ruppe wrote: On Wednesday, 24 November 2021 at 17:23:07 UTC, BoQsc wrote: The many times I tried this pragma, it did not even get recognised as pragma at all. You need to use `dmd -m32mscoff` or `dmd -m64`. Plain `dmd` won't work. If -m32mscoff and -m64 still don't work, what's your dmd version? It was added in 2.083.0, November 2018. Thanks, seems to work now. I had to add these two pragmas to the `winsamp.d` ``` pragma(linkerDirective, "/subsystem:windows"); pragma(lib, "user32.lib"); ``` And as you mentioned give additional`-m32mscoff` flag to the compiler. `dmd winsamp.d -m32mscoff` **The obvious problem now is:** How can you compile without specifying the flags. With plain dmd. Just a quick question before going deeper. Why do you not want to supply the definition file? To have a single standalone .d script file, that's the end goal. I want to have everything in one .d source file and run it without specifying additional files or flags. In other words: as simple as possible to use.
Re: Include .def definition file information for the linker into a .d source file
Since the **linkerDirective pragma** is not supported for OMF object file. Linker directives are only supported for MS-COFF output. https://dlang.org/spec/pragma.html#linkerDirective I doubt that this thread is completely resolved.
Re: Include .def definition file information for the linker into a .d source file
On Wednesday, 24 November 2021 at 17:38:42 UTC, BoQsc wrote: [...] **The obvious problem now is:** How can you compile without specifying the flags. With plain dmd. It probably has to do something with the default target of dmd (`-m32`) generating **OMF object file**. https://dlang.org/dmd-windows.html#switch-m32 `-m32mscoff` and `-m64` both generate **MS-COFF Object file** instead of **OMF object file**. --- The below error is caused when the compilation target is **OMF object file** instead of **MS-COFF Object file**. ``` winsamp.d(11): Error: unrecognized pragma(linkerDirective) ```
Re: Include .def definition file information for the linker into a .d source file
On Wednesday, 24 November 2021 at 17:29:09 UTC, Adam D Ruppe wrote: On Wednesday, 24 November 2021 at 17:23:07 UTC, BoQsc wrote: The many times I tried this pragma, it did not even get recognised as pragma at all. You need to use `dmd -m32mscoff` or `dmd -m64`. Plain `dmd` won't work. If -m32mscoff and -m64 still don't work, what's your dmd version? It was added in 2.083.0, November 2018. Thanks, seems to work now. I had to add these two pragmas to the `winsamp.d` ``` pragma(linkerDirective, "/subsystem:windows"); pragma(lib, "user32.lib"); ``` And as you mentioned give additional`-m32mscoff` flag to the compiler. `dmd winsamp.d -m32mscoff` **The obvious problem now is:** How can you compile without specifying the flags. With plain dmd.
Re: Include .def definition file information for the linker into a .d source file
On Wednesday, 24 November 2021 at 17:14:42 UTC, Adam D Ruppe wrote: On Wednesday, 24 November 2021 at 17:06:21 UTC, BoQsc wrote: **The question:** Is there a way to include the `.def` file instructions inside `.d` file, so that there won't be a need for additional `.def` file when compiling. (`dmd winsamp`) https://dlang.org/spec/pragma.html#linkerDirective The many times I tried this pragma, it did not even get recognised as pragma at all. Essentialy it did not work. Mind giving a demonstration of this pragma? ``` dmd winsamp.d winsamp.d(13): Error: unrecognized `pragma(linkerDirective)` ```
Include .def definition file information for the linker into a .d source file
I'm not sure if I have sucessfully achieved something like this before or is it even possible right now, but there is a sample file that comes with DMD compiler: `D\dmd2\samples\d\winsamp.d` **The problem:** `winsamp.d` have to be compiled with `.def` file. ``` /+ Compile with: + dmd winsamp winsamp.def + or: + dmd winsamp -L-Subsystem:Windows + + 64 bit version: + dmd -m64 winsamp -L-Subsystem:Windows user32.lib +/ ``` This is how the `.def` file looks like (`D\dmd2\samples\d\winsamp.def`): ``` EXETYPE NT SUBSYSTEM WINDOWS ``` **The question:** Is there a way to include the `.def` file instructions inside `.d` file, so that there won't be a need for additional `.def` file when compiling. (`dmd winsamp`)
How to use std.windows.registry, there are no documentations.
On Thursday, 11 July 2019 at 08:53:35 UTC, BoQsc wrote: https://dlang.org/phobos/std_windows_registry.html https://github.com/dlang/phobos/blob/master/std/windows/registry.d Can someone provide some examples on how to: set, change, receive something from the Windows registry using Phobos std.windows.registry library? ``` import std.stdio; import std.windows.registry; void main(string[] args) { writeln("hello world"); writefln("args.length = %d", args.length); foreach (index, arg; args) { writefln("args[%d] = '%s'", index, arg); } writeln(); writeln(Registry.localMachine().name); writeln(Registry.localMachine().getKey("System\\CurrentControlSet\\Control\\Session Manager\\Environment").name); writeln(Registry.localMachine().getKey("System").keyCount); writeln(Registry.localMachine().getKey("System").valueCount); writeln(Registry.localMachine().getKey("System\\CurrentControlSet\\Control\\Session Manager\\Environment").valueCount); write(Registry.localMachine().getKey("System\\CurrentControlSet\\Control\\Session Manager\\Environment").getValue("Path").value_EXPAND_SZ); Registry.currentUser().createKey("test"); } ```
How to make a new dub subpackage? [Answered]
Note: It is not possible to make subpackage inside subpackage. To make a subpackage with dub; follow these general guidelines. **General guidelines** 1. Create a new folder. 2. Open the folder. 3. Initialise a new package. (`dub init`) 4. Open `dub.json` file * Append this: ``` "subPackages": [ "./component1/" ] ``` 6. Create a new inner folder named `component1` 7. Initialise a new package inside the inner folder (`dub init`) 8. Open the previous package folder. 9. Run the subpackage as a test. (`dub run :component1`) ___ **This is how it is made in Windows 10:** (I use Windows 10, please excuse for not giving Linux directions.) mkdir "NewPackage" cd "./NewPackage" dub init notepad dub.json "subPackages": [ "./component1/" ] mkdir "component1" cd "./component1" dub init cd "../" dub run :component1 ___ More information can be found: https://dub.pm/package-format-json#sub-packages For SDL Package File Format: https://dub.pm/package-format-sdl#sub-packages
Re: How to read a single character in D language?
On Friday, 19 November 2021 at 18:01:57 UTC, Adam D Ruppe wrote: On Friday, 19 November 2021 at 17:36:55 UTC, BoQsc wrote: Let's say I want to write a simple program that asks for an input of a single character. After pressing a single key on a keyboard, the character is printed out and the program should stop. This is platform specific. About 10 lines of code for a minimum implementation per OS, but if you don't wanna do it that way my library has a function for it with a prepackaged sample: http://arsd-official.dpldocs.info/arsd.terminal.html#single-key that's arsd-official:terminal on dub or you can grab the file from my github repo. I guess you could view my source to see the impl but I don't feel like pulling it out right now. Thanks Adam. I've tested and it does work on Windows 10. mkdir "read_character_project" cd "read_character_project" dub init dub add arsd-official:terminal notepad ./source/app.d import arsd.terminal; void main() { auto terminal = Terminal(ConsoleOutputType.linear); auto input = RealTimeConsoleInput(&terminal, ConsoleInputFlags.raw); terminal.writeln("Press any key to continue..."); auto ch = input.getch(); terminal.writeln("You pressed ", ch); } dub run Performing "debug" build using C:\Program Files\LDC 1.28\bin\ldc2.exe for x86_64. arsd-official:terminal 10.3.10: target for configuration "normal" is up to date. arsd ~master: target for configuration "application" is up to date. To force a rebuild of up-to-date targets, run again with --force. Running arsd.exe Press any key to continue... You pressed u ___ Of interest, I also tried to look up getch() inside http://arsd-official.dpldocs.info/source/arsd.terminal.d.html#L2867 But the source file overwhelmed me by its size. For now I'm still interested in a more simple standalone implementation that would be more learning friendly, or at least with little explanation of basic things behind the code and how it is interfacing with the operating system, the native library.
How to read a single character in D language?
Let's say I want to write a simple program that asks for an input of a single character. After pressing a single key on a keyboard, the character is printed out and the program should stop.
Re: Find a char among string (string.findAmong.char)
I think nested foreach loops are more readable. ``` import std; void main() { alias alphabet = letters; char[26] letters = ['a','b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; string wordExample = "Book."; foreach (letter; wordExample){ foreach (alphabetLetter; letters){ if (letter == alphabetLetter) { writeln(letter); } } } } ```
Re: Find a char among string (string.findAmong.char)
On Tuesday, 6 July 2021 at 15:48:35 UTC, rassoc wrote: You can also do: ```d import std; void main() { // https://dlang.org/phobos/std_ascii.html#.lowercase "Book.".filter!(c => lowercase.canFind(c)) .each!(c => writeln(c, " found")); // Output: // o found // o found // k found } ``` I really don't like reading arrow functions. It takes some more effort to understand, follow and get used to them. I'd like something simple and effortless looking and feeling that would make code readable similarly to an english sentence. Such as this, but as noted, this does not work as intended/assumed by me: ``` if (letter.findAmong(alphabet)){ write("found"); } ```
Re: Find a char among string (string.findAmong.char)
On Monday, 5 July 2021 at 19:48:13 UTC, jfondren wrote: On Monday, 5 July 2021 at 19:34:14 UTC, BoQsc wrote: But I really don't like how it looks less readable and makes less sense on first look. `if (([letter].findAmong(alphabet)).length)` I'd like to use some method on the `letter` instead of [] And `.length` does not make a lot of sense when reading like an english sentence. I suggest canFind, like in my earlier example. findAmong is like "consume this range until you find one of these things, and then return the remainder of the range". It doesn't really fit your use. I tried out .canFind method, and to test it I removed the letter 'o' from the Alphabet. Weirdly enough .canFind method still found 'o' letter among the Alphabet. https://run.dlang.io/is/2Fvenf
Re: Find a char among string (string.findAmong.char)
On Monday, 5 July 2021 at 19:25:23 UTC, jfondren wrote: On Monday, 5 July 2021 at 19:19:19 UTC, BoQsc wrote: If I use `[letter].findAmong(alphabet)` in my code, it considers a dot (.) punctuation character as a letter. You can see it here: https://run.dlang.io/is/YWmaXU It returns a zero-length array that, because it's not null, is true. That's why I used .length in my example. ``` $ rdmd --eval 'writeln("str"[$..$].length); writeln("str"[$..$] ? true : false)' 0 true $ rdmd --eval 'writeln([].length); writeln([] ? true : false)' 0 false ``` Oh alright I think I fixed it with your guidance. ``` import std; void main() { alias alphabet = letters; char[26] letters = ['a','b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; string wordExample = "Book."; foreach (letter; wordExample){ if (([letter].findAmong(alphabet)).length){ write(letter); write(" letter is found among the alphabet."); writeln; } } } ``` But I really don't like how it looks less readable and makes less sense on first look. `if (([letter].findAmong(alphabet)).length)` I'd like to use some method on the `letter` instead of [] And `.length` does not make a lot of sense when reading like an english sentence.
Re: Find a char among string (string.findAmong.char)
On Monday, 5 July 2021 at 18:59:09 UTC, jfondren wrote: On Monday, 5 July 2021 at 18:53:27 UTC, jfondren wrote: If you replace the findAmong call with `[letter].findAmong(alphabet)`, this works. Consider: ```d import std; void main() { import std.ascii : alphabet = letters; string wordExample = "Book."; foreach (letter; wordExample) { writefln!"%c is %sa letter"(letter, [letter].findAmong(alphabet).length ? "" : "not "); writefln!"%c is %sa letter"(letter, alphabet.canFind(letter) ? "" : "not "); } writeln("___>>___finally some letters".findAmong(alphabet)); } ``` If I use `[letter].findAmong(alphabet)` in my code, it considers a dot (.) punctuation character as a letter. You can see it here: https://run.dlang.io/is/YWmaXU
Find a char among string (string.findAmong.char)
I get an error when I try to find that letter is among alphabet. onlineapp.d(13): Error: template `std.algorithm.searching.findAmong` cannot deduce function from argument types `!()(immutable(char), immutable(string))`, candidates are: /dlang/dmd/linux/bin64/../../src/phobos/std/algorithm/searching.d(2694): `findAmong(alias pred = "a == b", InputRange, ForwardRange)(InputRange seq, ForwardRange choices)` with `pred = "a == b", InputRange = immutable(char), ForwardRange = string` must satisfy the following constraint: ` isInputRange!InputRange` This is the code: You can run it at: https://run.dlang.io/is/5cvuUZ import std; void main() { alias alphabet = letters; char[26] letters = ['a','b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; string wordExample = "Book."; foreach (letter; wordExample){ if (letter.findAmong(alphabet)){ write("found"); } write(letter); } }
Download a file into array (using std.net.curl.download)
Let's say I can't store information into files. Is it possible to download a file into an array. This is what I have now. It saves a download into a file named: file.txt import std; import std.net.curl; void main() { writeln("Hello D"); download("https://gist.githubusercontent.com/deekayen/4148741/raw/98d35708fa344717d8eee15d11987de6c8e26d7d/1-1000.txt";, "file.txt"); } Also run.dlang.io seems to be blocking and not letting me to run curl requests. I'm feeling sad right now. https://run.dlang.io/?compiler=dmd&source=import%20std;%0Aimport%20std.net.curl;%0A%0A%0Avoid%20main()%0A%7B%0A%20%20%20%20writeln(%22Hello%20D%22);%0A%20%20%20%20download(%22https:%2F%2Fgist.githubusercontent.com%2Fdeekayen%2F4148741%2Fraw%2F98d35708fa344717d8eee15d11987de6c8e26d7d%2F1-1000.txt%22,%20%22.%22);%0A%7D
Re: Is there an alias for standard libraries to use in import statement?
On Sunday, 4 July 2021 at 08:50:54 UTC, Mike Parker wrote: You can use named imports, but then you have to use the name as a namespace: ``` import system = std; void main() { system.writeln("Hello D"); } ``` These were the examples that might feel more readable and natural than simply a three letter junction: import std; What do you think? If you're worried about the readability of `std` by itself, don't use it by itself. Import the specific modules you want: ``` import std.algorithm, std.range, std.stdio; ``` Thank you for showing the alternative. or whatever. It's a non-issue, IMO. It's not like anyone using D doesn't know what std is. It's not about knowing or not knowing, it's about the reading flow and ease on the thinking. For me, it's always better to have things spelled correctly. Constant abbrevations do feel unnatural to me, even if I'm familiar of the complexity behind it. Anyways, even if it is possible as you shown. I'm feeling like it's still non standard way and might confuse people when the whole D code base with community is about importing std library directly. But I'm glad I won't have to think about this problem anymore and that's important to have less important questions answered for more important things to accomplish.
Is there an alias for standard libraries to use in import statement?
I just started with a fresh look at the D language and would like to be able to rewrite this code: import std; void main() { writeln("Hello D"); } Into more readable standard library name: import system; void main() { writeln("Hello D"); } Or into this import library.standard; void main() { writeln("Hello D"); } Or into this: import library phobos; void main() { writeln("Hello D"); } These were the examples that might feel more readable and natural than simply a three letter junction: import std; What do you think?