SIGSEGV: Illegal storage access. (Attempt to read from nil?) in coroutines

2023-12-18 Thread mashingan
FYI, Fiber is used as cooperative multitasking instead of parallel execution and it uses single-thread. Here's the example: from std/strformat import fmt from std/coro import run, CoroutineRef, start, wait, suspend from std/os import sleep import std/[monotimes, times]

SIGSEGV: Illegal storage access. (Attempt to read from nil?) in coroutines

2023-12-18 Thread mashingan
You need to `run()` it first before even waiting those fibers. `Start` doesn't run immediately. import std/[strformat] import std/[os] import std/[times,monotimes] import std/[coro] proc doSleep() = sleep 3000 var fibers: seq[CoroutineRef] = @[

proc/func/method: syntax

2023-11-15 Thread mashingan
Having `:` as return type for func/proc is actually consistent. Seeing ":" means afterward "there's a type for it". It's the consistent with `var ident: ThisIsTheType` or change that `var`, `let`, `const` etc. To reinforce that observation, the argument of function also has `:` for its type sy

Playing with type states and lifetime-tracking hooks, facing some unexpected behavior

2023-10-22 Thread mashingan
func condense[T](e: Experiment[T, sGas]): var Experiment[T, sLiquid] = cast[ptr Experiment[T, sLiquid]](e.addr)[] Run Shouldn't the `e` is `var Experiment[T, sGas]` ? Is that typo or intended? If it's intended, based on the usage, this shouldn't compile though because the

Nim boilerplate

2023-10-11 Thread mashingan
Reworked your example, apparently the `a` in your concept is not concrete type (or just alias?) which simply can be anything, hence you need to "pin" it down with `T` as anything. By defining the argument as concrete type, it can match the type: from math import PI,pow from std

Nim boilerplate

2023-10-11 Thread mashingan
I tried your example but commented out the "boilerplate" func defs and it compiled fine.

Basic Async Questions

2023-08-22 Thread mashingan
> What is AsyncFD in terms of meaning? (I'm aware it's a distinct int32, but > what does that mean?) FD is abbreviation of file descriptor, on Windows it's called Handle. FD/Handle is basically just and object and with AsyncFD meaning can be applied for asynchronous operation. On Windows it's t

efficient way of running proc at a given time, that can be changed

2023-08-22 Thread mashingan
> But I dont realy want to create a new thread every time. So is there a better > way of achieving this? (it may be linux specific) Make the proc is always running the background as a dedicated thread but lock it to save the cpu loop and only continue if the lock receiving signal. For example h

FFI: How to bind to a cpp std::vector which contains another std::vector in nim?

2023-07-09 Thread mashingan
Put `/*TYPESECTION*/` in the very first of your emit pragma. Ref:

Undeclared field - Unrecognized proc

2023-06-28 Thread mashingan
> Because it is supposed to only have > >> method HookCallback(nCode: int32; wParam: WPARAM;lParam: LPARAM): LRESULT change the proc definition to proc HookCallback(nCode: int32; wParam: WPARAM;lParam: LPARAM): LRESULT Run send the object you want to access by casting

How to add a file to a project without importing

2022-11-15 Thread mashingan
By `include` -ing it: `include startup` . Combine with `when` block you can decide whether to include `startup1.nim` or `startup2.nim` or others during the compilation. @templatedperson > What's the use case for this? To treat both `main.nim` and `startup.nim` as a single package, as opposed t

Using return in templates returns nil

2022-08-26 Thread mashingan
I usually define template without returning when I want it as statement executions: template doStmt = echo "do this" template doubleInt(x: int): untyped = x * 2 doStmt() echo doubleInt(3) Run Especially when I want the template to ch

Setting compiler-style defines in normal code?

2022-06-24 Thread mashingan
> It's also easy to do in a config.nims file but affect all the Nim files in > the directory. Naming with `filename.nims` should affect only the `filename.nim` . At least it works like that when I tried compiling/running a single module file.

Example code with multithreading and channels is failing

2022-06-22 Thread mashingan
Sorry, I run your example and it's immediately failing with this message: D:\test.nim(203) receiver Error: unhandled exception: Message received is invalid: myMsg.str (This is a test for: 19) != "This is a test for: 27" [ValueError] D:\test.nim(203) receiver Error: unh

Example code with multithreading and channels is failing

2022-06-22 Thread mashingan
`createThread` is creating and running it immediately and you're calling it each time you invoke `addSenderThreadWithChannel`

Example code with multithreading and channels is failing

2022-06-22 Thread mashingan
In your gist, you're not using the channel.lock itself. Try to lock/unlock (or acquire/release?) when reading or writing to channel.list. You can also try separate lock for fetching and assigning the channel to the list, but using the same lock for fetching/assigning channel should be simpler.

Nim with curly brace and tab

2021-12-18 Thread mashingan
My superficial preference with braces is simply easier to navigate to end of block by pressing `%` with vim. Other than that, it doesn't really matter.

Macros: why and/or when to use them?

