-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetaprogramming.ktg
More file actions
54 lines (47 loc) · 1.67 KB
/
metaprogramming.ktg
File metadata and controls
54 lines (47 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Kintsugi [target: 'lua]
; Two metaprogramming tools:
; @template - declarative macros, expanded at call sites
; @preprocess - imperative compile-time code generation
; ============================================================
; @template -- code generation without ceremony
; ============================================================
; A @template body uses paren interpolation: parens in the body
; evaluate against the call-site arguments and splice into the
; expansion.
@template unless: [cond body [block!]] [
if not (cond) (body)
]
unless (1 > 10) [print "math works"]
; /only when the body contains set-words or raw names that
; should be preserved literally.
@template/only defn: [name [string!] params [block!] body [block!]] [
(to set-word! name) function (params) (body)
]
defn "square" [n] [n * n]
print square 7 ; 49
; ============================================================
; @preprocess -- compile-time codegen
; ============================================================
; @preprocess evaluates its body at parse time. Inside,
; `@emit [...]` injects code into the output program.
; Generate a family of functions from a data list.
@preprocess [
loop [
for [op] in [double triple quadruple] do [
n: match op [
['double] [2]
['triple] [3]
['quadruple] [4]
]
@emit [
(to set-word! op) function [x] [x * (n)]
]
]
]
]
print double 5 ; 10
print triple 5 ; 15
print quadruple 5 ; 20
; @preprocess with emit injects values at parse time.
@preprocess [@emit [max-enemies: 16]]
print max-enemies ; 16