ttempl3.nim 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. template withOpenFile(f: untyped, filename: string, mode: FileMode,
  2. actions: untyped): untyped =
  3. block:
  4. # test that 'f' is implicitly 'injecting':
  5. var f: File
  6. if open(f, filename, mode):
  7. try:
  8. actions
  9. finally:
  10. close(f)
  11. else:
  12. quit("cannot open for writing: " & filename)
  13. withOpenFile(txt, "ttempl3.txt", fmWrite):
  14. writeLine(txt, "line 1")
  15. txt.writeLine("line 2")
  16. var
  17. myVar: array[0..1, int]
  18. # Test zero argument template:
  19. template ha: untyped = myVar[0]
  20. ha = 1
  21. echo(ha)
  22. # Test identifier generation:
  23. template prefix(name): untyped = `"hu" name`
  24. var `hu "XYZ"` = "yay"
  25. echo prefix(XYZ)
  26. template typedef(name: untyped, typ: typeDesc) {.immediate, dirty.} =
  27. type
  28. `T name`* = typ
  29. `P name`* = ref `T name`
  30. typedef(myint, int)
  31. var x: PMyInt
  32. # Test UFCS
  33. type
  34. Foo = object
  35. arg: int
  36. proc initFoo(arg: int): Foo =
  37. result.arg = arg
  38. template create(typ: typeDesc, arg: untyped): untyped = `init typ`(arg)
  39. var ff = Foo.create(12)
  40. echo ff.arg