How to embed luasql.sqlite3 in a statically linked C program?

726 Views Asked by At

The luasql.sqlite3 module has been compiled into my C program successfully, statically linked. But, it seems the module has not been registered yet. The call of require 'luasql.sqlite3' always fails in Lua scripts.

Some other modules call luaL_register to register themselves. But luaL_register is not called in luaopen_luasql_sqlite3. How do I register luasql.sqlite3 in this case?

I use Lua-5.1.5.

The source code of luaopen_luasql_sqlite3 is at the bottom

3

There are 3 best solutions below

0
On BEST ANSWER

Here is the way of putting luaopen_ functions into the package.preload table.

lua_getfield(L, LUA_GLOBALSINDEX, "package");
lua_getfield(L, -1, "preload");
lua_pushcfunction(L, luaopen_socket_core);
lua_setfield(L, -2, "socket.core");
0
On

This works with LuaSQL 2.4 and Lua 5.1 AND newer...

In C

/* Execute the luasql initializers */
lua_getglobal(L, "package");
lua_getfield(L, -1, "preload");
lua_pushcfunction(L, luaopen_luasql_postgres);
lua_setfield(L, -2, "luasql.postgres");
lua_pop(L, 2);

lua_getglobal(L, "package");
lua_getfield(L, -1, "preload");
lua_pushcfunction(L, luaopen_luasql_mysql);
lua_setfield(L, -2, "luasql.mysql");
lua_pop(L, 2);

etc, etc for each DBI interface you need...and THEN, in your Lua script(s)

 local luasql = require "luasql.postgres";
 pg = luasql.postgres();
 dev, err = pg:connect( netidb_conninfo );
 if err then .....

Please note you will have to prototype luaopen_luasql_postgres(), etc yourself for C to compile successfully as the library doesn't have prototypes for the functions defined for external use.

1
On

require works with DLLs because it uses the given module name to track down the DLL and fetch a specific function from that DLL. It doesn't work automatically for static libraries because C and C++ have no introspection; you can't dymanically find a C function that starts with luaopen_.

As such, you need to tell the Lua package system that you want to make this module available to Lua code. You do this by sticking the luaopen_ function in the package.preload table, giving it the name that the module will be called.