tfields.nim 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. discard """
  2. output: '''
  3. n
  4. n
  5. (one: 1, two: 2, three: 3)
  6. 1
  7. 2
  8. 3
  9. (one: 4, two: 5, three: 6)
  10. 4
  11. (one: 7, two: 8, three: 9)
  12. 7
  13. 8
  14. 9
  15. (foo: 38, other: "string here")
  16. 43
  17. 100
  18. 90
  19. '''
  20. """
  21. block tindex:
  22. type
  23. TMyTuple = tuple[a, b: int]
  24. proc indexOf(t: typedesc, name: string): int =
  25. ## takes a tuple and looks for the field by name.
  26. ## returs index of that field.
  27. var
  28. d: t
  29. i = 0
  30. for n, x in fieldPairs(d):
  31. if n == name: return i
  32. i.inc
  33. raise newException(ValueError, "No field " & name & " in type " &
  34. astToStr(t))
  35. doAssert TMyTuple.indexOf("b") == 1
  36. block ttemplate:
  37. # bug #1902
  38. # This works.
  39. for name, value in (n: "v").fieldPairs:
  40. echo name
  41. template wrapper: typed =
  42. for name, value in (n: "v").fieldPairs:
  43. echo name
  44. wrapper()
  45. block tbreak:
  46. # bug #2134
  47. type
  48. TestType = object
  49. one: int
  50. two: int
  51. three: int
  52. var
  53. ab = TestType(one:1, two:2, three:3)
  54. ac = TestType(one:4, two:5, three:6)
  55. ad = TestType(one:7, two:8, three:9)
  56. tstSeq = [ab, ac, ad]
  57. for tstElement in mitems(tstSeq):
  58. echo tstElement
  59. for tstField in fields(tstElement):
  60. #for tstField in [1,2,4,6]:
  61. echo tstField
  62. if tstField == 4:
  63. break
  64. block timplicit_with_partial:
  65. type
  66. Base = ref object of RootObj
  67. Foo {.partial.} = ref object of Base
  68. proc my(f: Foo) =
  69. #var f.next = f
  70. let f.foo = 38
  71. let f.other = "string here"
  72. echo f[]
  73. echo f.foo + 5
  74. var g: Foo
  75. new(g)
  76. my(g)
  77. type
  78. FooTask {.partial.} = ref object of RootObj
  79. proc foo(t: FooTask) {.liftLocals: t.} =
  80. var x = 90
  81. if true:
  82. var x = 10
  83. while x < 100:
  84. inc x
  85. echo x
  86. echo x
  87. foo(FooTask())