-
Notifications
You must be signed in to change notification settings - Fork 117
Manipulating an array
Wang Renxin edited this page May 31, 2022
·
3 revisions
Array index in MY-BASIC starts from 0, which is a little different from some other BASIC dialects.
MY-BASIC offers several array manipulation functions to create array dynamically, besides defining with a DIM
statement. A BASIC defined array variable is not re-assignable, but a dynamically created one is not limited by it. Simply speaking, array is either "DIM
ed" or dynamically "created".
Use mb_init_array
to initialize an array; mb_get_array_len
to get the rank value of a dimension; mb_get_array_elem
to get the value of an element; mb_set_array_elem
to set the value of an element. For example assume a string SPLIT
interface as follow using all these functions:
static int _split(struct mb_interpreter_t* s, void** l) {
int result = MB_FUNC_OK;
char* arg = 0;
char* ch = 0;
char* part = 0;
int c = 0;
void* arr = 0;
int d[1] = { 0 };
int i = 0;
char** parts = 0;
int count = 0;
mb_value_t val;
mb_assert(s && l);
mb_check(mb_attempt_open_bracket(s, l));
mb_check(mb_pop_string(s, l, &arg));
mb_check(mb_pop_string(s, l, &ch));
mb_check(mb_attempt_close_bracket(s, l));
arg = strdup(arg);
part = strtok(arg, ch);
while(part) {
if(++c >= count) {
parts = (char**)realloc(parts, c * sizeof(char*));
count = c;
}
parts[c - 1] = part;
part = strtok(0, ch);
}
d[0] = c;
mb_init_array(s, l, MB_DT_STRING, d, 1, &arr);
for(i = 0; i < count; i++) {
val.type = MB_DT_STRING;
val.value.string = parts[i];
d[0] = i;
mb_set_array_elem(s, l, arr, d, 1, val);
}
val.type = MB_DT_ARRAY;
val.value.array = arr;
mb_check(mb_push_value(s, l, val));
free(parts);
free(arg);
return result;
}
Then it's possible to use it as:
s$ = "123,456,789"
a$ = split(s$, ",")
print a$(0), a$(1), a$(2)
- Principles
- Coding
- Data types
- Standalone shell
- Integration
- Customization
- More scripting API
- FAQ