Natural Tiny Basic (NT-Basic)

使い方


様々な環境で動作

Natural Tiny Basic (NT-Basic) は、様々な環境で動作します。 以下に二つの異なる環境で動作させる場合の例について示します。

コンピュータ環境で使用する例

コンピュータ環境であればlibcを使ってプログラムを読み込むようなアプリケーションを簡単に構成できるでしょう。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "ntbasic.h"
#include "progedit.h"

static int load_program(progedit_t *p, const char *filename)
{
  char buf[BUFSIZ];
  int line = 0;
  FILE *fp = fopen(filename, "rb");
  if (fp == NULL) {
    return -1;
  }

  while (fgets(buf, sizeof(buf), fp) != NULL) {
    line++;
    if (progedit_insert(p, buf) != 0) {
      printf("Insert failed.\nline=%d:%s\n", line, buf);
    }
  }

  fclose(fp);
  return line;
}

static int print_program(progedit_t *p)
{
  char buf[BUFSIZ];
  int line = 0;
  while (progedit_fetch(p, line, buf, sizeof(buf)) == 0) {
    line++;
    printf("  %d: [%s]\n", line, buf);
  }
  return line;
}

int main(int argc, char *argv[])
{
  ntbasic_t ntbasic;
  ntbasic_error_t error;
  progedit_t prog;
  int line_files, line_progs;
  char errmsg[BUFSIZ];
  void *extobj = "This is a user external object for the test.";

  /*
   * Check the arguments.
   */
  if (argc != 2) {
    printf("usage: ntbasic \n");
    return 1;
  }

  /*
   * Load program from a file system.
   */
  progedit_init(&prog);
  line_files = load_program(&prog, argv[1]);
  if (line_files < 0) {
    printf("program read failed.\n");
    return 2;
  }

  printf("[Program list]\n");
  line_progs = print_program(&prog);
  printf("\n");
  printf("[Program information]\n");
  printf("  %d lines readed.\n", line_files);
  printf("  %d lines stored.\n", line_progs);
  printf("  %d bytes.\n", (int)strlen(PROGEDIT_PROGRAM(&prog)));
  printf("\n");

  /*
   * Setup and execute.
   */
  error = ntbasic_setup(&ntbasic, PROGEDIT_PROGRAM(&prog), extobj);
  while (error == NoError) {
    error = ntbasic_execute(&ntbasic);
  }

  /*
   * Check the termination code.
   */
  if (error != EndOfTheProgram) {
    ntbasic_get_error_message(&ntbasic, error, errmsg, sizeof(errmsg));
    printf("Error: %s\n", errmsg);
  }

  return (error == EndOfTheProgram) ? 0 : error;
}

組み込みシステム環境で使用する例

#include "ntbasic.h"

int main(void)
{
  ntbasic_t ntbasic;
  ntbasic_error_t error;
  char *program =
    "100 PRINT \"This is a test\"\n" \
    "110 END\n";
  void *extobj = (void *)0;

  error = ntbasic_setup(&ntbasic, program, extobj);
  while (error == NoError) {
    error = ntbasic_execute(&ntbasic);
  }

  while (1) {
  }
}