diff --git a/src/blua/liolib.c b/src/blua/liolib.c
index b209eec91ff205e52e18b1f9ff4f1bb88aa91c0d..2d20f5292aea485878b4b8903d4902cd3240982a 100644
--- a/src/blua/liolib.c
+++ b/src/blua/liolib.c
@@ -26,6 +26,8 @@
 #define IO_INPUT	1
 #define IO_OUTPUT	2
 
+#define FILELIMIT 1024*1024 // Size limit for reading/writing files
+
 
 static const char *const fnames[] = {"input", "output"};
 static const char *whitelist[] = { // Allow scripters to write files of these types to SRB2's folder
@@ -437,6 +439,7 @@ static int io_readline (lua_State *L) {
 static int g_write (lua_State *L, FILE *f, int arg) {
   int nargs = lua_gettop(L) - 1;
   int status = 1;
+  size_t count;
   for (; nargs--; arg++) {
     if (lua_type(L, arg) == LUA_TNUMBER) {
       /* optimization: could be done exactly as for strings */
@@ -446,6 +449,12 @@ static int g_write (lua_State *L, FILE *f, int arg) {
     else {
       size_t l;
       const char *s = luaL_checklstring(L, arg, &l);
+	  count += l;
+	  if (ftell(f) + l > FILELIMIT)
+	  {
+		luaL_error(L,"write limit bypassed in file. Changes have been discarded.");
+		break;
+	  }
       status = status && (fwrite(s, sizeof(char), l, f) == l);
     }
   }