Contexts

sebastian edited this page Nov 28, 2012 · 2 revisions
Clone this wiki locally

erlv8 allows you to create multiple contexts. A context is more or less a scope of Variable visibility, assignments and changes that happen within one scope don't change any other scope. The usual scope is the Global scope which more or less reflects the default state of the VM.

Let's first set up a erlv8 VM:

application:start(erlv8),
{ok, VM} = erlv8_vm:start().

The global state can be accessed via the following code:

Global = erlv8_vm:global(VM).

You know about the global context already from Using erlv8 so we dive right into how to set up additional contexts. First of all we have to create the context and cause of fun we create two:

Context1 = erlv8_context:new(VM),
Context2 = erlv8_context:new(VM).

Now we have the context which is pretty nice we can run code in it's scope now:

erlv8_vm:run(VM, Context1, "x = 42").
% => {ok,42}
erlv8_vm:run(VM, Context1, "x").     
% => {ok,42}
erlv8_vm:run(VM, Context2, "x").
% => {throw,{erlv8_object,<<>>,<0.40.0>}}

So we have a context and can run code in it but the Context is not enough to set data from Erlang. To do this we have to create a Global for the Context:

Context2Global = erlv8_context:global(Context2),
Context2Global:set_value("funky_erlang_value", 19).

erlv8_vm:run(VM, Context2, "funky_erlang_value").
% => {ok,19}

Now this is how you create a context, get its global and set data on it - have fun!