Skip to content

Instantly share code, notes, and snippets.

@leiradel
Created February 29, 2020 19:44
Show Gist options
  • Save leiradel/41eecd75c50545835d429b369e26a5eb to your computer and use it in GitHub Desktop.
Save leiradel/41eecd75c50545835d429b369e26a5eb to your computer and use it in GitHub Desktop.
Use a package searcher to static link LuaSocket into an executable.
#include <stddef.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include "luasocket/src/ftp.lua.h"
#include "luasocket/src/headers.lua.h"
#include "luasocket/src/http.lua.h"
#include "luasocket/src/ltn12.lua.h"
#include "luasocket/src/mbox.lua.h"
#include "luasocket/src/mime.lua.h"
#include "luasocket/src/smtp.lua.h"
#include "luasocket/src/socket.lua.h"
#include "luasocket/src/tp.lua.h"
#include "luasocket/src/url.lua.h"
int luaopen_mime_core(lua_State*);
int luaopen_socket_core(lua_State*);
typedef struct
{
const char* name;
union
{
const char* source;
lua_CFunction openf;
};
size_t length;
}
module_t;
#define MODL(name, array) {name, {array}, sizeof(array)}
#define MODC(name, openf) {name, {(char*)openf}, 0}
static const module_t modules[] =
{
MODL("ltn12", socket_ltn12_lua),
MODL("mbox", socket_mbox_lua),
MODL("mime", socket_mime_lua),
MODC("mime.core", luaopen_mime_core),
MODL("socket", socket_socket_lua),
MODC("socket.core", luaopen_socket_core),
MODL("socket.ftp", socket_ftp_lua),
MODL("socket.headers", socket_headers_lua),
MODL("socket.http", socket_http_lua),
MODL("socket.smtp", socket_smtp_lua),
MODL("socket.tp", socket_tp_lua),
MODL("socket.url", socket_url_lua)
};
#undef MODL
#undef MODC
static int searcher(lua_State* const L)
{
const char* const name = lua_tostring(L, 1);
for (size_t i = 0; i < sizeof(modules) / sizeof(modules[0]); i++)
{
if (strcmp(name, modules[i].name) == 0)
{
if (modules[i].length != 0)
{
const int res = luaL_loadbufferx(L, modules[i].source, modules[i].length, name, "t");
if (res != LUA_OK)
{
return lua_error(L);
}
}
else
{
lua_pushcfunction(L, modules[i].openf);
}
return 1;
}
}
lua_pushfstring(L, "unknown module \"%s\"", name);
return 1;
}
void registermods(lua_State* const L)
{
lua_getglobal(L, "package");
lua_getfield(L, -1, "searchers");
const size_t length = lua_rawlen(L, -1);
lua_pushcfunction(L, searcher);
lua_rawseti(L, -2, length + 1);
lua_pop(L, 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment