2

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

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
douyw
  • 4,034
  • 1
  • 30
  • 28

3 Answers3

2

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");
douyw
  • 4,034
  • 1
  • 30
  • 28
1

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • thanks. I call luaopen_ function directly in C. luaL_requiref function is not available in lua5.1. Is there a convenient way to put luaopen_ function into package.preload table? – douyw Sep 02 '12 at 14:42
0

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.