Hi, Ondřej. Thanks for the speedy reply. I think I am still missing
something, however. Here's the sample code I'm playing with:
==
#include <v8.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace v8;
#define JS_SET "var doggie = \"laika\";"
#define WRAP_PREFIX "(function() {"
#define WRAP_SUFFIX "})"
Handle<Function> wrapped_function(const char* code) {
HandleScope handle_scope;
// Wrapped arg to constrain scope
char* wrapped_code = (char *) calloc(sizeof(WRAP_PREFIX) + strlen
(code) + sizeof(WRAP_SUFFIX), sizeof(char));
sprintf(wrapped_code, "%s%s%s", WRAP_PREFIX, code, WRAP_SUFFIX);
Handle<Script> wrapped_script = Script::New(String::New
(wrapped_code));
free(wrapped_code);
Handle<Value> wrapped_fun_result = wrapped_script->Run();
Handle<Function> wrapped_fun = Handle<Function>(Function::Cast
(*wrapped_fun_result));
return handle_scope.Close(wrapped_fun);
}
void print_value(const char* label, Handle<Object> scope, const char*
name) {
HandleScope handle_scope;
Handle<Value> value = scope->Get(String::New(name));
String::AsciiValue av(value);
printf("%s in %s = %s\n", name, label, *av);
}
int main(int argc, char** argv) {
HandleScope handle_scope;
Persistent<Context> context = Context::New();
Context::Scope context_scope(context);
// Wrap functions to contain scope
Handle<Function> fun_set = wrapped_function(JS_SET);
// Assign the value in the other scope
Handle<Object> some_other_scope = Object::New();
fun_set->Call(some_other_scope, 0, NULL);
// What is "doggie" in the other scope?
print_value("other scope", some_other_scope, "doggie");
// What is "doggie" in the global scope?
print_value("global", context->Global(), "doggie");
}
==
which outputs:
==
doggie in other scope = undefined
doggie in global = undefined
==
Do you have any insights into what I might be doing wrong?
Thanks,
David
On Nov 20, 2:53 pm, Ondřej Žára <[email protected]> wrote:
> Hi David,
>
> I believe that "wrapping" is actually the right way to go.
>
> Prepend your string with "function() {" and append "}"; compile, run and
> convert the result to function. v8::Handle<v8::Function> has then the Call()
> method, in which the first argument is your scope object....
>
> Ondrej
--~--~---------~--~----~------------~-------~--~----~
v8-users mailing list
[email protected]
http://groups.google.com/group/v8-users
-~----------~----~----~----~------~----~------~--~---