Parcourir la source

Create a Lua allocator, to use mg_malloc/mg_free

bel il y a 11 ans
Parent
commit
bd896a0fa0
1 fichiers modifiés avec 14 ajouts et 3 suppressions
  1. 14 3
      src/mod_lua.inl

+ 14 - 3
src/mod_lua.inl

@@ -817,6 +817,17 @@ static int lua_error_handler(lua_State *L)
     return 0;
 }
 
+static void * lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize) {
+  
+    (void)ud; (void)osize; /* not used */
+
+    if (nsize == 0) {
+        mg_free(ptr);
+        return NULL;
+    }
+    return mg_realloc(ptr, nsize);
+}
+
 void mg_exec_lua_script(struct mg_connection *conn, const char *path,
     const void **exports)
 {
@@ -827,7 +838,7 @@ void mg_exec_lua_script(struct mg_connection *conn, const char *path,
     conn->must_close=1;
 
     /* Execute a plain Lua script. */
-    if (path != NULL && (L = luaL_newstate()) != NULL) {
+    if (path != NULL && (L = lua_newstate(lua_allocator, NULL)) != NULL) {
         prepare_lua_environment(conn, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
         lua_pushcclosure(L, &lua_error_handler, 0);
 
@@ -885,7 +896,7 @@ struct file *filep, struct lua_State *ls)
         fileno(filep->fp), 0)) == MAP_FAILED) {
             lsp_send_err(conn, ls, "mmap(%s, %zu, %d): %s", path, (size_t) filep->size,
                 fileno(filep->fp), strerror(errno));
-    } else if ((L = ls != NULL ? ls : luaL_newstate()) == NULL) {
+    } else if ((L = ls != NULL ? ls : lua_newstate(lua_allocator, NULL)) == NULL) {
         send_http_error(conn, 500, http_500_error, "%s", "luaL_newstate failed");
     } else {
         /* We're not sending HTTP headers here, Lua page must do it. */
@@ -978,7 +989,7 @@ static void * lua_websocket_new(const char * script, struct mg_connection *conn,
             lws_data->shared = is_shared;
             lws_data->conn = conn;
             lws_data->script = mg_strdup(script);
-            lws_data->main = luaL_newstate();
+            lws_data->main = lua_newstate(lua_allocator, NULL);
             if (is_shared) {
                 (void)pthread_mutex_lock(&conn->ctx->mutex);
                 shared_websock_list = &(conn->ctx->shared_lua_websockets);