No `[]` iterators for collections?

2020-06-10 Thread dawkot
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

2020-06-06 Thread dawkot
No cast needed: 


proc foo(x: var int) = discard

var p: ptr int

foo p[]


Run


Re: closure procs with the javascript backend

2020-05-20 Thread dawkot
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?

2020-05-20 Thread dawkot
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?

2020-05-13 Thread dawkot
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?

2020-05-12 Thread dawkot
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

2020-05-12 Thread dawkot
It's just a funny way of using command invocation syntax, usually used without 
braces: 


if unlikely position < 0:


Run


Re: Reference to sequence

2020-05-10 Thread dawkot



Re: Is there a simple example on how to create a Windows UI

2020-05-04 Thread dawkot
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

2020-05-02 Thread dawkot
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 ...

2020-04-25 Thread dawkot
sugar.collect can be used to convert between different collection types.


Re: Sequential execution on what appears to be async code

2020-04-20 Thread dawkot
Using asyncCheck instead of await in main should work, maybe


Re: Nim programming book for kids

2020-04-12 Thread dawkot
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

2020-04-11 Thread dawkot
You didn't change .to[:T] to .tp[:ref T]


Re: Enum bitmasks (flags)

2020-04-03 Thread dawkot
You can also create a set of all possible values like this: 


{State.low .. State.high}

Run


Re: Updating Element style via Karax (noobish?)

2020-03-19 Thread dawkot
You can also setAttr on a style


Re: Type safe opengl

2020-03-15 Thread dawkot
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)

2020-03-11 Thread dawkot
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

2020-03-08 Thread dawkot
As I said, you must use the devel version. You can install it with a tool 
called choosenim.


Re: Nested list comprehension

2020-03-07 Thread dawkot
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?

2020-03-06 Thread dawkot
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

2020-03-06 Thread dawkot
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

2020-03-05 Thread dawkot

proc myProc = ##[my comment]## discard

myProc()


Run

.


Why does `setCommand` exist?

2020-03-05 Thread dawkot
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?

2020-03-02 Thread dawkot
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

2020-02-26 Thread dawkot
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

2020-02-24 Thread dawkot
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

2020-02-24 Thread dawkot

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?

2020-02-22 Thread dawkot
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

