No `[]` iterators for collections?
I always assumed that that this code wouldn't allocate a new seq, and just iterate over the existing one: for it in someseq[1..^1]: echo x Run But I don't see such iterators in system.nim. Is this an oversight?
Re: Funny, we can cast ptr to var for proc arguments
No cast needed: proc foo(x: var int) = discard var p: ptr int foo p[] Run
Re: closure procs with the javascript backend
Did you try adding closure annotation the suspect procs yourself? If it works, you could create a pull request.
Re: How to implement observer (publish/subscribe) pattern?
This should be enough, you can capture whatever type you want inside a closure. type Publisher = ref object subs: seq[proc(data: int)] Run
Re: Is it possible for a macro to know the context it is used?
If there's a pattern of doing init(...), evaluate: ..., let ... = getValue(), then you can convert it to something like this: dsl: algo1 as x: echo x algo2(x) as y: echo y Run
Re: Is it possible for a macro to know the context it is used?
This is how I would do it import macros macro dsl(nodes) = result = newStmtList() for n in nodes: var value: NimNode if eqIdent(n[0], "algo1"): value = newLit"Foo" elif eqIdent(n[0], "algo2"): value = newLit(123) else: error "Unexpected ident: ", n[0] for kid in n[1]: if eqIdent(kid[0], "evaluate"): let body = kid[1] result.add quote do: template value: untyped = `value` `body` else: error "Unexpected ident: ", kid[0] dsl: algo1: evaluate: echo "[algo1] Evaluation is " & $value algo2: evaluate: echo "[algo2] Evaluation is " & $value Run
Re: Multithreading Pt 2.5: Nichecache
It's just a funny way of using command invocation syntax, usually used without braces: if unlikely position < 0: Run
Re: Reference to sequence
Re: Is there a simple example on how to create a Windows UI
I dont know of any, but I know that theres a webview library on nimble so it should be pretty straightforward
Re: Is there a simple example on how to create a Windows UI
If you're fine with the UI being minimal, wNim should be okay. If you want it to be shiny and don't mind html/css, maybe the simplest approach would be to use Karax and webview.
Re: NOOB: Few simple questions ...
sugar.collect can be used to convert between different collection types.
Re: Sequential execution on what appears to be async code
Using asyncCheck instead of await in main should work, maybe
Re: Nim programming book for kids
Programming is almost certainly easier to into, if just because it's easier to go from theory to practice and see the results.
Re: Return complex type from thread
You didn't change .to[:T] to .tp[:ref T]
Re: Enum bitmasks (flags)
You can also create a set of all possible values like this: {State.low .. State.high} Run
Re: Updating Element style via Karax (noobish?)
You can also setAttr on a style
Re: Type safe opengl
There's also fancygl: [https://github.com/krux02/opengl-sandbox/blob/master/examples/hello_triangle.nim](https://github.com/krux02/opengl-sandbox/blob/master/examples/hello_triangle.nim)
Re: Casting basics (a few questions)
In your example let value = cast[uint8](address) Run should be let value = cast[uint8](address[]) Run You should use UncheckedArray here for nicer syntax: const size = 3 var buf = cast[ptr UncheckedArray[uint8]](create(uint8, size)) buf[0] = 0 buf[1] = 1 buf[2] = 2 var data = newSeq[uint8](size) for i in 0 ..< size: data[i] = buf[i] echo data Run
Re: Nested list comprehension
As I said, you must use the devel version. You can install it with a tool called choosenim.
Re: Nested list comprehension
I generally only put brackets where neccessary. You can write this using devel version of nim (you can use choosenim) import tables, sugar, sets, sequtils proc cross(xs, ys: string): seq[string] = for x in xs: (for y in ys: result.add x & y) let rows = "ABCDEFGHI" cols = "123456789" squares = cross(rows, cols) let unitSeq = collect(newSeq, for c in cols: cross(rows, $c)) & collect(newSeq, for r in rows: cross($r, cols)) & collect(newSeq, for rs in ["ABC", "DEF", "GHI"]: for cs in ["123", "456", "789"]: cross(rs, cs)) let units = collect newOrderedTable: for s in squares: {s: collect(newSeq, for u in unitSeq: (if s in u: u))} let peers = collect newOrderedTable: for s in squares: var v = units[s].foldl(a & b) v.delete v.find s {s: v} echo "unitSeq:"; for u in unitSeq: echo u echo "\nunits"; for k, v in units: echo k, ": ", v echo "\npeers"; for k, v in peers: echo k, ": ", v Run For some reason peers isn't what it should, but the rest is ok.
Re: Why does `setCommand` exist?
I still don't get it. Setting -d:js in my config file makes nimble build output js code instead of a binary just as much as setCommand js.
Re: Nested list comprehension
This should work: import tables, strutils proc cross(xs, ys: string): seq[string] = for x in xs: (for y in ys: result.add x & y) let rows = "ABCDEFGHI" cols = "123456789" squares = cross(rows, cols) var unitSeq: seq[string] for c in cols: unitSeq.add cross(rows, $c) for r in rows: unitSeq.add cross(cols, $r) for rs in ["ABC", "DEF", "GHI"]: (for cs in ["123", "456", "789"]: unitSeq.add cross(rs, cs)) var units, peers: Table[string, seq[string]] for s in squares: var tmp: seq[string] for u in unitSeq: (if s in u: tmp.add u) units[s] = tmp if (let i = tmp.find s; i >= 0): tmp.del i peers[s] = tmp Run
Re: Documenting one liner
proc myProc = ##[my comment]## discard myProc() Run .
Why does `setCommand` exist?
As far as I can tell setCommand "js" Run is equivalent to switch "d", "js" Run Is it?
Re: How to declare a thread-global variable?
You can create a pointer. import tables var t = create Table[int, int] t[] = toTable {1: 2, 3: 4} echo t[] Run
Re: Bug with makeNimstrLit on JS backend
JS string is called cstring in Nim [https://nim-lang.org/docs/manual.html#types-cstring-type](https://nim-lang.org/docs/manual.html#types-cstring-type)
Re: Capture Problem
I realised you don't actually need toSeq here import random, sugar, math proc foo[T, U](a: openArray[T], cdf: openArray[U]): auto = let (a, cdf) = (@a, @cdf) (() => random.sample(a, cdf.cumsummed)) echo foo([1,2], [1,2])() Run
Re: Capture Problem
import random, sugar, math from sequtils import toSeq proc test1[I, T, U](a: array[I, T], cdf: array[I, U]): auto = (() => random.sample(a, cdf.cumsummed)) proc test2[T, U](a: openArray[T], cdf: openArray[U]): auto = (() => random.sample(a.toSeq, cdf.toSeq.cumsummed)) assert compiles test1([1,2], [1,2]) assert compiles test2([1,2], [1,2]) Run .
Re: Why doesn't jester compile to js?
This is unsupported but, if you were going to wrap Express, you might as well wrap another library to replace Jester. But at that point you're probably better off just using JS?
Re: debug-only echo
[dump](https://nim-lang.org/docs/sugar.html#dump.m%2Ctyped) does the same. Also, there's [astToStr](https://nim-lang.org/docs/system.html#astToStr%2CT).
Re: debug-only echo
when not released: debugEcho "some info" Run .
Re: json confusion
You convert an object into a JsonNode with [%](https://nim-lang.org/docs/json.html#%25%2CT)
Re: Access to Iterators of Sequences
Also an option: [https://nim-lang.org/docs/manual.html#macros-for-loop-macro](https://nim-lang.org/docs/manual.html#macros-for-loop-macro)
Re: Why does the this code work?
Varargs has to be the last parameter, openarray(s) can be anywhere.
Re: Why does the this code work?
Why shouldn't it 樂? The implicit conversion to a varargs/openarray (same thing) is cheap.
Re: Is it possible to see sql executed?
You should be able to just echo string(theQuery) Run
Re: Equivalent of VBA With structure
template my: untyped = s.processor
Re: What are move semantics ,rvalue and lvalue ?
> You mean this function is behaving like a variable or a storage container ? It's _result_ (a pointer to an int) is a storage.
Re: conditional compilation from macro-generated code?
I guess for simplicity of implementation and to limit the differences between nim and nimscript (which is what I think macros use)? The code is generated _by_ a macro, not _in_ a macro, so it's matter here anyway.
Re: conditional compilation from macro-generated code?
You need to use 'when' instead of 'if'.
Re: Karax seems to only update button when text changes. Even other onclick should be bound.
Works for me without changing anything on stable and devel. Maybe try reinstalling karax?
Re: future of htmlgen
> Also, should I categorize that source code filters are the "officially > recommended way" to generate html? Or is that extrapolating too much? I doubt they are recommended for anything when they're not even mentioned in the manual. You can use any of the html-generating nimble libraries or create your own html builder using macros.
Re: How to chain prodecure calls that mutate a reference object ?
get_child returns a Child, not a var Child
Re: Newbie question: Why am I getting the too many variables error on my loop index variable?
If you don't want to allocate a seq (like you do when you invoke pairs), you can use enumerate from [https://nim-lang.org/docs/manual.html#macros-for-loop-macro](https://nim-lang.org/docs/manual.html#macros-for-loop-macro)
Re: anonymous procedures and closures
proc iota(): proc(): int = var i = 0 proc fn (): int = i = i + 1 return i result = fn var j = iota() echo j() , j() var k = iota() echo k(), k(), k() echo j() Run i is local to each closure.
Is this expected behaviour?
var x {.compileTime.} = false static: x = true echo x Run > false
Re: Check if a procedure exists for a given type at compile time
var car: Car when compiles (drive car): .. else: .. Run When is a compile-time version of if
Re: Is there a default initializer that can be overloaded?
You can use a template instead of a proc: template usesFoo = foo() block: proc foo = echo "a" usesFoo block: proc foo = echo "b" usesFoo # prints: # a # b Run
Re: How to manage local dependencies with nimble?
> how to specify specific version of package, e.g. opengl 1.2.3 in nimble file? Nimble's github page doesn't show this, but according to [the source](https://github.com/nim-lang/nimble/blob/master/src/nimblepkg/version.nim): requires "opengl 1.2.3" Run or requires "opengl == 1.2.3" Run
Re: OK, a collection of complains
1. I think Araq meant that you can create a chain macro yourself 2. If you really care, you can create your own API on top of sequtils
Re: Using the file system and AST in conjunction
I think the main reason ormin generates a separate file is to serve as a cache, instead of parsing the DB schema over and over again and slowing down the compiler (and nimcheck, presumably).
Re: Need help of a pair programmer
block: echo "1 (no crash)" var m: CoverMatrix for it in m: discard block: echo "2 (crash)" var m: ref CoverMatrix new m for it in m[]: discard Run Funny. If you replace all the procs with this code and comment out the second block it works fine, but if you don't, it doesn't even print anything, so the runtime crash occurs before the code is executed.
Re: Translating C# code to Nim code. Help needed
The easiest way I know of is just using an extremely short proc name, maybe even a single letter long.
`typedesc` returned from a `typedesc[proc]`
Is there a way to get the return type of a proc type as a typedesc? ex. type Proc = proc: int type ReturnType = Proc.??? Run
Re: Return subobject from proc
Call A with B as a parameter A(B()) A B() B().A Run
Re: Macros help
> But could you please explain or provide a link where I can learn more about > varargs ? It's in the manual: [https://nim-lang.org/docs/manual.html#types-varargs](https://nim-lang.org/docs/manual.html#types-varargs)
Re: Macros help
template regGroup(name; types: varargs[int, getId]) = let name = newGroup types Run
Re: Distinct for indices, is it good library Api?
Why not overload procs like fromEdges to accept pairs of integers?
How to check if a proc has no return type?
This approach doesn't compile: echo echo(":)") is void Run
{.global.} in global scope
What does the global pragma do the way it is used [here](https://github.com/Araq/ormin/blob/master/examples/forum/forum.nim)? import "../ormin/ormin", json importModel(DbBackend.sqlite, "forum_model") var db {.global.} = open("stuff", "", "", "") ... Run
Re: Translating C# code to Nim code. Help needed
`# placeholder just to make the compiler shut up type Storage[T] = seq[T] proc newStorage[T](size: int): seq[T] = newSeq[T] size proc components[T](x: var seq[T]): var seq[T] = x type Entity = object id: int ComponentMotion = object x, y: float template setupComponent(t: typedesc) = var x {.used.} = newStorage[t] 100 proc getStorage(_: typedesc[t]): var Storage[t] = x proc getComponent(self: Entity, _: typedesc[t]): ptr t = addr x.components[self.id] proc setComponent[T](self: Entity, comp: T) = self.getComponent(T)[] = comp setupComponent ComponentMotion var en = Entity(id: 0) en.setComponent ComponentMotion() en.getComponent(ComponentMotion).x = 10 echo en.getComponent(ComponentMotion).x echo getStorage(ComponentMotion)[0].x ` Run
Re: creating a enum type after calling a macro on various modules
You'd have to gather group names in a compileTime variable.
Re: binarySearch (from algorithm) not always working
https://nim-lang.org/docs/system.html#find%2CT%2CS
Re: Translating C# code to Nim code. Help needed
You can ctrl+F it in the manual, but the difference between inheritable and RootObj is not that important. This is just a limitation of the parser, you must not use dot call syntax: var x: StorageBase discard Storage[int] x Run But if you just want cute syntax, you may as well use some metaprogramming not to deal with inheritance when it's not neccesary: template container(T: typedesc, size=100) = var `name` = newSeq[`T`] size template `@`(typ: typedesc[T]): untyped {.used.} = `name` container int container float @int[0] = 123 echo @int[0] # 123 echo @int[1] # 0 echo @int.len == @float.len # true Run
Re: Translating C# code to Nim code. Help needed
type Component {.inheritable.} = ref object A = ref object of Component x: int B = ref object of Component y: int var components: seq[Component] components.add A(x: 1) components.add B(y: 2) echo components[0] of A # true echo components[1] of B # true echo components[0].A.x# 1 echo components[1].B.y# 2 Run .
Re: How to direct access values of JSON JObjects when they are within a main JsonNode JObject?
import json let j = parseJson """{ "x": { "y": { "z": 123 } } }""" echo j["x"]["y"]["z"].getInt Run
Re: Force types from specific imported modules
https://play.nim-lang.org/#ix=24cs
Re: Recommended GUI library?
Is there a good reason people often don't even mention QML in these threads?
Re: Karax Components
I didn't get to use VComponents, so I don't really know how it works. All I could infer was from [https://github.com/pragmagic/karax/blob/master/examples/carousel/carousel.nim](https://github.com/pragmagic/karax/blob/master/examples/carousel/carousel.nim)
Re: Karax Components
If you want to use VComponents, you'll need to use a commit before this bug was introduced (until it gets fixed): [https://github.com/pragmagic/karax/issues/112](https://github.com/pragmagic/karax/issues/112) If you're not going to use VComponents, I'm pretty sure the only alternative is global variables.
Re: It seems a bit confusing to express the current class object with the first argument.
import macros macro function(x) = var params: seq[NimNode] expectKind x, nnkCommand expectKind x[0], nnkPar expectKind x[0][0], nnkExprColonExpr params.add newIdentDefs(x[0][0][0], x[0][0][1]) expectKind x[1], nnkCommand expectKind x[1][0], nnkIdent let name = x[1][0] expectKind x[1][1], nnkCommand expectKind x[1][1][0], nnkPar for it in x[1][1][0]: case it.kind of nnkExprColonExpr: params.add newIdentDefs(it[0], it[1]) of nnkExprEqExpr: params.add newIdentDefs(it[0], newEmptyNode(), it[1]) else: raiseAssert ":-(" let x = x[1][1][1] expectKind x, nnkCall var pragmas, body = newEmptyNode() case x[0].kind of nnkPragmaExpr: expectKind x[0][0], nnkIdent expectKind x[0][1], nnkPragma expectKind x[1], nnkStmtList params.insert x[0][0], 0 # return type pragmas = x[0][1] body = x[1] of nnkIdent: params.insert x[0], 0 # return type body = x[1] of nnkStmtList: params.insert newEmptyNode(), 0 # return type body = x[0] else: raiseAssert ":-(" newProc(name, params, body, nnkProcDef, pragmas) var x = 0 function (a: int) foo (b: int, c = 42) int {.exportc, cdecl, dynlib.} do: inc x a + b + c assert 2.foo(3) == 47 assert x == 1 Run Most of the code is just checking the arguments anyway.
Re: Java / D / C# Interfaces
I think this is what you're looking for: type My_Interface = object foo: proc() proc to_my_interface(x: int): auto = My_Interface(foo: proc = echo "int: " & $x) proc to_my_interface(x: float): auto = My_Interface(foo: proc = echo "float: " & $x) var coll: seq[My_Interface] = @[to_my_interface(2), to_my_interface(3.0)] for it in coll: it.foo() Run The output is `int: 2` `float: 3.0`
Re: recvmsg on AsyncSocket
You can receive a line (the message would have to end with a newline): [https://nim-lang.org/docs/asyncnet.html#recvLine%2CAsyncSocket](https://nim-lang.org/docs/asyncnet.html#recvLine%2CAsyncSocket)
Re: nim in nim
Araq?
Re: Nim Coding Examples and Exercises for beginners?
Maybe my [chess game](https://github.com/dawkot/netchess) will be helpful. The rules are in src/game.nim and should on all targets.
Re: Using `{.gcsafe.}` on a global string
Well, the entire point of the pragma is, according to the manual: `To override the compiler's gcsafety analysis a {.gcsafe.} pragma block can be used`
Re: Trying to make dict in dict (table in table)
You're supposed to either have Server be a ref object for it to have reference semantics or use it as a [var parameter](https://nim-lang.org/docs/manual.html#procedures-var-parameters)
Re: Persistent data structures
> Why do you think its easy? Well, it should be just a matter of translating whatever code is out there to nim.
Is StringStream ever going to be included on JS backend?
Useful or not on it's own, the parsers and the marshal module in stdlib depend on it.
Re: How to return a seq[string] from proc
I think you didn't notice that seq is passed by value and not by reference.
Re: What's the most idiomatic way to call ``execCmdEx`` in parallel?
It would be something like this: import std / [osproc, streams, asyncdispatch] proc asyncProcess(cmd: string, args: seq[string]): Future[(int, string)] {.async.} = var p = startProcess(cmd, args=args) while p.running: await sleepAsync 5 return (p.peekExitCode, readAll p.outputStream) let a = asyncProcess("nim", @["-v"]) let b = asyncProcess("nim", @["-v"]) for (code, output) in waitFor all(a, b): echo ">> ", code, "\n\n", output Run
Re: What's the most idiomatic way to call ``execCmdEx`` in parallel?
Sure, but he can use asyncdispatch which doesn't involve threads.
No exception on index/key out of range on JS backend
Is this expected behaviour? It makes error messages much less helpful.
Hashing references by address
Is it safe to hash ref values by the value addr proc returns? If so, does it apply to all the backends?
Can't return closure procedures from `closureScope` blocks
proc foo: seq[proc: int {.closure.}] = for i in 0..1: closureScope: result.add proc: int = 1 for f in foo(): echo f() Run `(14, 7) Error: 'result' is of type which cannot be captured as it would violate memory safety, declared here: abc.nim(11, 1)` How am I supposed to append it to the result variable, then?
Re: Tuple field names in a macro
Nevermind, getTypeInst does it. But it's a little unexpected because it seems like if getType does so for objects, it should also work for tuples.
Re: Wrapping an object without generics
You can represent all the expected types with an enum that will determine which field of your object is the valid one. To reduce object's size (probably doesn't matter), there are object variants [https://nim-lang.org/docs/manual.html#types-object-variants](https://nim-lang.org/docs/manual.html#types-object-variants) For completely dynamic types there is [https://nimble.directory/pkg/variant](https://nimble.directory/pkg/variant)
Tuple field names in a macro
What does getType not return field names for named tuples? It does so for objects.
Re: Unexpected async behaviour?
Thanks for help.
Re: Unexpected async behaviour?
Right, this works as expected: import asyncdispatch, asyncnet let s = newAsyncSocket() s.setSockOpt(OptReuseAddr, true) s.bindAddr Port 12345 s.listen let c1, c2 = newAsyncSocket() for c in [c1, c2]: asyncCheck c.connect("localhost", Port 12345) proc serve(c: AsyncSocket) {.async.} = while true: echo repr c.getFd await sleepAsync 2000 proc serveNewConnections {.async.} = while true: let c = await s.accept asyncCheck serve c asyncCheck serveNewConnections() runForever() Run This does not: import asyncdispatch, asyncnet let s = newAsyncSocket() s.setSockOpt(OptReuseAddr, true) s.bindAddr Port 12345 s.listen let c1, c2 = newAsyncSocket() for c in [c1, c2]: asyncCheck c.connect("localhost", Port 12345) proc serveNewConnections {.async.} = while true: let c = await s.accept proc serve {.async.} = while true: echo repr c.getFd await sleepAsync 2000 asyncCheck serve() asyncCheck serveNewConnections() runForever() Run It's as if the first closure's context is being replaced by the context of the second closure.
Unexpected async behaviour?
import asyncdispatch, asyncnet template asyncDo(x) = asyncCheck (proc {.async.} = x)() let s = newAsyncSocket() s.setSockOpt(OptReuseAddr, true) s.bindAddr Port 12345 s.listen let c1, c2 = newAsyncSocket() for c in [c1, c2]: asyncCheck c.connect("localhost", Port 12345) asyncDo: while true: let c = await s.accept asyncDo: while true: echo repr c.getFd await sleepAsync 2000 runForever() Run Ouput: 21 22 22 22 22 22 22 22 (...) Run The first two lines are as I would expect, but what's up with the rest? Why is FD 21 suddenly gone?
Re: Bizzare macro error
Thanks. I assumed that if the error is raised on a loop, there is something wrong with the loop itself.
Re: Bizzare macro error
Here it is [https://pastebin.com/Vj0EB8Yr](https://pastebin.com/Vj0EB8Yr)
Bizzare macro error
for i, node in toSeq(prc.getType)[2..^1]: #error let isRef = node.kind == nnkBracketExpr and $node[0] == "ref" let isServer = node.kind == nnkBracketExpr and $node[0] == "ref" and ( serverKind == ServerKind.Tcp and $node[1] == "TcpServer:ObjectType" or serverKind == ServerKind.Udp and $node[1] == "UdpServer:ObjectType" ) Full error message: _type mismatch: got (char)_ _but expected one of:_ _proc myProc(a: string; b: TcpServer)_ Removing either isRef or isServer gets a rid of the error. Writing it in a different way to get the same result returns the same error. Any idea how to make it work? I don't think the rest of code matters in this case.
Re: What does "invalid type" error mean in this context?
Forgot to add that the type actually gets generated, it's just that I can't use it.
What does "invalid type" error mean in this context?
variant Shape: Cube(a, b: int, c: int) None Error var x: Shape #error Here's the entire abomination of a macro: [https://pastebin.com/m2pLkCNs](https://pastebin.com/m2pLkCNs)
Re: Anonymous iterators
Yup, that's what I was looking for.
Anonymous iterators
Are anonymous iterators implemented, and if not, will they be?
Re: Question about sockets
Oh, well, too bad this proc doesn't support buffered sockets.
Re: Question about sockets
Thanks, weird that I missed recvFrom when looking through the library.