Re: Why `foo.x.saa.aa` and `foo.y.saa.aa` is the same? `shared_AA.saa` should still be instance variable, not class variable, right?
It's a bug.
Re: How to use D without the GC ?
1) arena allocator makes memory manageable with occasional cache invalidation problem 2) no hashtable no problem 3) error handling depends on your code complexity, but even in complex C# code I found exceptions as boolean: you either have an exception or you don't 4) I occasionally use CTFE, where `@nogc` is a nuisance 5) polymorphism can be a little quirky
Re: How to pass in reference a fixed array in parameter
With accessor: ``` void main() { s_cell[] maze=make(5,5); s_cell a=maze.get(1,2); print_maze(maze); } void print_maze(s_cell[] maze) { } s_cell[] make(int width, int height) { return new s_cell[width*height]; } s_cell get(s_cell[] maze, int x, int y) { return maze[5*y+x]; //oops } ``` looks like you need to store the maze width somewhere.
Re: How to pass in reference a fixed array in parameter
On Tuesday, 4 June 2024 at 12:22:23 UTC, Eric P626 wrote: I try to create a 2D array of fixed length and pass it in parameter as a reference. Normally, in C, I would have used a pointer as parameter, and pass the address of the array. Not obvious what you're trying to do. How would you do it in C? Use one dimensional array? You can use one dimensional array in D too. If dimensions of the maze are dynamic, you just write the maze creation function that allocates the maze as you want. In simple case: ``` void main() { writeln("Maze generation demo"); s_cell [5][5] maze; print_maze (maze); } void print_maze (ref s_cell [5][5] maze ) { } ``` With factory: ``` void main() { s_cell[][] maze=make(5,5); print_maze(maze); } void print_maze(s_cell[][] maze) { } s_cell[][] make(int width, int height) { } ```
Re: bool passed by ref, safe or not ?
On Wednesday, 5 June 2024 at 01:18:06 UTC, Paul Backus wrote: The only safe values for a `bool` are 0 (false) and 1 (true). AFAIK that was fixed and now full 8-bit range is safe.
Re: "Error: `TypeInfo` cannot be used with -betterC" on a CTFE function
On Sunday, 7 April 2024 at 06:46:39 UTC, Liam McGillivray wrote: instantiated from here: `front!char` Looks like autodecoding, try to comment `canFind`.
Re: vibe.d still does not work on FreeBSD.
Docs say SSL_get0_peer_certificate was added in openssl 3.
Re: length's type.
On Tuesday, 13 February 2024 at 23:57:12 UTC, Ivan Kazmenko wrote: I do use lengths in arithmetic sometimes, and that leads to silent bugs currently. On the other hand, since going from 16 bits to 32 and then 64, in my user-side programs, I had a flat zero bugs because some length was 2^{31} or greater -- but at the same time not 2^{32} or greater. So, in D, I usually `to!int` or `to!long` them anyway. Or cast in performance-critical places. I had a similar bug in C++: the find function returns npos sentinel value when not found, it was assigned to uint and then didn't match npos on comparison, but it would if they were signed.
Re: length's type.
On Thursday, 8 February 2024 at 05:56:57 UTC, Kevin Bailey wrote: How many times does the following loop print? I ran into this twice doing the AoC exercises. It would be nice if it Just Worked. ``` import std.stdio; int main() { char[] something = ['a', 'b', 'c']; for (auto i = -1; i < something.length; ++i) writeln("less than"); return 0; } ``` Try this: ``` import std.stdio; int ilength(T)(in T[] a) { assert(a.length<=int.max); return cast(int)a.length; } int main() { char[] something = ['a', 'b', 'c']; for (auto i = -1; i < something.ilength; ++i) writeln("less than"); return 0; } ```
Re: what was the problem with the old post blit operator already ?
It was mostly fine, such types are not supposed to be immutable, but recently came an idea of reference counted strings, which need to be immutable for being strings.
New discussion
You can just post with a new title.
Re: length's type.
I have an idea to estimate how long strlen takes on an exabyte string.
Re: Accessing array elements with a pointer-to-array
On Thursday, 25 January 2024 at 20:11:05 UTC, Stephen Tashiro wrote: void main() { ulong [3][2] static_array = [ [0,1,2],[3,4,5] ]; static_array[2][1] = 6; } The static array has length 2, so index 2 is out of bounds, must be 0 or 1.
Re: Error "Outer Function Context is Needed" when class declared in unittest
Looks like the context is currently passed for nested functions, not for nested classes.
Re: Behaves different on my osx and linux machines
Maybe you're not supposed to print text while reading?
Re: Behaves different on my osx and linux machines
Maybe write and read lock each other, try to use puts: ``` bool done = false; while (!done) { puts("1"); auto result = ["echo", "Hello World"].execute; if (result.status != 0) { writeln(2); throw new Exception("echo failed"); } puts("2"); writeln(result.output); puts("3"); receiveTimeout(dur!"msecs"(-1), (LinkTerminated t) { writeln("Done"); done = true; }, ); writeln(4); } writeln("ByeBye"); ```
Re: Behaves different on my osx and linux machines
Add more debugging? ``` bool done = false; while (!done) { writeln(1); auto result = ["echo", "Hello World"].execute; if (result.status != 0) { writeln(2); throw new Exception("echo failed"); } writeln(result.output); receiveTimeout(dur!"msecs"(-1), (LinkTerminated t) { writeln("Done"); done = true; }, ); writeln(3); } writeln("ByeBye"); ```
Re: ImportC: Windows.h
Is GENERIC_WRITE awailable?
Re: ImportC: Windows.h
You can declare them ``` extern(C) void _InterlockedExchangeAdd(){ assert(false); } ```
Re: DMD: How to compile executable without producing .obj file?
The .exe is produced by the linker, which works with files: it takes one or more .obj files with program code and links them into and .exe file. I heard ldc has builtin linker or something like that, so hypothetically might be able to link on the fly.
Re: malloc error when trying to assign the returned pointer to a struct field
On Friday, 8 September 2023 at 13:32:00 UTC, rempas wrote: On Friday, 8 September 2023 at 13:05:47 UTC, evilrat wrote: ```d import core.stdc.stdlib; import core.stdc.stdio; alias u64 = ulong; alias i64 = long; struct Vec(T) { private: T* _ptr = null; // The pointer to the data u64 _cap = 0; // Total amount of elements (not bytes) we can store u64 _len = 0; public: /* Create a vector by just allocating memory for it. The null terminator is not set for strings as, the vector is considered empty and we should first push something to it in order to use it! */ this(i64 size) { this._len = 0; this._cap = size; static if (is(T == char)) { size += 1; } // Additional space for the null terminator this._ptr = cast(T*)malloc(size); } ref T opIndex(size_t idx) { return _ptr[idx]; } } extern(C) void main() //unittest { enum el = 3; auto vec = Vec!char(10); assert(vec._ptr); vec[el] = 'h'; assert(vec[el] == 'h'); printf("ptr = %p\n", vec._ptr); printf("vec ptr = %p\n", &vec[el]); printf("vec local = %p\n", &vec); printf("vec[%d] = %c\n", el, vec[el]); foreach (i; 0..vec._cap) { printf("-"); } printf("\n"); foreach (i; 0..vec._cap) { printf("%d", vec[i]); } printf("\n"); printf("run ok\n"); } ``` ldc2 -betterC -run membug.d output ``` ptr = 0x55cb701de2a0 vec ptr = 0x55cb701de2a3 vec local = 0x7fffa1542258 vec[3] = h -- 00010400 run ok ``` I have made a search on the web and I found out one thread that pointed out that it may be a Glibc error. However, because like I said the problem only happens when I assign the returned value to the `_ptr` field, I just wanted to post here in case someone has a similar experience and if it's a compiler bug in which case, we should report it. Did you run this example program above? Does it crash?
Re: AA vs __gshared
Your error is using allocating the object with malloc. Since gc doesn't see your AA, the AA is freed and you get UAF.
Re: Is it possible to make an Linux Executable Binary using a Windows Operating System? [compiling and linking]
You will also need crt1.o, crti.o, crtn.o and libc.a
Re: array index out of bound may not throw exception?
On Friday, 21 July 2023 at 23:40:44 UTC, mw wrote: Is there a way to let it report on the spot when it happens? On linux if you catch an exception and call abort, the debugger will show you where abort was called, on windows you can call DebugBreak function, the debugger will show where it was called.
Re: AA vs __gshared
On Friday, 28 July 2023 at 03:54:53 UTC, IchorDev wrote: I was told that using `__gshared` is quite a bit faster at runtime than using `shared`, but I also don't really know anything concrete about `shared` because the spec is so incredibly vague about it. The difference between them is purely formal if you're not on an old gdc, where shared was synchronized like C# volatile. If the crashes are frequent, can you reproduce a crash with a minimal amount of code, start many threads and access the locked AA concurrently.
Re: Print debug data
Naming is hard.
Re: Compiling to RiscV32
Maybe the problem is with va_list, try to compile with -mtriple=riscv64-unknown-linux -mcpu=generic-rv64
Re: Compiling to RiscV32
Probably bug in druntime, v-functions shouldn't have `pragma(printf)`, because they don't have arguments to check.
Re: Compiling to RiscV32
Worked for me on ldc 1.20 https://forum.dlang.org/post/vuxuftogvszztdrrt...@forum.dlang.org
Re: Compiling to RiscV32
You try to use C declarations, but they are specific to each C library, and different C libraries have different declarations, so headers can't decide which C library declarations to use. Try -mtriple=riscv32-unknown-linux
Re: Log rotation in std.logger.filelogger
I suppose you write a custom logger for that or take an already written one from code.dlang.org
Re: Convert binary to UUID from LDAP
This guid is (int,short,short,byte[8]) in little endian byte order. So if you want to convert it to big endian, you'll need to swap bytes in those int and two shorts. ``` ubyte[] guid=... int* g1=cast(int*)guid.ptr; *g1=bswap(*g1); ```
Re: Convert binary to UUID from LDAP
This guid is (int,short,short,byte[8]) in little endian byte order. So if you want to convert it to big endian, you'll need to swap bytes in those int and two shorts. ``` ubyte[] guid=... int* g1=cast(int*)guid.ptr; *g1=bswap(*g1); ```
Re: Best way to read/write Chinese (GBK/GB18030) files?
https://dlang.org/phobos/std_stdio.html#rawWrite
Re: Threads
static is thread local by default. ``` module main; import app; import core.thread; int main(string[] args) { static shared int result; static shared string[] args_copy; static void app_thread() { App app = new App(); result = app.run(args_copy); } args_copy = cast(shared)args; // Running app interface in a thread; Thread thread = new Thread(&app_thread).start(); thread.join(); return result; } ```
Re: Best way to read/write Chinese (GBK/GB18030) files?
On Monday, 13 March 2023 at 00:32:07 UTC, zjh wrote: Thank you for your reply, but is there any way to output `gbk` code to the console? I guess if your console is in gbk encoding, you can just write bytes with stdout.write.
[OT] (Go) Do I read it right?
https://github.com/dominikh/go-tools/issues/917 How go programmers cope with this feature?
Re: Non-ugly ways to implement a 'static' class or namespace?
My point is you know you're just picky.
Re: Non-ugly ways to implement a 'static' class or namespace?
On Monday, 13 February 2023 at 08:22:06 UTC, ProtectAndHide wrote: Chris Lattner outlines the reasons for removing it in Swift 3.0 here: https://github.com/apple/swift-evolution/blob/main/proposals/0004-remove-pre-post-inc-decrement.md So your complaint is that you agree with Chris Lattner and disagree with others?
Re: Non-ugly ways to implement a 'static' class or namespace?
On Friday, 10 February 2023 at 21:52:02 UTC, ProtectAndHide wrote: Well in Swift, there is no problem .. at all. Why is it a problem in D then? (and I mean technically). What about the increment operator `++` ?
Re: Non-ugly ways to implement a 'static' class or namespace?
On Friday, 10 February 2023 at 14:17:25 UTC, Kagamin wrote: Pretty sure you can strip namespaces in any language that has namespaces, C# routinely does it and refers to all types with their nonqualified names. It even has Keys enum: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.keys which is referred to as Keys after stripping the System.Windows.Forms namespace. An example from KeePass: https://github.com/dlech/KeePass2.x/blob/VS2022/KeePass/Util/SendInputExt/SiCodes.cs#L86
Re: Non-ugly ways to implement a 'static' class or namespace?
On Monday, 23 January 2023 at 00:36:36 UTC, thebluepandabear wrote: It's not a freedom issue, it's a library-design issue. Some libraries want to incorporate a namespace-like design to force the user to be more 'explicit' with what they want. SFML has a `Keyboard` namespace which has a `Key` enum. The user is 'forced' (although I am not sure if this is the case since it's C++) to use the `Keyboard.` declaration before using the `Key` enum. Looking at code block 1 and 2, which makes more sense? Pretty sure you can strip namespaces in any language that has namespaces, C# routinely does it and refers to all types with their nonqualified names. It even has Keys enum: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.keys which is referred to as Keys after stripping the System.Windows.Forms namespace.
Re: Logging logs in Windows
On Saturday, 4 February 2023 at 13:31:41 UTC, Alexander Zhirov wrote: I understand that programming under Windows is a shame for a programmer, but is there really no ready-made solution for using the system log in Windows? It would be a logging library like log4j that would have different logging backends.
Re: How often I should be using const? Is it useless/overrated?
On Friday, 18 November 2022 at 17:57:25 UTC, H. S. Teoh wrote: You're looking at it the wrong way. The kind of issues having const would solve is like when your function takes parameters x, y, z, and somewhere deep in the function you see the expression `x + y*z`. If x, y, and z are const, then you immediately know what the value of this expression is. However, if they were not, then you'd have to trace through all of the preceding code to figure out whether their values have changed, and how they have changed. The former makes the code easier to understand, the latter adds complexity to understanding the code. AFAIK Rust allows shadowing (intentionally) to solve usability problems with immutable variables, so when deep in the function you see `x+y*z`, you can't immediately tell its value, because the variables could be previously shadowed and you have to trace through all of the preceding code to figure it out :)
Re: aa.keys, synchronized and shared
This works for me: ``` synchronized final class SyncAA(K, V) { this(K key, V val) { sharedTable[key]=val; } V opIndex(K key) { return sharedTable[key]; } V opIndexAssign(V value, K key) { return sharedTable[key]=value; } const(K[]) keys() const { return unsharedTable.keys; } void remove(K key) { sharedTable.remove(key); } V get(K key, lazy V defaultValue=V.init) { auto p = key in sharedTable; return p ? *p : defaultValue; } private: V[K] sharedTable; inout(V[K]) unsharedTable() inout { return cast(inout(V[K]))sharedTable; } } shared SyncAA!(string,string) saa; void f() { saa=new shared SyncAA!(string,string)("1","2"); saa.keys(); saa["12"]="34"; saa.remove("12"); } ```
Re: aa.keys, synchronized and shared
With allocation: ``` synchronized final class SyncAA(K, V) { V opIndex(K key) { return sharedTable[key]; } V opIndexAssign(V value, K key) { return sharedTable[key]=value; } const(K[]) keys() const { return unsharedTable.keys; } void remove(K key) { sharedTable.remove(key); } V get(K key, lazy V defaultValue=V.init) { auto p = key in sharedTable; return p ? *p : defaultValue; } private: V[K] sharedTable; ref inout(V[K]) unsharedTable() inout { return *cast(inout(V[K])*)&sharedTable; } } shared SyncAA!(string,string) saa; void f() { saa=new shared SyncAA!(string,string); saa.keys(); saa["12"]="34"; saa.remove("12"); } ```
Re: aa.keys, synchronized and shared
Try this: ``` synchronized final class SyncAA(K, V) { V opIndex(K key) { return sharedTable[key]; } V opIndexAssign(V value, K key) { return sharedTable[key]=value; } const(K[]) keys() const { return unsharedTable.keys; } void remove(K key) { sharedTable.remove(key); } V get(K key, lazy V defaultValue=V.init) { auto p = key in sharedTable; return p ? *p : defaultValue; } private: V[K] sharedTable; ref inout(V[K]) unsharedTable() inout { return *cast(inout(V[K])*)&sharedTable; } } void f(shared SyncAA!(string,string) a) { a.keys(); a["12"]="34"; a.remove("12"); } ```
Re: Make IN Dlang
Another idea is to separate the script and interpreter then compile them together. ``` --- interp.d --- import script; import ...more stuff ...boilerplate code int main() { interpret(script.All); return 0; } --- script.d --- #! ? module script; import mind; auto All=Task(...); ...more declarative tasks --- run --- dmd /usr/local/interp.d /path/to/script.d ```
Re: Make IN Dlang
But embedded sdl is likely to be dwarfed by the actual code anyway.
Re: Make IN Dlang
On Tuesday, 1 November 2022 at 23:40:22 UTC, Christian Köstlin wrote: I am still trying to find answers to the following questions: 1. Is it somehow possible to get rid of the dub single file scheme, and e.g. interpret a full dlang script at runtime? If there was an interpreter like ``` #!/bin/mind ...code ``` maybe it could run dub with right options and thus won't need a build script.
Re: dub ldc2 static linking
On Friday, 28 October 2022 at 02:46:42 UTC, ryuukk_ wrote: I'm just right now having an issue with glibc version mismatch for my server Just compile with an old enough glibc, 2.14 works for me.
Re: Is "auto t=T();" not the same as "T t;"?
Looks like explicitly initialized variable in this case allocates array literal. Uninitialized variable is initialized with init pattern. This may be correct as uninitialized variable isn't guaranteed to hold a value most useful for you, it's only guaranteed to hold a defined value.
Re: Static executable (ldc, linux)
ldc2 -link-defaultlib-shared=false or something like that
Re: How to workaround on this (bug?)
Provide two functions and let the caller choose ``` void fun(ref Variant v) nothrow { } void fun2(Variant v) { fun(v); } ```
Re: toString doesn't compile with -dip1000 switch
Bar.toString is typed `@system`.
Re: char* pointers between C and D
This is how to do it the D way: ``` int main(string[] args) { string ch1 = "Hello World!"; char[] ch2="Hello World!".dup; string s1=ch1[1..$]; char[] s2=ch2[1..$]; writeln(s1); writeln(s2); return 0; } ```
Re: null == "" is true?
On Tuesday, 19 July 2022 at 18:05:34 UTC, Antonio wrote: In a relational database, `NULL` is not the same that `""`... and `NULL` is not the same that `0`. Are semantically different and there are database invariants (like foreign keys) based on it. Trying to "mix" this concepts in a database is a mistake. So, it's an implementation detail or a relational database that leaks into business logic because nobody thought about it? Just because a relational database has many features, it doesn't mean business logic must use them all, it must use only what makes sense for business logic. When you treat with Domain Models, you try to represent this semantics in all levels of your software... including APIs What semantics your domain models implement? Is it semantics of all features of a relational database or is semantics of business logic?
Re: null == "" is true?
Also what's the difference between null and empty phone number?
Re: null == "" is true?
On Tuesday, 19 July 2022 at 10:29:40 UTC, Antonio wrote: The summary is that a DTO that works like a Map needs to represent the absent key ant this is not the same that the Null value Example: ```d struct Null { /*...*/ } struct Undefined { /*...*/ } struct ContactDto { DtoVal!(Undefined, string) name DtoVal!(Undefined, Null, string) phonenumber, DtoVal!(Undefined, AddressDto) address } // ... ContactDto data = {phonenumber:Null(), address:{city:{code:"BCN"}}}; updateContact(id, data); ``` As I understand, in your scenario there's no difference between null string and empty string, they both work like empty string, and D treats them as empty string. That's what I mean when I said that distinction between null and empty is meaningless.
Re: null == "" is true?
On Monday, 18 July 2022 at 21:23:32 UTC, Antonio wrote: I will study it in detail and report (if required). May be, I will write the DTO problem with D article if I find time in august. In my experience null and empty in DTOs usually play the same logical role. It's a very contrived technical difference without practical usage, such distinction is way beyond any business logic. Even if you implement this distinction, I'm not sure anybody will carefully pay attention to it. In languages that make difference between null and empty, null is often replaced with empty to work around problems with null, such codebase can't properly preserve null values.
Re: null == "" is true?
On Tuesday, 12 July 2022 at 20:36:03 UTC, Antonio wrote: Honestly, it is difficult to understand for newcomers... there is a reason, but there is a reason in javascript for `0 == ''` too People would have different preferences there. Difference between null and empty is useless. D does the right thing here, what other languages do, is a mistake. If you want such difference, use the Nullable wrapper or Algebraic.
Re: How to debug thread code
On Sunday, 10 July 2022 at 21:27:08 UTC, Hipreme wrote: "Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code)." Open the threads window and click on threads there, their stack will be in the stack window.
Re: freebsd dub linker error
Try to run clang with -v option and compare with gcc.
Re: Is there a way to not escape slashes when parsing JSON?
On Monday, 21 February 2022 at 09:04:06 UTC, bauss wrote: Why are we even escaping them by default, it should be the other way around, that slashes are only escaped if you ask for it; that's how it literally is in almost every JSON library. Really? I always see escaped slashes in JSON, e.g. wikipedia does this, but everything else too.
Re: How to verify DMD download with GPG?
3AAF1A18E61F6FAA3B7193E4DB8C5218B9329CF8 is 0xDB8C5218B9329CF8 This shortening was supposed to improve user experience.
Re: Cross Compile to Linux from Windows using LDC?
Isn't cross-linker enough? My regular mingw build of ld says it supports elf64-x86-64 traget, so I assume something like this should be enough: ld -b elf64-x86-64 -L lib --dynamic-linker /lib64/ld-linux-x86-64.so.2 --as-needed --gc-sections -s lib/crt1.o lib/crti.o my.o -lc lib/crtn.o
Re: How to print unicode characters (no library)?
On Monday, 27 December 2021 at 11:21:54 UTC, rempas wrote: So should I just use UTF-8 only for Linux? What about other operating systems? I suppose Unix-based OSs (maybe MacOS as well if I'm lucky) work the same as well. But what about Windows? Unfortunately I have to support this OS too with my library so I should know. If you know and you can tell me of course... https://utf8everywhere.org/ - this is an advise from a windows programmer, I use it too. Windows allocates a per thread buffer and when you call, say, WriteConsoleA, it first transcodes the string to UTF-16 in the buffer and calls WriteConsoleW, you would do something like that.
Re: How to print unicode characters (no library)?
On Monday, 27 December 2021 at 07:29:05 UTC, rempas wrote: How can you do that? I'm trying to print the codes for them but it doesn't work. Or you cannot choose to have this behavior and there are only some terminals that support this? Try it on https://en.wikipedia.org/wiki/Teletype_Model_33
Re: How to print unicode characters (no library)?
D strings are plain arrays without any text-specific logic, the element is called code unit, which has a fixed size, and the array length specifies how many elements are in the array. This model is most adequate for memory correctness, i.e. it shows what takes how much memory and where it will fit. D doesn't impose fixed interpretations like characters or code points, because there are many of them and neither is the correct one, you need one or another in different situations. Linux console one example of such situation: it doesn't accept characters or code points, it accepts utf8 code units, using anything else is an error.
Re: French and Greek strings
You can use the string type to hold non-ascii characters. Just a substring of another string.
Re: abs and minimum values
Unsigned integers aren't numbers. assert(-abs(1)<0);
Re: Analyze debug condition in template
You can do something like ```d enum LogSettings { func1,func2,func3 } alias logger!LogSettings logf; void func1() { logf(...); } ``` Then the logger can inspect symbols in the template argument and compare their names to the function name.
Re: Analyze debug condition in template
`debug(func1)writefln(...)` But specify a global debug version for the compiler: `dmd -debug=func1 app.d`
Re: Why do we have Dmain?
Actually C runtime is many megabytes in size.
Re: How to test if a string is pointing into read-only memory?
On Tuesday, 12 October 2021 at 08:19:01 UTC, jfondren wrote: and string literals weren't reliably in read-only memory as recently as early 2017: https://github.com/dlang/dmd/pull/6546#issuecomment-280612721 Sometimes sections have defined symbols for start and end, you can check if the string is in rdata section. On windows you can test it generically with IsBadWritePtr function.
Re: Python's list equivalent with std.variant?
On Sunday, 3 October 2021 at 22:22:48 UTC, rjkilpatrick wrote: ```d import std.stdio : writeln; import std.variant; import std.conv; // Arbitrary super class class SuperClass { this() { } } // Derived class with members class DerivedClass : SuperClass { public: this(float a) { this.a = a; } float a; } class OtherDerivedClass : SuperClass {} void main() { // When we use `SuperClass[] list;` here, we find 'a' is hidden by the base class Variant[] list; // Attempting to append derived class instances to list list ~= new DerivedClass(1.0f); list ~= new OtherDerivedClass; list[0].a; list[0].to!(get!(list[0].type)).a.writeln; } ``` Looks like you want full duck typing. Dynamic objects are just hashtables of properties, so an array of them is something like this: Variant[string][] list; Variant[string] obj; obj["a"]=Variant(1.0f); list[0]["a"].get!float.writeln;
Re: better c fibers
On Tuesday, 21 September 2021 at 09:37:30 UTC, Abby wrote: Hi there, I'm new in dlang I specially like betterC. I was hoping that d fibers would be implemented in without using classes, but there are not. On windows you can use the fiber api https://docs.microsoft.com/en-us/windows/win32/procthread/fibers just as you would do in C.
Re: Scope with owner types
Yes, the `return` attribute is what should do it. You also need to compile the code with -dip1000 option.
Re: Run-time setting of immutable variable?
If you want only address, you can keep it as size_t: ubyte[10] Arr; immutable size_t Address; static this() { Address = cast(size_t)(&Arr[0]); }
Re: Error load: QtE5Widgets64.dll
Maybe you're trying to load a 32-bit library into a 64-bit process.
Re: std.stdio.File is throwing with the message of: "Access Violation"
On Wednesday, 18 August 2021 at 17:56:53 UTC, Ruby The Roobster wrote: When I removed those two lines of code, the program ran perfectly without displaying any error or throwing any exception... The errors aren't always nicely located and can be elsewhere. Try to write a minimal runnable example. Also that cast won't work, you don't really know what you're doing there, use toStringz instead.
Re: Shift operator, unexpected result
On Wednesday, 9 June 2021 at 19:13:10 UTC, JG wrote: produces: 123 I would expect 0. What is the rationale for this behaviour or is it a bug? Processor just takes lower 6 bits for the shift amount and those hold zero in your case, shifting by 65 will shift by 1.
Re: How to cross build a RISC-V target betterC code using LDC on x86-64 machine
https://forum.dlang.org/post/koxqrqqzadfefbgkd...@forum.dlang.org
Re: How do I create classes dynamically?
On Friday, 16 April 2021 at 08:31:27 UTC, Imperatorn wrote: One example would be a repl That has little to do with what OP meant.
Re: How do I create classes dynamically?
On Wednesday, 14 April 2021 at 20:38:16 UTC, Mario wrote: Maybe I am just too short in D, but I wanted to find out if it is possible to create classes dynamically. My problem is, I just don't know where to start reading. Maybe at mixin templates? CreateClassWithName!("MyDynamicClassName"); should create the following class to work with dynamically: class MyDynamicClassName { this() { writeln("I was not written, but still I exist!"); } } So that I in the end by means of MyDynamicClassName cls = new MyDynamicClassName; String mixins is D replacement of macros for code generation. Works like this: ```d mixin("class MyDynamicClassName { }"); MyDynamicClassName cls = new MyDynamicClassName; ```
Re: "this" as default parameter for a constructor.
class foo { this ( foo p /* , other params */ ) { parent = p; } foo create() { return new foo(this); } void use() { foo f = create(); } foo parent; }
Re: Why I need DUB? Will never DMD don't just use import for import packages?
On Monday, 29 March 2021 at 19:06:33 UTC, Marcone wrote: Why can't I just use: import vibe.vibe; for import packages like Nim or Python? Why I still use DUB? Theoretically an rdmd-like tool can automatically infer dependencies from imports (autodub?). But it can also easily expose you to a supply chain attack.
Re: Don't allow to reassign, but content is editable
struct A { private int[] a; this(int[] b){a=b;} int[] c(){ return a; } @disable void opAssign(); } struct B { A a; this(int){ a=new int[5]; } int[] b(){ return a.c; } void f(){ a=new int[5]; } }
Re: Can I make this work?
struct S { this(string s) { type = Type.type1; } this(int n) { type = Type.type2; } Type type; int n; } int value(S s)() { static if(s.type == Type.type2) { // do something } return n; }
Re: How to delete dynamic array ?
On Thursday, 18 March 2021 at 17:57:30 UTC, Patrick Schluter wrote: It's important to understand that [] is just a practical syntax for a fat pointer. Thinking of [] just as a fancy pointer helps imho to clarify that the pointed to memory nature is independant of the pointer itself. I think they are arrays alright. What's missing is expression of ownership, because D follows traditional language design approach, and traditionally ownership wasn't expressed in language and was done by convention.
Re: tiny alternative to std library
I suppose commercial vendors aren't interested in suckless paradigm, so this library is for people and only for people.
Re: tiny alternative to std library
On Wednesday, 3 March 2021 at 20:54:43 UTC, Anthony Quizon wrote: I'm having some success pulling out small bits of code from other libraries and keeping things minimal and c-style-ish. If you're really ok with minimalism, I'm writing such a library https://filebin.net/7gtyh5j01gk1ofly I didn't publish it anywhere yet, feel free to do so. Not everything is finished there yet.
Re: Name mangling problem with tiny Windows 10 load-time DLL example
mangleof should give _D4file6addOneFiZi, not _D6patron6addOneFiZi
Re: Real simple unresolved external symbols question...
Add libraries that provide missing symbols.
Re: Compile time check for GC?
You can make it opt in, it's insurance.
Re: Compile time check for GC?
You can define a symbol that will conflict with GC and prevent linking with it.
Re: Surprising behaviour of std.experimental.allocator
Try to compile in debug mode, maybe you breach some contract.
Re: Updating to newer files with different disk formats
You can compare like time1 > time2 + 100.msec, though posix specifies only second precision.
Re: CMD && comand not work
On Thursday, 10 December 2020 at 21:01:30 UTC, Marcone wrote: In this very generic example && not work to finalize the instruct and start a new instruct. Yes, I know dmd can build and run without it, but this is only a example. execute(["cmd", "/c", "dmd test.d", "&&", "start test.exe"]); How can I substitute && ? Try other variants: execute(["cmd", "/c", "dmd test.d && start test.exe"]); execute(["cmd", "/c", "dmd", "test.d", "&&", "start", "test.exe"]);
Re: Is garbage detection a thing?
On Sunday, 29 November 2020 at 19:09:07 UTC, Mark wrote: Looking at Ada now. I found: Ada is not good for me. It has no augmented assignment. It's just that I want DRY because I use very verbose variable names Using a reasonable naming convention should be much easier than looking for a perfect custom language. Well, another variant is zig, which was supposed to be C but safe.