|
| 1 | +#define LUA_LIB |
| 2 | + |
| 3 | +#include <lua.h> |
| 4 | +#include <lauxlib.h> |
| 5 | +#include "queue.h" |
| 6 | + |
| 7 | +static int |
| 8 | +lmqueue_new(lua_State *L) { |
| 9 | + int size = luaL_checkinteger(L, 1); |
| 10 | + struct queue * q = queue_new_ptr(size); |
| 11 | + lua_pushlightuserdata(L, q); |
| 12 | + return 1; |
| 13 | +} |
| 14 | + |
| 15 | +static int |
| 16 | +lmqueue_delete(lua_State *L) { |
| 17 | + luaL_checktype(L, 1, LUA_TLIGHTUSERDATA); |
| 18 | + struct queue *q = (struct queue *)lua_touserdata(L, 1); |
| 19 | + queue_delete(q); |
| 20 | + return 0; |
| 21 | +} |
| 22 | + |
| 23 | +static int |
| 24 | +lmqueue_send(lua_State *L) { |
| 25 | + luaL_checktype(L, 1, LUA_TLIGHTUSERDATA); |
| 26 | + luaL_checktype(L, 2, LUA_TLIGHTUSERDATA); |
| 27 | + struct queue *q = (struct queue *)lua_touserdata(L, 1); |
| 28 | + void *v = lua_touserdata(L, 2); |
| 29 | + if (queue_push_ptr(q, v)) { |
| 30 | + // block |
| 31 | + return 0; |
| 32 | + } |
| 33 | + lua_pushboolean(L, 1); |
| 34 | + return 1; |
| 35 | +} |
| 36 | + |
| 37 | +static int |
| 38 | +lmqueue_recv(lua_State *L) { |
| 39 | + luaL_checktype(L, 1, LUA_TLIGHTUSERDATA); |
| 40 | + struct queue *q = (struct queue *)lua_touserdata(L, 1); |
| 41 | + void *msg = queue_pop_ptr(q); |
| 42 | + if (msg == NULL) |
| 43 | + return 0; |
| 44 | + lua_pushlightuserdata(L, msg); |
| 45 | + return 1; |
| 46 | +} |
| 47 | + |
| 48 | +LUAMOD_API int |
| 49 | +luaopen_ltask_mqueue(lua_State *L) { |
| 50 | + luaL_Reg l[] = { |
| 51 | + { "new", lmqueue_new }, |
| 52 | + { "delete", lmqueue_delete }, |
| 53 | + { "send", lmqueue_send }, |
| 54 | + { "recv", lmqueue_recv }, |
| 55 | + { NULL, NULL }, |
| 56 | + }; |
| 57 | + luaL_newlib(L, l); |
| 58 | + return 1; |
| 59 | +} |
0 commit comments