summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorAki <please@ignore.pl>2021-02-24 20:43:11 +0100
committerAki <please@ignore.pl>2021-02-24 20:43:11 +0100
commitd46748ac59c3b8d8895d2671aa4b1eca3914d1d4 (patch)
tree1538031a06ab20bf423b9e6d13c7a1e0670ead76
parent4fdf60a4c9ce16dd459e05ad7664010ea45c43db (diff)
downloadplop-d46748ac59c3b8d8895d2671aa4b1eca3914d1d4.zip
plop-d46748ac59c3b8d8895d2671aa4b1eca3914d1d4.tar.gz
plop-d46748ac59c3b8d8895d2671aa4b1eca3914d1d4.tar.bz2
Added buffer and garbage collection to stream
-rw-r--r--stream.c26
-rw-r--r--stream.h9
2 files changed, 33 insertions, 2 deletions
diff --git a/stream.c b/stream.c
index d6a5254..a322e2b 100644
--- a/stream.c
+++ b/stream.c
@@ -1,11 +1,13 @@
#include "stream.h"
+#include <stdlib.h>
+
#include <lauxlib.h>
#include <lua.h>
/// Creates and pushes new Stream into the Lua stack.
/// \param L Lua state to push to
-/// \param fd File descriptor used by stream
+/// \param fd File descriptor used by the Stream
/// \return TODO
int stream_push_new(lua_State * L, const int fd)
{
@@ -14,10 +16,30 @@ int stream_push_new(lua_State * L, const int fd)
if (1 == luaL_newmetatable(L, "stream"))
{
- // TODO: initialize metatable for stream
+ lua_pushstring(L, "__gc");
+ lua_pushcfunction(L, stream_gc);
+ lua_rawset(L, -3);
}
lua_setmetatable(L, -2);
return LUA_OK;
}
+
+/// Metamethod to handle garbage collection of Stream userdata.
+/// \param L Lua state in which Stream resides
+/// \return Always zero, which is the number of the results pushed to the stack
+int stream_gc(lua_State * L)
+{
+ struct stream * s = lua_touserdata(L, -1);
+
+ if (NULL != s)
+ {
+ if (NULL != s->in.data)
+ {
+ free(s->in.data);
+ }
+ }
+
+ return 0;
+}
diff --git a/stream.h b/stream.h
index 5762bc8..f38b6ef 100644
--- a/stream.h
+++ b/stream.h
@@ -2,9 +2,18 @@
#include <lua.h>
+struct buffer
+{
+ char * data;
+ int length;
+ int offset;
+};
+
struct stream
{
int fd;
+ struct buffer in;
};
int stream_push_new(lua_State *, const int);
+int stream_gc(lua_State *);