Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Copyright https://github.com/tilkinsc/ MIT
- // handles line by line interpretation (REPL)
- static int lua_main_postexist(lua_State* L) {
- input = malloc(PRIMARY_REPL_BUFFER_SIZE);
- retfmt = malloc(SECONDARY_REPL_BUFFER_SIZE);
- check_error_OOM(input == NULL || retfmt == NULL, __LINE__);
- int base = 0;
- int status = 0;
- unsigned int ch = 0;
- size_t i = 0;
- while(should_close != 1) {
- retry:
- // 1. reset
- status = 0;
- i = 0;
- // 2. read
- lfprint("%c", '>');
- while((ch = fgetc(stdin)) != '\n') {
- if(ch == -1) // sigint
- // TODO: might crash utf16 multichar string
- return luaL_error(L, "SIGINT");
- if(i == PRIMARY_REPL_BUFFER_SIZE - 1) { // if max input reached
- //lferror(_(REPL_LINE_ERROR));
- lferror("Repl line error");
- fflush(stdin);
- goto retry;
- }
- input[i++] = ch;
- }
- input[i++] = '\0'; // ensure c-string format
- // 2.1 exit if requested
- if(memcmp(input, "return", 6 + 1) == 0) { // return\0 returns if without arguments
- should_close = 1;
- return 0;
- }
- // 3. return %s; test
- snprintf(retfmt, SECONDARY_REPL_BUFFER_SIZE, "return %s;", input);
- status = luaL_loadbuffer(L, retfmt, strlen(retfmt), "REPL return");
- if(status != 0) {
- lua_pop(L, 1); // err msg
- } else {
- // attempt first test, return seems to work
- int top = lua_gettop(L);
- status = lua_pcall(L, 0, LUA_MULTRET, 0);
- if(status == 0) { // on success
- top = lua_gettop(L) - top + 1; // + 1 = ignore pushed function
- if(top > 0) { // more than 0 arguments returned
- lua_getglobal(L, "print");
- if(lua_isnil(L, -1) != 1) { // check even if no_libraries == 1
- lua_insert(L, lua_gettop(L)-top);
- lua_call(L, top, 0);
- } else
- lua_pop(L, 1 + top); // nil, anything returned
- }
- continue;
- } else lua_pop(L, 1); // err msg, also ignore it - no relevance
- }
- // 4. load and execute originally inserted code with error handler
- lua_pushcclosure(L, lua_print_error, 0);
- base = lua_gettop(L);
- if((status = luaL_loadbuffer(L, input, strlen(input), "REPL")) != 0) {
- print_error(SYNTAX_ERROR, 1);
- lua_pop(L, 2); // err msg, err handler
- } else {
- if((status = lua_pcall(L, 0, LUA_MULTRET, base)) != 0)
- lua_pop(L, 2); // err msg, err handler, also ignore it - no relevance
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement