ThakeeNathees / pocketlang

A lightweight, fast embeddable scripting language.
https://thakeenathees.github.io/pocketlang/
MIT License
1.52k stars 80 forks source link

[Enhancement] add compile and eval for metaprogramming #285

Open khchen opened 2 years ago

khchen commented 2 years ago

compile can compile the source code into a closure at runtime time. Example:

message = "Metaprogramming"
value = 12345

code = "
  def test
    return $value
  end
  print('$message')
  return test()
"
func = compile(code)
print(func())

Output:

Metaprogramming
12345

eval can evaluate an expression and returns the result. Example:

message = eval("'Meta' + 'programming'")
value = eval("123450 / 10")
func = eval("
  fn
    print(message)
    return eval('value')
  end
")
eval("print")(eval("func()"))

Output:

Metaprogramming
12345