Posted on 2008-10-20 23:06
sufan 閱讀(2214)
評論(0) 編輯 收藏 引用 所屬分類:
翻譯
打印“print” 函數將會是我們自定義的另外一個函數,它通過使用 printf 函數將所接受的參數全部打印出來。和先前“plus”函數一樣,我們需要在全局模板中注冊這個新函數:
//associates print on script to the Print function
global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print));
實現“print”函數
// The callback that is invoked by v8 whenever the JavaScript 'print'
// function is called. Prints its arguments on stdout separated by
// spaces and ending with a newline.
v8::Handle<v8::Value> Print(const v8::Arguments& args)
{
bool first = true;
for (int i = 0; i < args.Length(); i++)
{
v8::HandleScope handle_scope;
if (first)
{
first = false;
}
else
{
printf(" ");
}
//convert the args[i] type to normal char* string
v8::String::AsciiValue str(args[i]);
printf("%s", *str);
}
printf("\n");
//returning Undefined is the same as returning void...
return v8::Undefined();
}
針對每個參數,需要構造一個 v8::String::AsciiValue 對象為傳遞值創建一個 char * 的表示。有了它,我們就能把其他類型轉換為相應的字符串表示,并將它打印出來!
JavaScript 小樣
現在,我們已經可以在 demo 程序中使用這個 JavaScript 小樣了。
print("begin script");
print(script executed by + user);
if ( user == "John Doe"){
print("\tuser name is invalid. Changing name to Chuck Norris");
user = "Chuck Norris";
}
print("123 plus 27 = " + plus(123,27));
x = plus(3456789,6543211);
print("end script");
這段腳本使用到了“x”變量,“user”變量,以及“plus”函數和“print”函數。