/* ** Interface to 'lua_pcall', which sets appropriate message function ** and C-signal handler. Used to run all chunks. */ staticintdocall(lua_State *L, int narg, int nres) { int status; int base = lua_gettop(L) - narg; /* function index */ lua_pushcfunction(L, msghandler); /* push message handler */ lua_insert(L, base); /* put it under function and args */ globalL = L; /* to be available to 'laction' */ signal(SIGINT, laction); /* set C-signal handler */ status = lua_pcall(L, narg, nres, base); signal(SIGINT, SIG_DFL); /* reset C-signal handler */ lua_remove(L, base); /* remove message handler from the stack */ return status; }
/* ** Calls 'require(name)' and stores the result in a global variable ** with the given name. */ staticintdolibrary(lua_State *L, constchar *name) { int status; lua_getglobal(L, "require"); lua_pushstring(L, name); status = docall(L, 1, 1); /* call 'require(name)' */ if (status == LUA_OK) lua_setglobal(L, name); /* global[name] = require return */ return report(L, status); }
/* ** Do the REPL: repeatedly read (load) a line, evaluate (call) it, and ** print any results. */ staticvoiddoREPL(lua_State *L) { int status; constchar *oldprogname = progname; progname = NULL; /* no 'progname' on errors in interactive mode */ while ((status = loadline(L)) != -1) { if (status == LUA_OK) status = docall(L, 0, LUA_MULTRET); if (status == LUA_OK) l_print(L); else report(L, status); } lua_settop(L, 0); /* clear stack */ lua_writeline(); progname = oldprogname; }
doREPL()循环调用 loadline()来从终端加载 Lua语句。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* ** Read a line and try to load (compile) it first as an expression (by ** adding "return " in front of it) and second as a statement. Return ** the final status of load/call with the resulting function (if any) ** in the top of the stack. */ staticintloadline(lua_State *L) { int status; lua_settop(L, 0); if (!pushline(L, 1)) return-1; /* no input */ if ((status = addreturn(L)) != LUA_OK) /* 'return ...' did not work? */ status = multiline(L); /* try as command, maybe with continuation lines */ lua_remove(L, 1); /* remove line from the stack */ lua_assert(lua_gettop(L) == 1); return status; }