| 52 | } |
| 53 | |
| 54 | void demonstrateNativeFunctionBinding() |
| 55 | { |
| 56 | std::cout << "\n=== Native Function Binding Demo ===\n"; |
| 57 | |
| 58 | try |
| 59 | { |
| 60 | auto context = choc::javascript::createQuickJSContext(); |
| 61 | |
| 62 | // Register a simple C++ function |
| 63 | context.registerFunction ("add", [](choc::javascript::ArgumentList args) -> choc::value::Value |
| 64 | { |
| 65 | double a = args.get<double>(0, 0.0); |
| 66 | double b = args.get<double>(1, 0.0); |
| 67 | return choc::value::createFloat64 (a + b); |
| 68 | }); |
| 69 | |
| 70 | // Register a more complex function |
| 71 | context.registerFunction ("greet", [](choc::javascript::ArgumentList args) -> choc::value::Value |
| 72 | { |
| 73 | std::string name = args.get<std::string>(0, "World"); |
| 74 | return choc::value::createString ("Hello, " + name + "!"); |
| 75 | }); |
| 76 | |
| 77 | // Register a function that works with arrays |
| 78 | context.registerFunction ("sum", [](choc::javascript::ArgumentList args) -> choc::value::Value |
| 79 | { |
| 80 | if (args.size() == 0) |
| 81 | return choc::value::createFloat64 (0.0); |
| 82 | |
| 83 | auto array = args[0]; |
| 84 | if (! array || ! array->isArray()) |
| 85 | return choc::value::createFloat64 (0.0); |
| 86 | |
| 87 | double sum = 0.0; |
| 88 | for (uint32_t i = 0; i < array->size(); ++i) |
| 89 | { |
| 90 | auto element = (*array)[i]; |
| 91 | if (element.isFloat() || element.isInt()) |
| 92 | sum += element.getWithDefault<double>(0.0); |
| 93 | } |
| 94 | return choc::value::createFloat64 (sum); |
| 95 | }); |
| 96 | |
| 97 | // Register a function that demonstrates error handling |
| 98 | context.registerFunction ("divide", [](choc::javascript::ArgumentList args) -> choc::value::Value |
| 99 | { |
| 100 | double a = args.get<double>(0, 0.0); |
| 101 | double b = args.get<double>(1, 0.0); |
| 102 | if (b == 0.0) |
| 103 | throw choc::javascript::Error ("Division by zero!"); |
| 104 | return choc::value::createFloat64 (a / b); |
| 105 | }); |
| 106 | |
| 107 | // Test the registered functions |
| 108 | std::cout << "Testing native functions from JavaScript:\n"; |
| 109 | |
| 110 | auto result1 = context.evaluateExpression ("add (5, 3)"); |
| 111 | std::cout << "add (5, 3) = " << result1.getWithDefault<double>(0.0) << "\n"; |
no test coverage detected