pooooky
pooooky

Reputation: 520

how to pass +, -, etc. to macro in Nim

I want to do something like this macro in Nim

#define BINARY_OP(op) \
    do { \
      double left = getLast(); \
      double right = getLast(); \
      push(right op left); \
    } while (false)

I tried to do this:

macro binaryOp(op: untyped) = 
  let right = getLast()
  let left = getLast()
  vm.push(left op right)

But the compiler throws an error:

Error: attempting to call routine: 'op'

How can I fix this?

Update

I want to use the macro like this:

binaryop(+)

Upvotes: 0

Views: 178

Answers (1)

Jason
Jason

Reputation: 495

Nim macros are not like C macros, they're code generators that take in source code. What you want is a template, which is akin to C macros, but still more sophisticated.

template binaryOp(op: untyped) = 
  let right = 10
  let left = 20
  echo op(left, right)

binaryOp(`+`)

In this case you need to use backticks to lexically strop +, explained here.

Upvotes: 2

Related Questions