2020-02-21 Thread dawkot
[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

2020-02-21 Thread dawkot

when not released: debugEcho "some info"


Run

.


Re: json confusion

2020-02-18 Thread dawkot
You convert an object into a JsonNode with 
[%](https://nim-lang.org/docs/json.html#%25%2CT)


Re: Access to Iterators of Sequences

2020-02-16 Thread dawkot
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?

2020-02-16 Thread dawkot
Varargs has to be the last parameter, openarray(s) can be anywhere.


Re: Why does the this code work?

2020-02-15 Thread dawkot
Why shouldn't it 樂? The implicit conversion to a varargs/openarray (same thing) 
is cheap.


Re: Is it possible to see sql executed?

2020-02-15 Thread dawkot
You should be able to just 


echo string(theQuery)


Run


Re: Equivalent of VBA With structure

2020-02-01 Thread dawkot
template my: untyped = s.processor


Re: What are move semantics ,rvalue and lvalue ?

2020-01-29 Thread dawkot
> 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?

2020-01-26 Thread dawkot
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?

2020-01-25 Thread dawkot
You need to use 'when' instead of 'if'.


Re: Karax seems to only update button when text changes. Even other onclick should be bound.

2020-01-25 Thread dawkot
Works for me without changing anything on stable and devel. Maybe try 
reinstalling karax?


Re: future of htmlgen

2020-01-23 Thread dawkot
> 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 ?

2020-01-19 Thread dawkot
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?

2020-01-15 Thread dawkot
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

2020-01-15 Thread dawkot

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?

2020-01-13 Thread dawkot

var x {.compileTime.} = false

static:
  x = true

echo x


Run

> false


Re: Check if a procedure exists for a given type at compile time

2020-01-12 Thread dawkot

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?

2020-01-10 Thread dawkot
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?

2020-01-10 Thread dawkot
> 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

2020-01-07 Thread dawkot
  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

2020-01-07 Thread dawkot
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

2020-01-02 Thread dawkot

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

2019-12-31 Thread dawkot
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]`

2019-12-31 Thread dawkot
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

2019-12-31 Thread dawkot
Call A with B as a parameter 


A(B())
A B()
B().A


Run


Re: Macros help

2019-12-31 Thread dawkot
> 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

2019-12-30 Thread dawkot

template regGroup(name; types: varargs[int, getId]) =
  let name = newGroup types


Run


Re: Distinct for indices, is it good library Api?

2019-12-25 Thread dawkot
Why not overload procs like fromEdges to accept pairs of integers?


How to check if a proc has no return type?

2019-12-25 Thread dawkot
This approach doesn't compile: 


echo echo(":)") is void


Run


{.global.} in global scope

2019-12-25 Thread dawkot
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

2019-12-19 Thread dawkot
`# 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

2019-12-19 Thread dawkot
You'd have to gather group names in a compileTime variable. 


Re: binarySearch (from algorithm) not always working

2019-12-16 Thread dawkot
https://nim-lang.org/docs/system.html#find%2CT%2CS


Re: Translating C# code to Nim code. Help needed

2019-12-16 Thread dawkot
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

2019-12-16 Thread dawkot

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?

2019-12-15 Thread dawkot

import json

let j = parseJson """{ "x": { "y": { "z": 123 } } }"""
echo j["x"]["y"]["z"].getInt


Run


Re: Force types from specific imported modules

2019-12-12 Thread dawkot
https://play.nim-lang.org/#ix=24cs


Re: Recommended GUI library?

2019-12-09 Thread dawkot
Is there a good reason people often don't even mention QML in these threads?


Re: Karax Components

2019-11-19 Thread dawkot
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

2019-11-19 Thread dawkot
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.

2019-11-14 Thread dawkot

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

2019-10-21 Thread dawkot
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

2019-10-17 Thread dawkot
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

2019-10-09 Thread dawkot
Araq?


Re: Nim Coding Examples and Exercises for beginners?

2019-10-08 Thread dawkot
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

2019-10-08 Thread dawkot
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)

2019-10-08 Thread dawkot
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

2019-09-30 Thread dawkot
> 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?

2019-08-24 Thread dawkot
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

2019-07-20 Thread dawkot
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?

2019-07-12 Thread dawkot
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?

2019-07-11 Thread dawkot
Sure, but he can use asyncdispatch which doesn't involve threads.


No exception on index/key out of range on JS backend

2019-07-11 Thread dawkot
Is this expected behaviour? It makes error messages much less helpful.


Hashing references by address

2019-07-08 Thread dawkot
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

2019-03-16 Thread dawkot

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

2019-03-04 Thread dawkot
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

2019-03-04 Thread dawkot
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

2019-03-04 Thread dawkot
What does getType not return field names for named tuples? It does so for 
objects. 


Re: Unexpected async behaviour?

2019-02-13 Thread dawkot
Thanks for help.


Re: Unexpected async behaviour?

2019-02-09 Thread dawkot
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?

2019-02-06 Thread dawkot

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

2018-01-05 Thread dawkot
Thanks. I assumed that if the error is raised on a loop, there is something 
wrong with the loop itself.


Re: Bizzare macro error

2018-01-05 Thread dawkot
Here it is [https://pastebin.com/Vj0EB8Yr](https://pastebin.com/Vj0EB8Yr)


Bizzare macro error

2018-01-05 Thread dawkot

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?

2017-12-28 Thread dawkot
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?

2017-12-28 Thread dawkot

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

2017-12-01 Thread dawkot
Yup, that's what I was looking for.


Anonymous iterators

2017-11-30 Thread dawkot
Are anonymous iterators implemented, and if not, will they be?


Re: Question about sockets

2017-11-24 Thread dawkot
Oh, well, too bad this proc doesn't support buffered sockets.


Re: Question about sockets

2017-11-23 Thread dawkot
Thanks, weird that I missed recvFrom when looking through the library.


  1   2   >