Skip to content

Callback

Wang Renxin edited this page Mar 3, 2016 · 18 revisions

Call from script to script

The CALL statement is used to get a routine value itself as:

def fun(msg)
	print msg;
enddef

routine = call(fun) ' get a routine value
routine("hello")    ' invoke a routine value

Be aware it requires a pair of brackets comes along with a CALL statement to get a routine value, otherwise it means call the routine immediately.

This mechanism is useful when you are tending to store a sub routine value for later invoking.

Call from C to script

Besides, it's able to call a script routine from C side as well, for instance, assuming we got a sub routine defined in script:

def fun(num)
	print num;
enddef

native ' this is a registered native function

Now we are able to callback fun at C side as follow:

static int native(struct mb_interpreter_t* s, void** l) {
	int result = MB_FUNC_OK;

	mb_assert(s && l);

	mb_check(mb_attempt_func_begin(s, l));
	mb_check(mb_attempt_func_end(s, l));

	{
		mb_value_t routine;
		mb_value_t args[1];

		mb_get_routine(s, l, "FUN", &routine);   // Get the "FUN" routine

		args[0].type = MB_DT_INT;
		args[0].value.integer = 123;
		mb_eval_routine(s, l, routine, args, 1); // Evaluate the "FUN" routine with arguments
	}

	return result;
}

Not it needs uppercase identifier to lookup a routine (and other symbols in MY-BASIC).

Call from script to C

The most attractive part of callback in MY-BASIC is that there is no difference between a routine defined in script and in C. Assuming we have two C functions as follow:

static int foo(struct mb_interpreter_t* s, void** l, mb_value_t* va, unsigned ca, void* r, mb_has_routine_arg_func_t has, mb_pop_routine_arg_func_t pop) {
	int result = MB_FUNC_OK;
	mb_value_t val;
	unsigned ia = 0;

	mb_assert(s && l);

	mb_check(mb_attempt_open_bracket(s, l));

	mb_make_nil(val);
	if(has(s, l, va, ca, &ia, r)) {
		mb_check(pop(s, l, va, ca, &ia, r, &val));
	}

	mb_check(mb_attempt_close_bracket(s, l));

	printf("%d\n", val.value.integer);

	return result;
}

static int test(struct mb_interpreter_t* s, void** l) {
	int result = MB_FUNC_OK;

	mb_assert(s && l);

	mb_check(mb_attempt_func_begin(s, l));
	mb_check(mb_attempt_func_end(s, l));

	mb_set_routine(s, l, "FOO", foo, true); // Define a routine named "FOO"

	return result;
}

Don't forget to register test:

mb_reg_fun(bas, test);

Now we can call the C function foo as a routine:

test     ' call "test"

foo(123) ' "foo" is defined as a routine when calling "test"
Clone this wiki locally