Hi all, I am trying to learn templates in nim. This code is from nim tutorial.
template `!=` (a, b: untyped): untyped =
# this definition exists in the System module
not (a == b)
assert(5 != 6) # the compiler rewrites that to: assert(not (5 == 6))
Here i have an example to understand how templates works. I can understand that the "!=" works an operator here. But i am confused with this example.
const
debug = true
template log(msg: string) =
if debug: stdout.writeLine(msg)
var
x = 4
log("x has the value: " & $x)
Here, template named "log" behaves like a proc. So how compiler understands this behavioral change ? And see this example from winim's github page.
template `<<`(p: ptr char | ptr byte | cstring; s: mstring | string)
They are saying that this will "Fill buffer by string." But how to use in our code. All i know about creating stringBuffer is like this;
char myStr[5] ;
# this C code can convert into nim like this;
var myStr = newStringOfCap(5)
OK, so, i have created a string buffer. Now, how can i use the above said template in this string buffer ? Like this ?
myStr << "test"
Is this the proper way to use of this template ?and yes, the backticks make them operators
I think that wording is very wrong and lead to confusion for beginners.
When I remember correctly, operator names can not be arbitrary letters, but only a combination of the operator chars like +-!< and many more. So we can not do
proc `mySpecialPlus`(a, b: int): int =
mySpecialPlus() is not an operator as its name is built with ordinary letters, and the surrounding backticks will not make it one.
For a routine f (where f is an ordinary identifier consisting of letters) a call can be written as
f a
f(a)
a.f
For a routine @ (where @ is an operator symbol consisting of special characters) a call can be writen as:
@a # unary operator call; only receives one argument
a @ b # binary operator call; receives two arguments
`@`(a, b) # backticks to use the "ordinary" routine syntax
a.`@`(b) # method invokation syntax, allowed for consistency
And that's it, the syntax is independent of the concrete routine kind, whether it's a proc, a template, an iterator does not matter for the syntax.
You are mixing a lot of Nim stuff on the same question, and get confused.
Function calls:
echo "a"
echo("b")
echo"c"
"d".echo
"e".echo()
The minimal possible example of Templates:
template mini(body: untyped) =
body
mini():
echo "foo"
template times(integer: int, code_to_repeat: untyped): untyped =
for i in 1..integer:
code_to_repeat
10.times:
echo "This repeats 10 times"