-
Notifications
You must be signed in to change notification settings - Fork 118
Redirecting PRINT and INPUT
Wang Renxin edited this page May 31, 2022
·
3 revisions
Include a header file to use variadic:
#include <stdarg.h>
Customizable print handler:
int my_print(struct mb_interpreter_t* s, const char* fmt, ...) {
char buf[64];
char* ptr = buf;
size_t len = sizeof(buf);
int result = 0;
va_list argptr;
mb_unrefvar(s);
va_start(argptr, fmt);
result = vsnprintf(ptr, len, fmt, argptr);
if(result < 0) {
fprintf(stderr, "Encoding error.\n");
} else if(result > (int)len) {
len = result + 1;
ptr = (char*)malloc(result + 1);
result = vsnprintf(ptr, len, fmt, argptr);
}
va_end(argptr);
if(result >= 0)
printf(ptr); /* Change me */
if(ptr != buf)
free(ptr);
return result;
}
Customizable input handler:
int my_input(struct mb_interpreter_t* s, const char* pmt, char* buf, int n) {
int result = 0;
mb_unrefvar(s);
if(fgets(buf, n, stdin) == 0) { /* Change me */
fprintf(stderr, "Error reading.\n");
exit(1);
}
result = (int)strlen(buf);
if(buf[result - 1] == '\n')
buf[result - 1] = '\0';
return result;
}
Register handlers to an interpreter instance:
mb_set_printer(bas, my_print);
mb_set_inputer(bas, my_input);
Now PRINT
and INPUT
in BASIC uses your customized printer and inputer instead of the standard implementations.
- Principles
- Coding
- Data types
- Standalone shell
- Integration
- Customization
- More scripting API
- FAQ