/* * Concat "<key>=<value>" as the result string. We store away the string in a * Lua table so it will not be garbage collected. This procedure has the * advantage of sharing environment strings between all nodes, as Lua * internally store only one copy of each string. */ static const char* record_env_mapping(td_engine *engine, lua_State *L, int engine_pos, int key, int value) { const char* result; lua_pushvalue(L, engine_pos); lua_gettable(L, LUA_REGISTRYINDEX); lua_pushvalue(L, key); lua_pushlstring(L, "=", 1); lua_pushvalue(L, value); lua_concat(L, 3); result = lua_tostring(L, -1); lua_pushboolean(L, 1); lua_settable(L, -3); lua_pop(L, 1); return result; }
static int parse_file (lua_State *L, const char *filename) { ZIO z; int status; int bin; /* flag for file mode */ int c; /* look ahead char */ PHYSFS_file *f = PHYSFS_openRead(filename, -1); if (f == NULL) return LUA_ERRFILE; /* unable to open file */ c = my_physfs_fgetc(f); PHYSFS_close(f); f = PHYSFS_openRead(filename, -1); bin = (c == ID_CHUNK); lua_pushstring(L, "@"); lua_pushstring(L, filename); lua_concat(L, 2); filename = lua_tostring(L, -1); /* filename = '@'..filename */ lua_pop(L, 1); /* OK: there is no GC during parser */ luaZ_Fopen(&z, f, filename); status = protectedparser(L, &z, bin); PHYSFS_close(f); return status; }
/* the equivalent of lua_is* for usertable */ static int lua_isusertable (lua_State* L, int lo, const const char* type) { int r = 0; if (lo < 0) lo = lua_gettop(L)+lo+1; lua_pushvalue(L,lo); lua_rawget(L,LUA_REGISTRYINDEX); /* get registry[t] */ if (lua_isstring(L,-1)) { r = strcmp(lua_tostring(L,-1),type)==0; if (!r) { /* try const */ lua_pushstring(L,"const "); lua_insert(L,-2); lua_concat(L,2); r = lua_isstring(L,-1) && strcmp(lua_tostring(L,-1),type)==0; } } lua_pop(L, 1); return r; }
static int getline_nowait(lua_State *L) { char buf[BMO_TEXT_BUF]; memset(buf, '\0', BMO_TEXT_BUF); lua_settop(L, 0); size_t len; if (!current_buff) { current_buff = ""; } len = try_getline(buf, BMO_TEXT_BUF); if (!len) { return 0; } buf[len < BMO_TEXT_BUF ? len : BMO_TEXT_BUF - 1] = '\0'; lua_pushstring(L, current_buff); lua_pushstring(L, buf); lua_concat(L, 2); current_buff = bmo_strdup(lua_tostring(L, -1)); return 1; }
int errorhandler(lua_State *state) { // TODO //const char* msg = lua_tostring(state, 1); lua_Debug debug; int level = 0; int count = 0; lua_pushstring(state, "\n\nStack trace:\n"); while(lua_getstack(state, level, &debug)) { lua_getinfo(state, "Sl", &debug); if(strcmp(debug.what, "C")) { lua_pushstring(state, debug.short_src); lua_pushstring(state, ":"); lua_pushnumber(state, debug.currentline); lua_pushstring(state, "\n"); ++count; } ++level; } lua_concat(state, 4*count+2); return 1; }
static int loadline(lua_State *L) { int status; lua_settop(L, 0); if(!pushline(L, 1)) return -1; /* no input */ for(;;) { /* repeat until gets a complete line */ status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin"); if(!incomplete(L, status)) break; /* cannot try to add lines? */ if(!pushline(L, 0)) /* no more input? */ return -1; lua_pushliteral(L, "\n"); /* add a new line... */ lua_insert(L, -2); /* ...between the two lines */ lua_concat(L, 3); /* join them */ } lua_saveline(L, 1); lua_remove(L, 1); /* remove line */ return status; }
static const char *findfile (lua_State *L, const char *name, const char *pname) { const char *path; name = luaL_gsub(L, name, ".", LUA_DIRSEP); lua_getfield(L, LUA_ENVIRONINDEX, pname); path = lua_tostring(L, -1); if (path == NULL) luaL_error(L, LUA_QL("package.%s") " must be a string", pname); lua_pushliteral(L, ""); /* error accumulator */ while ((path = pushnexttemplate(L, path)) != NULL) { const char *filename; filename = luaL_gsub(L, lua_tostring(L, -1), LUA_PATH_MARK, name); lua_remove(L, -2); /* remove path template */ if (readable(filename)) /* does file exist and is readable? */ return filename; /* return that file name */ lua_pushfstring(L, "\n\tno file " LUA_QS, filename); lua_remove(L, -2); /* remove file name */ lua_concat(L, 2); /* add entry to possible error message */ } return NULL; /* not found */ }
/* Push and returns the corresponding object typename */ TOLUA_API const char* tolua_typename (lua_State* L, int lo) { int tag = lua_type(L,lo); if (tag == LUA_TNONE) lua_pushstring(L,"[no object]"); else if (tag != LUA_TUSERDATA && tag != LUA_TTABLE) lua_pushstring(L,lua_typename(L,tag)); else if (tag == LUA_TUSERDATA) { if (!lua_getmetatable(L,lo)) { lua_pushstring(L,lua_typename(L,tag)); } else { lua_rawget(L,LUA_REGISTRYINDEX); if (!lua_isstring(L,-1)) { lua_pop(L,1); lua_pushstring(L,"[undefined]"); } } } else /* is table */ { lua_pushvalue(L,lo); lua_rawget(L,LUA_REGISTRYINDEX); if (!lua_isstring(L,-1)) { lua_pop(L,1); lua_pushstring(L,"table"); } else { lua_pushstring(L,"class "); lua_insert(L,-2); lua_concat(L,2); } } return lua_tostring(L,-1); }
void parse_args(lua_State * L, int argc, char ** argv, bool * interactive, int * begin_script) { int ch; static struct option longopts[] = { { "help", 0, NULL, 'h' }, { "verbose", 0, NULL, 'v' }, { "interactive", 0, NULL, 'i' }, { "path", 0, NULL, 'p' }, { NULL, 0, NULL, 0 } }; int verbose = 0; /* Parse commandline options */ opterr = 0; while ((ch = getopt_long(argc, argv, "+hvip:", longopts, NULL)) != -1) { switch (ch) { case 'v': verbose++; terra_setverbose(L,verbose); break; case 'i': *interactive = true; break; case 'p': lua_getglobal(L,"package"); lua_getfield(L,-1,"path"); lua_pushstring(L,";"); lua_pushstring(L,optarg); lua_concat(L,3); lua_setfield(L,-2,"path"); lua_pop(L,1); break; case ':': case 'h': default: usage(); exit(-1); break; } } *begin_script = optind; }
static int luaC_array__tostring(lua_State *L) { Array *A = lunum_checkarray1(L, 1); lua_pushstring(L, " [ "); size_t nstr = 1; for (size_t n=0; n<A->size; ++n) { char s[64]; switch (A->dtype) { case ARRAY_TYPE_BOOL : sprintf(s, "%s" , ((Bool*)A->data)[n]?"true":"false"); break; case ARRAY_TYPE_CHAR : sprintf(s, "%d" , ((char *)A->data)[n]); break; case ARRAY_TYPE_SHORT : sprintf(s, "%d" , ((short *)A->data)[n]); break; case ARRAY_TYPE_INT : sprintf(s, "%d" , ((int *)A->data)[n]); break; case ARRAY_TYPE_LONG : sprintf(s, "%ld", ((long *)A->data)[n]); break; case ARRAY_TYPE_SIZE_T : sprintf(s, "%lu", ((size_t *)A->data)[n]); break; case ARRAY_TYPE_FLOAT : sprintf(s, "%g" , ((float *)A->data)[n]); break; case ARRAY_TYPE_DOUBLE : sprintf(s, "%g" , ((double *)A->data)[n]); break; case ARRAY_TYPE_COMPLEX : sprintf(s, "%g%s%gj", creal(((Complex*)A->data)[n]), cimag(((Complex*)A->data)[n]) >= 0.0 ? "+" : "-", fabs(cimag(((Complex*)A->data)[n]))); break; } if (n == A->size-1) { lua_pushfstring(L, "%s", s); } else { lua_pushfstring(L, "%s, ", s); } if ((n+1) % 10 == 0 && n != 0 && n != A->size-1) { lua_pushstring(L, "\n "); ++nstr; } } lua_pushstring(L, " ]"); ++nstr; lua_concat(L, A->size + nstr); return 1; }
int jiveL_style_path(lua_State *L) { int numStrings = 0; lua_pushvalue(L, 1); while (!lua_isnil(L, -1)) { lua_getfield(L, -1, "style"); if (!lua_isnil(L, -1)) { lua_insert(L, 2); lua_pushstring(L, "."); lua_insert(L, 2); numStrings += 2; } else { lua_pop(L, 1); } lua_getfield(L, -1, "styleModifier"); if (!lua_isnil(L, -1)) { lua_insert(L, 2); lua_pushstring(L, "."); lua_insert(L, 2); numStrings += 2; } else { lua_pop(L, 1); } lua_getfield(L, -1, "parent"); lua_replace(L, -2); } lua_pop(L, 1); lua_concat(L, numStrings - 1); lua_remove(L, -2); lua_pushvalue(L, -1); lua_setfield(L, 1, "_stylePath"); return 1; }
static int ll_require (lua_State *L) { const char *name = luaL_checkstring(L, 1); int i; lua_settop(L, 1); /* _LOADED table will be at index 2 */ lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); lua_getfield(L, 2, name); if (lua_toboolean(L, -1)) /* is it there? */ return 1; /* package is already loaded */ /* else must load it; iterate over available loaders */ lua_getfield(L, lua_upvalueindex(1), "loaders"); if (!lua_istable(L, -1)) luaL_error(L, LUA_QL("package.loaders") " must be a table"); lua_pushliteral(L, ""); /* error message accumulator */ for (i=1; ; i++) { lua_rawgeti(L, -2, i); /* get a loader */ if (lua_isnil(L, -1)) luaL_error(L, "module " LUA_QS " not found:%s", name, lua_tostring(L, -2)); lua_pushstring(L, name); lua_call(L, 1, 1); /* call it */ if (lua_isfunction(L, -1)) /* did it find module? */ break; /* module loaded successfully */ else if (lua_isstring(L, -1)) /* loader returned error message? */ lua_concat(L, 2); /* accumulate it */ else lua_pop(L, 1); } lua_pushstring(L, name); /* pass name as argument to module */ lua_call(L, 1, 1); /* run loaded module */ if (!lua_isnil(L, -1)) /* non-nil return? */ lua_setfield(L, 2, name); /* _LOADED[name] = returned value */ lua_getfield(L, 2, name); if (lua_isnil(L, -1)) { /* module did not set a value? */ lua_pushboolean(L, 1); /* use true as result */ lua_pushvalue(L, -1); /* extra copy to be returned */ lua_setfield(L, 2, name); /* _LOADED[name] = true */ } return 1; }
/* ** search for 'objidx' in table at index -1. ** return 1 + string at top if find a good name. */ static int findfield (lua_State *L, int objidx, int level) { if (level == 0 || !lua_istable(L, -1)) return 0; /* not found */ lua_pushnil(L); /* start 'next' loop */ while (lua_next(L, -2)) { /* for each pair in table */ if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */ if (lua_rawequal(L, objidx, -1)) { /* found object? */ lua_pop(L, 1); /* remove value (but keep name) */ return 1; } else if (findfield(L, objidx, level - 1)) { /* try recursively */ lua_remove(L, -2); /* remove table (but keep name) */ lua_pushliteral(L, "."); lua_insert(L, -2); /* place '.' between the two names */ lua_concat(L, 3); return 1; } } lua_pop(L, 1); /* remove value */ } return 0; /* not found */ }
static int lluv_udp_try_send(lua_State *L){ lluv_handle_t *handle = lluv_check_udp(L, 1, LLUV_FLAG_OPEN); struct sockaddr_storage sa; int err = lluv_check_addr(L, 2, &sa); size_t len; const char *str = luaL_checklstring(L, 4, &len); uv_buf_t buf = uv_buf_init((char*)str, len); if(err < 0){ lua_settop(L, 3); lua_pushliteral(L, ":");lua_insert(L, -2);lua_concat(L, 3); return lluv_fail(L, handle->flags, LLUV_ERR_UV, err, lua_tostring(L, -1)); } lluv_check_none(L, 3); err = uv_udp_try_send(LLUV_H(handle, uv_udp_t), &buf, 1, (struct sockaddr*)&sa); if(err < 0){ return lluv_fail(L, handle->flags, LLUV_ERR_UV, err, NULL); } lua_pushinteger(L, err); return 1; }
int ObjectBinding::newIndex( lua_State* L ) { co::IObject** ud = reinterpret_cast<co::IObject**>( lua_touserdata( L, 1 ) ); assert( ud ); assert( lua_isstring( L, 2 ) ); __BEGIN_EXCEPTIONS_BARRIER__ if( isStringComponent( L, 2 ) ) throw co::IllegalArgumentException( "'component' is a facet and cannot be set" ); co::IObject* object = *ud; pushMember( L, object->getComponent(), true ); if( lua_islightuserdata( L, -1 ) ) { co::IPort* port = checkPort( L, -1 ); if( port->getIsFacet() ) { lua_pushliteral( L, "'" ); lua_pushvalue( L, 2 ); lua_pushliteral( L, "' is a facet and cannot be set" ); lua_concat( L, 3 ); throw lua::MsgOnStackException(); } co::IService* service; co::Any any; any.setVariable( port->getType(), co::Any::VarIsPointer|co::Any::VarIsReference, &service ); LuaState::getValue( L, 3, any ); object->setServiceAt( port, service ); // notify interceptors for( co::Range<IInterceptor* const> r( sm_interceptors ); r; r.popFirst() ) r.getFirst()->postSetService( object, port, service ); } return 0; __END_EXCEPTIONS_BARRIER__ }
int CorsixTH_lua_stacktrace(lua_State *L) { // err = tostring(err) lua_settop(L, 1); lua_getglobal(L, "tostring"); lua_insert(L, 1); lua_call(L, 1, 1); // err = <description> .. err lua_pushliteral(L, "An error has occured in CorsixTH:\n"); lua_insert(L, 1); lua_concat(L, 2); // return debug.traceback(err, 2) lua_getglobal(L, "debug"); lua_getfield(L, -1, "traceback"); lua_pushvalue(L, 1); lua_pushinteger(L, 2); lua_call(L, 2, 1); return 1; }
static int bindtable(lua_State *T, sqlite3_stmt *stmt) { int parameters = sqlite3_bind_parameter_count(stmt); const char *name; const char *err; int i; for (i = 1; i <= parameters; i++) { int ret; name = sqlite3_bind_parameter_name(stmt, i); lua_settop(T, 2); if (name == NULL || name[0] == '?') lua_rawgeti(T, 2, i); else if (name[0] == '@') lua_getfield(T, 2, name + 1); else lua_getfield(T, 2, name); ret = _bind_arg(T, 3, stmt, i); if (ret != SQLITE_OK) { err = sqlite3_errmsg(sqlite3_db_handle(stmt)); goto error; } } return 0; error: (void)sqlite3_clear_bindings(stmt); luaL_where(T, 1); if (name == NULL || name[0] == '?') lua_pushfstring(T, "error binding %d: %s", i, err); else lua_pushfstring(T, "error binding '%s': %s", name, err); lua_concat(T, 2); return -1; }
/* ** Rollback the current transaction. */ static int conn_rollback(lua_State *L) { char *errmsg; conn_data *conn = getconnection(L); int res; const char *sql = "ROLLBACK"; if (conn->auto_commit == 0) sql = "ROLLBACK;BEGIN"; res = sqlite3_exec(conn->sql_conn, sql, NULL, NULL, &errmsg); if (res != SQLITE_OK) { lua_pushnil(L); lua_pushliteral(L, LUASQL_PREFIX); lua_pushstring(L, errmsg); sqlite3_free(errmsg); lua_concat(L, 2); return 2; } lua_pushboolean(L, 1); return 1; }
/* Load add-on module. */ static int loadjitmodule(lua_State *L) { lua_getglobal(L, "require"); lua_pushliteral(L, "jit."); lua_pushvalue(L, -3); lua_concat(L, 2); if (lua_pcall(L, 1, 1, 0)) { const char *msg = lua_tostring(L, -1); if (msg && !strncmp(msg, "module ", 7)) goto nomodule; return report(L, 1); } lua_getfield(L, -1, "start"); if (lua_isnil(L, -1)) { nomodule: l_message(progname, "unknown luaJIT command or jit.* modules not installed"); return 1; } lua_remove(L, -2); /* Drop module table. */ return 0; }
/*! * \brief Concatenate a list of lua function arguments into a comma separated * string. * \param L the lua_State to use * \param start the index of the first argument * \param nargs the number of args * * The resulting string will be left on the top of the stack. */ static void lua_concat_args(lua_State *L, int start, int nargs) { int concat = 0; int i = start + 1; if (start <= nargs && !lua_isnil(L, start)) { lua_pushvalue(L, start); concat += 1; } for (; i <= nargs; i++) { if (lua_isnil(L, i)) { lua_pushliteral(L, ","); concat += 1; } else { lua_pushliteral(L, ","); lua_pushvalue(L, i); concat += 2; } } lua_concat(L, concat); }
static int glob_tostring(lua_State *L) { struct _fileglob* glob = *(struct _fileglob**)(lua_touserdata(L, 1)); fileglob_uint64 filetime; char buffer[100]; int top; if (!glob) { lua_pushstring(L, "[glob object]: done"); return 1; } top = lua_gettop(L); lua_pushstring(L, "[glob object]: filename = \""); lua_pushstring(L, fileglob_FileName(glob)); lua_pushstring(L, "\""); sprintf(buffer, ", creation_time = %lld", fileglob_CreationTime(glob)); lua_pushstring(L, buffer); sprintf(buffer, ", access_time = %lld", fileglob_AccessTime(glob)); lua_pushstring(L, buffer); sprintf(buffer, ", write_time = %lld", fileglob_WriteTime(glob)); lua_pushstring(L, buffer); filetime = fileglob_CreationFILETIME(glob); sprintf(buffer, ", creation_FILETIME = { %u, %u }", (unsigned int)(filetime & 0xffffffff), (unsigned int)(filetime >> 32)); lua_pushstring(L, buffer); filetime = fileglob_AccessFILETIME(glob); sprintf(buffer, ", access_FILETIME = { %u, %u }", (unsigned int)(filetime & 0xffffffff), (unsigned int)(filetime >> 32)); lua_pushstring(L, buffer); filetime = fileglob_WriteFILETIME(glob); sprintf(buffer, ", write_FILETIME = { %u, %u }", (unsigned int)(filetime & 0xffffffff), (unsigned int)(filetime >> 32)); lua_pushstring(L, buffer); sprintf(buffer, ", size = %lld", fileglob_FileSize(glob)); lua_pushstring(L, buffer); sprintf(buffer, ", is_directory = %s", fileglob_IsDirectory(glob) ? "true" : "false"); lua_pushstring(L, buffer); sprintf(buffer, ", is_readonly = %s", fileglob_IsReadOnly(glob)? "true" : "false"); lua_pushstring(L, buffer); lua_concat(L, lua_gettop(L) - top); return 1; }
static int filefind_tostring(lua_State *L) { struct FileFindInfo* info = filefind_checkmetatable(L, 1); char buffer[100]; int top; #if defined(WIN32) if (info->handle == INVALID_HANDLE_VALUE) { lua_pushstring(L, "[filefind object]: empty"); return 1; } top = lua_gettop(L); lua_pushstring(L, "[filefind object]: filename = \""); lua_pushstring(L, info->fd.cFileName); lua_pushstring(L, "\""); sprintf(buffer, ", creation_time = %u", fileglob_ConvertToTime_t(&info->fd.ftCreationTime)); lua_pushstring(L, buffer); sprintf(buffer, ", access_time = %u", fileglob_ConvertToTime_t(&info->fd.ftLastAccessTime)); lua_pushstring(L, buffer); sprintf(buffer, ", write_time = %u", fileglob_ConvertToTime_t(&info->fd.ftLastWriteTime)); lua_pushstring(L, buffer); sprintf(buffer, ", creation_FILETIME = { %u, %u }", info->fd.ftCreationTime.dwLowDateTime, info->fd.ftCreationTime.dwHighDateTime); lua_pushstring(L, buffer); sprintf(buffer, ", access_FILETIME = { %u, %u }", info->fd.ftLastAccessTime.dwLowDateTime, info->fd.ftLastAccessTime.dwHighDateTime); lua_pushstring(L, buffer); sprintf(buffer, ", write_FILETIME = { %u, %u }", info->fd.ftLastWriteTime.dwLowDateTime, info->fd.ftLastWriteTime.dwHighDateTime); lua_pushstring(L, buffer); sprintf(buffer, ", size = %I64d", ((unsigned __int64)info->fd.nFileSizeLow + ((unsigned __int64)info->fd.nFileSizeHigh << 32))); lua_pushstring(L, buffer); sprintf(buffer, ", is_directory = %s", (info->fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 ? "true" : "false"); lua_pushstring(L, buffer); sprintf(buffer, ", is_readonly = %s", (info->fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? "true" : "false"); lua_pushstring(L, buffer); lua_concat(L, lua_gettop(L) - top); return 1; #else return 0; #endif }
int os_locate(lua_State* L) { const char* path; int i; int nArgs = lua_gettop(L); /* Fetch premake.path */ lua_getglobal(L, "premake"); lua_getfield(L, -1, "path"); path = lua_tostring(L, -1); for (i = 1; i <= nArgs; ++i) { const char* name = lua_tostring(L, i); /* Direct path to file? Return as absolute path */ if (do_isfile(name)) { lua_pushcfunction(L, path_getabsolute); lua_pushvalue(L, i); lua_call(L, 1, 1); return 1; } /* do_locate(arg[i], premake.path) */ if (do_locate(L, name, path)) { return 1; } /* embedded in the executable? */ if (premake_find_embedded_script(name)) { lua_pushstring(L, "$/"); lua_pushvalue(L, i); lua_concat(L, 2); return 1; } } return 0; }
int LuaProgressSink::LuaDebugOut(lua_State *L) { ProgressSink *ps = GetObjPointer(L, lua_upvalueindex(1)); // Check trace level if (lua_isnumber(L, 1)) { if (lua_tointeger(L, 1) > ps->GetTraceLevel()) return 0; // remove trace level lua_remove(L, 1); } // Only do format-string handling if there's more than one argument left // (If there's more than one argument left, assume first is a format string and rest are format arguments) if (lua_gettop(L) > 1) { // Format the string lua_getglobal(L, "string"); lua_getfield(L, -1, "format"); // Here stack contains format string, format arguments, 'string' table, format function // remove 'string' table lua_remove(L, -2); // put the format function into place lua_insert(L, 1); // call format function if (lua_pcall(L, lua_gettop(L) - 1, 1, 0)) { // format failed so top of the stack now has an error message // which we want to add position information to luaL_where(L, 1); lua_insert(L, 1); lua_concat(L, 2); lua_error(L); } } // Top of stack is now a string to output ps->Log(luaL_checkstring(L, 1)); return 0; }
/** @name listFiles @text Lists the files contained in a directory @opt string path Path to search. Default is current directory. @out table files A table of filenames (or nil if the path is invalid) */ int MOAIFileSystem::_listFiles ( lua_State* L ) { UNUSED ( L ); STLString oldPath = USFileSys::GetCurrentPath (); cc8* dir = NULL; if ( lua_type ( L, 1 ) == LUA_TSTRING ) { dir = lua_tostring ( L, 1 ); if( !USFileSys::SetCurrentPath ( dir )) { return 0; } } USDirectoryItr dirItr; lua_newtable ( L ); int n = 0; dirItr.Start (); while ( dirItr.NextFile ()) { if ( dir ) { lua_pushstring ( L, dir ); lua_pushstring ( L, "/" ); lua_pushstring ( L, dirItr.Current ()); lua_concat ( L, 3 ); } else { lua_pushstring ( L, dirItr.Current ()); } n++; luaL_setn ( L, -2, n ); // new size lua_rawseti ( L, -2, n ); // t[pos] = v } USFileSys::SetCurrentPath ( oldPath ); return 1; }
static int make_path_relative(lua_State *L) { if (!lua_isstring(L, -1) || !lua_isstring(L, -2)) { lua_pushnil(L); return 1; } const char *x = lua_tostring(L, -1); //file const char *y = lua_tostring(L, -2); //origin path (with trailing '/') int strings = 1; while (*x && *x == *y) { x++; y++; } while (*y) { if (*(y++) == '/') { lua_pushstring(L, "../"); strings++; } } lua_pushstring(L, x); lua_concat(L, strings); return 1; }
/** * Override Lua print function, output message to NginX error logs. * * @param l Lua state pointer * @retval always 0 (don't return values to Lua) * @note NginX request pointer should be stored in Lua VM registry with key * 'ngx._req' in order to make logging working. * */ int ngx_http_lua_print(lua_State *l) { ngx_http_request_t *r; lua_getglobal(l, GLOBALS_SYMBOL_REQUEST); r = lua_touserdata(l, -1); lua_pop(l, 1); if(r && r->connection && r->connection->log) { const char *s; // XXX: easy way to support multiple args, any serious performance penalties? lua_concat(l, lua_gettop(l)); s = lua_tostring(l, -1); ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "(lua-print) %s", (s == NULL) ? "(null)" : s); } else { dd("(lua-print) can't output print content to error log due to invalid logging context!"); } return 0; }
/** Generate and throw an error. @function [parent=#global] error @param level stack level where the error must be reported @param narg indice of the erroneous argument @param expected name of the expected type @param got name of the type actually found @return never returns (throws a Lua error instead) */ static int error( lua_State *L, int level, int narg, const char *expected, const char *got) { lua_Debug ar; lua_getstack( L, level, & ar); lua_getinfo( L, "n", & ar); luaL_where( L, level+1); lua_pushfstring( L, " bad argument #%d to %s (%s expected, got %s)", narg, ar.name, expected, got); lua_concat( L, 2); #if 0 /* Debugging cruft */ int i; for(i=0;i<10;i++){ if( ! lua_getstack( L, i, & ar)) break; lua_getinfo( L, "n", & ar); printf( "\tat level %d: '%s' / '%s'\n", i, ar.name, ar.namewhat); } printf( "\tend of error, level was %d\n\n", level); #endif return lua_error( L); }
static int luaA_dofunction_on_error(lua_State *L) { /* Convert error to string, to prevent a follow-up error with lua_concat. */ luaA_tolstring(L, -1, NULL); /* duplicate string error */ lua_pushvalue(L, -1); /* emit error signal */ signal_object_emit(L, &global_signals, "debug::error", 1); if(!luaL_dostring(L, "return debug.traceback(\"error while running function\", 3)")) { /* Move traceback before error */ lua_insert(L, -2); /* Insert sentence */ lua_pushliteral(L, "\nerror: "); /* Move it before error */ lua_insert(L, -2); lua_concat(L, 3); } return 1; }
static int file_read(lua_State *L) { char buf[4096]; char filepath[512]; const char *file = luaL_checkstring(L, 1); Q_snprintf(filepath, sizeof(filepath), "%s/%s/%s", pAdminOP.GameDir(), pAdminOP.DataDir(), file); V_FixSlashes(filepath); FILE *fp = fopen(filepath, "rt"); if(fp) { int top = lua_gettop(L); int pushes = 0; int len; while(!feof(fp)) { if(len = fread(buf, 1, sizeof(buf), fp)) { luaL_checkstack(L, 1, "file read"); lua_pushlstring(L, buf, len); pushes++; } } fclose(fp); if(pushes) { lua_concat(L, pushes); return 1; } } lua_pushstring(L, ""); return 1; }