Skip to content

Miscellaneous module

Wang Renxin edited this page Sep 22, 2015 · 11 revisions

This is a demonstration about how to implement miscellaneous module with MY-BASIC.

Add implementation functions. An IIF statement which evaluates the first argument and returns the second argument if it results true, otherwise returns the third one. This is similar to ?: ternary operator in some other languages, see below:

static int _iif(struct mb_interpreter_t* s, void** l) {
	int result = MB_FUNC_OK;
	mb_value_t arg;
	mb_value_t st;
	mb_value_t sf;
	bool_t cond = false;

	mb_assert(s && l);

	mb_check(mb_attempt_open_bracket(s, l));

	mb_check(mb_pop_value(s, l, &arg));
	mb_check(mb_pop_value(s, l, &st));
	mb_check(mb_pop_value(s, l, &sf));

	mb_check(mb_attempt_close_bracket(s, l));

	switch(arg.type) {
	case MB_DT_NIL:
		break;
	case MB_DT_INT:
		cond = !!arg.value.integer;
		break;
	default:
		cond = true;
		break;
	}

	if(cond) {
		mb_check(mb_push_value(s, l, st));
	} else {
		mb_check(mb_push_value(s, l, sf));
	}

	return result;
}

A system statement which invokes a system command as below:

static int _system(struct mb_interpreter_t* s, void** l) {
	int result = MB_FUNC_OK;
	char* arg = 0;

	mb_assert(s && l);

	mb_check(mb_attempt_open_bracket(s, l));

	mb_check(mb_pop_string(s, l, &arg));

	mb_check(mb_attempt_close_bracket(s, l));

	if(arg)
		system(arg);

	return result;
}

Register them:

mb_register_func(bas, "IIF", _iif);
mb_register_func(bas, "SYSTEM", _system);

See the script usage below.

IIF statement:

print iif(true, "succeed", "fail");
print iif(false, "fail", "succeed");
print iif(nil, "fail", "succeed");
print iif(0, "fail", "succeed");
print iif(1, "succeed", "fail");
print iif(0.1, "succeed", "fail");
print iif("", "succeed", "fail");

SYSTEM statement:

system("ls")
Clone this wiki locally