HOWTO use Amber VM

User documentation
03/03/2008

Okay here a small example how to extend your application with Amnber VM.

The application

Say you've dome a horrible complex application that takes input and outputs it again, like giving an echo! So lets start with this highly complex application - hence I'll do some dirty tricks to keep the source short so bare with me here.

begin 
  s=gets.chomp
  puts s
end until s == 'QUIT'

What Amber VM can offer

Now say you got the crazy idea that people should also be able to do calculation with this super cool program. Hence it might seem terrible complicated to add such a functionality to a program that is already as complex as this. But here comes Amber VM to save your butt!

It is pretty easy. Given the math code at this time does not need a environment to be executed in (environment is the storage for variables and such) which makes it a bit easier then.

First you will need to get the latest version of Amber VM which is nearly as complicated as to use it:

gem install Amber VM

Pew. Now you can get a cold coke and whip the sweat from your forehead as you have taken the second most complicated step of the whole thing. But enough rest for now my brave friend! Second is to load the Amber VM engine so you'll have to modify your program a bit this is certainly the most complicated part as it will make your code grow by 33.33%!

require 'rubygems'
require 'amber' # This loads the Amber VM gem
require 'amber/languages/math'  #This loads the math plugin as well as the math function library
begin
  s=gets.chomp
  puts s
end until s == 'QUIT'

Well done! I'm proud of you now the rest should be like a walk in the park to you, nothing really complicated left, you'll just need to add a condition to let the user prefix calculations with a '=' (just to make sure that this program at least makes any kind of sense).

require 'rubygems'
require 'amber' # This loads the Amber VM gem
require 'amber/languages/math'  #This loads the math plugin as well as the math function library
compiler = AmberVM::Languages[:math].new #Lets get us the compiler
begin
  s=gets.chomp
  if m= s.match(/^=(.*)/) #See if it started with a =
    code = m[1] #Extract the code
    puts compiler.compile(code).execute(nil) # We pass nil as we don't need an environment.
  else
    puts s
  end
end until s == 'QUIT'

Done, try it, enjoy it!

Advanced

If you want a bit more you can look at the example calculator program that allowes full usage of the math plugin.

require 'rubygems'
require 'amber' # This loads the Amber VM gem
require 'amber/languages/math'  #This loads the math plugin as well as the math function library
compiler = AmberVM::Languages[:math].new #Lets get us the compiler
env = AmberVM::Interpreter.env
while
    print '> '
    s=gets.chomp
    begin
        puts compiler.compile(s).execute(env) # We pass  the enviroment to make sure privoouse changes are carried over.
    rescue
    end
end until s == 'QUIT'

Files