2021-11-26 Thread mashingan
I remember answering this kind of exact question about a year ago on Nim subreddit [https://www.reddit.com/r/nim/comments/jg83c9/macros_vs_functions/g9pi2v3/?utm_source=reddit&utm_medium=web2x&context=3](https://www.reddit.com/r/nim/comments/jg83c9/macros_vs_functions/g9pi2v3/?utm_source=reddit&u

Direct I2C device access with pure Nim

2021-09-18 Thread mashingan
Is the int actually int32 or int64? Depend on your arch, you need to cast to seq[uint8] instead of converting to uint8. Maybe it should be like this (untested): import sequtils proc i2c_write(busNo, devAddress, regAddress: int64; data: seq[int64]) : int = let i2cPo

What is the role of the expression "{.importc.}" when transpiling to JavaScript?

2021-09-14 Thread mashingan
> What is the point of an {.importc.} Importing and using [js fetch with importc](https://github.com/mashingan/anonimongo/blob/develop/examples/uploadfile/appjs.nim#L5) example. > What is the point of an {.exportc.} Calling the callback which defined with exportc pragma in [appjs.nim]

Attempt to read from nil, Arc bug?

2021-06-23 Thread mashingan
> Could you share the code that you modified? Just changed a line, diff: 56 -var buf: array[1, char] 56 +var buf: array[512, char] Run The Dockerfile is FROM nimlang/nim:alpine as build COPY example.nim / COPY example.nim.cfg / RUN

Attempt to read from nil, Arc bug?

2021-06-23 Thread mashingan
> I missed this, thanks! It does still SIGSEGV though. By changing the buffer to 512 as @planetis mentioned, it's running fine (?) when I tried it on Alpine Docker. I got below from the console and it's never quitting (and also eating the cpu because of `while true: discard` ), is this the expe

Why does Nim compiler allways depends on another's language compiler?

2021-06-23 Thread mashingan
> but by compiling to another language doesn't that limit Nims performance to > that language? i.e. Nim can only ever be as fast as C because it compiles to C In case you didn't know/forgot, you can write an inline assembler.

Suddenly getting infinite genericDeepCopy recursion

2021-05-01 Thread mashingan
I happened to see this error when doing some [(old) example](https://github.com/mashingan/nim-etc/tree/master/armyfactions) in Nim, was 0.17.0. >From the message, the debug build has call depth limit, in my example above, I >couldn't really avoid the recursion since it's trav

Suddenly getting infinite genericDeepCopy recursion

2021-05-01 Thread mashingan
Something you can try: 1\. Try cleaning the `~/.nimcache` or recompile your app with `-f` or `--force` option. 2 .Try to compile with different build mode, just for reference. 1. Reset to the last working commit, (#1) and add your change and compile it gradually to find out which change is pr

Found article on concurrency: "Go statement considered harmful"

2021-03-20 Thread mashingan
Nah, the article is just an ads for the lib which give nothing new, it's just: var op1 = await myFunc() var op2 = await anotherFunc() # don't start anotherFunc when myFunc not finished yet Run if we "structurize" our operations as synchronous tasks. or

Cancelation points in async

2021-01-02 Thread mashingan
Modifying your 2nd example import std/[asyncdispatch, sugar] var connectionAlive: bool = true type Cancellation = proc(): bool proc test(c: Cancellation) {.async.} = var x = 0 while connectionAlive: await sleepAsync(1000) # await for heartbea

Example of a simply UDP client

2020-11-30 Thread mashingan
> But, if I set the address to 192.168.1.45, > > socket.bindAddr(Port(cfgPort), localhost) This is the problem, change it to empty string which set it to `ADDR_ANY` in order the bound address able to listen to any address e.g. socket.bindAddr(Port cfgPort) Run Just f

How can I do 'fetch' or 'XMLrequest' thing in JS?

2020-11-27 Thread mashingan
With importc pragma, you can write like the example here: [its type import definition](https://github.com/mashingan/nim-js-loan-calculator/blob/master/loancalculator.nim#L10-L16) , [its methods definition](https://github.com/mashingan/nim-js-loan-calculator/blob/master/loancalculator.nim#L30

SSL error using httpClient

2020-10-31 Thread mashingan
For Nim v1.4.0, the proc `net.newContext` has changed the interface with keys and certificates related files. You have to download the certificates pem files for example here: and you can do import httpclient, net let ctx = newCont

How can i separate the integer part of a number from its decimal part ?

2020-09-01 Thread mashingan
Try: import rationals, math var num = 786.654 ratNum = num.toRational numPart = floor num decPart = ratNum - numPart.toRational echo numPart echo decPart.toFloat Run If the decimal is important, it's usually preferable to wo

Problem with template and async

2020-08-27 Thread mashingan
I think it's because async proc is transformed into iterator so you can't return immediately. This works import asyncdispatch template test: untyped = result = true proc main(): Future[bool] {.async.} = test() doAssert waitFor main()

Why use range[0..255] instead of char?

2020-08-12 Thread mashingan
> Why would one limit the range of possible values for r,g and b with > range[0..255] instead of using the char type? This is a matter of representation, RGB is represented as range[0..255] to clearly indicate as such while char is, well, literally a character. I rarely use the char past of 'z'

embed DLL into EXE?

2020-07-18 Thread mashingan
Like this import streams type AddXY = proc(x, y: int): int {.cdecl.} const dll = "libadd.dll" bin = readFile dll size = bin.len let inmem = alloc size readsize = newStringStream(bin).readData(inmem, size) handle = MemoryL