1

luasql.sqlite3模块已成功编译到我的C程序中,静态链接。但是,该模块似乎尚未注册。在 Lua 脚本中调用require 'luasql.sqlite3'always 失败。

其他一些模块调用luaL_register来注册自己。但是luaL_register没有被调用luaopen_luasql_sqlite3luasql.sqlite3在这种情况下如何注册?

我使用 Lua-5.1.5。

luaopen_luasql_sqlite3的源码在底部

4

3 回答 3

2

这是将 luaopen_ 函数放入 package.preload 表的方法。

lua_getfield(L, LUA_GLOBALSINDEX, "package");
lua_getfield(L, -1, "preload");
lua_pushcfunction(L, luaopen_socket_core);
lua_setfield(L, -2, "socket.core");
于 2012-11-07T07:01:32.733 回答
1

require与 DLL 一起工作,因为它使用给定的模块名称来跟踪 DLL 并从该 DLL 中获取特定函数。它不能自动用于静态库,因为 C 和 C++ 没有自省;您无法动态找到以 . 开头的 C 函数luaopen_

因此,你需要告诉 Lua 包系统你想让这个模块对 Lua 代码可用。为此,您可以将luaopen_函数粘贴在package.preload表中,并为其命名模块将被调用的名称。

于 2012-09-02T13:37:12.143 回答
0

这适用于 LuaSQL 2.4 和 Lua 5.1 及更新版本...

在 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);

等等,对于您需要的每个 DBI 接口……然后,在您的 Lua 脚本中

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

请注意,您必须自己制作 luaopen_luasql_postgres() 等原型才能成功编译 C,因为该库没有为外部使用定义的函数的原型。

于 2020-04-12T01:56:59.517 回答