Skip to content

Callback

Wang Renxin edited this page Dec 16, 2015 · 18 revisions

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.

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).

Clone this wiki locally