Skip ZMQ context for embedded Lua from C

In my C application, I have one ZMQ context that I would like to share with all Lua states. I am using Lua version 5.2 and ZMQ version 3.2.

I would like to use the existing binding for Lua, for example lzmq.

For instance:

// create ZMQ context
void *ctx = zmq_ctx_new();
...
// create Lua State
lua_State *L = luaL_newstate();
...
// push the context or something
lua_setglobal(L, "MY_ZMQ_CONTEXT");

and then the ability to somehow use this ZMQ context in Lua (example using lzmq):

local zmq = require "lzmq"
require "utils"

print_version(zmq)

local ctx = MY_ZMQ_CONTEXT -- ???

local skt = ctx:socket{zmq.REQ,
    linger = 0, rcvtimeo = 1000;
    connect = "inproc://hello";
}

skt:send("hello from cli")
print_msg("recv: ",skt:recv())

skt:close()

How would I do something like this? either using lzmq or any other ZMQ Lua bindings?

+4
source share
1 answer

You can install lightuserda and use the init_ctx function.

lua_pushlightuserdata(L, ctx);
lua_setglobal(L, "MY_ZMQ_CONTEXT");

local zmq = require "lzmq"
local ctx = zmq.init_ctx(MY_ZMQ_CONTEXT)

In this case, you cannot close the context from Lua. I have an idea to add this functionality to the next version.

lzmq C functoin LUAZMQ_EXPORT int luazmq_context (lua_State *L, void *ctx, unsigned char own). .

luazmq_contex(L, ctx, 0);
// or if you want hase ability to destroy contex from Lua
// luazmq_contex(L, ctx, 1);

// MY_ZMQ_CONTEXT is lzmq context
lua_setglobal(L, "MY_ZMQ_CONTEXT");
+3

Source: https://habr.com/ru/post/1543487/


All Articles