Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way for Lua script to call a C shared lib?

Tags:

lua

I come from more of a Python and CTYPES background...and am trying to work out the best way to call a standard C shared lib from Lua script.

I have heard of "Alien" (http://alien.luaforge.net/), but am not sure how current it is? Meaning it is updated regulary?

For example, I know that thier is an SQLite Lua library but let's say I wanted to call the SQLite shared lib that is created when I compile SQLIte?

So for example: In my case the lib is in /usr/local/lib/libsqlite3.so

If I write a little dummy script just to see if it can load the lib

require "libsqlite3"

print "hello"

I get the following error:

debian@debian:~/Desktop/SQLite Test$ lua sqlite_test.lua
lua: error loading module 'libsqlite3' from file '/usr/local/lib/lua/5.2/libsqlite3.so':
    /usr/local/lib/lua/5.2/libsqlite3.so: undefined symbol: luaopen_libsqlite3
stack traceback:
    [C]: in ?
    [C]: in function 'require'
    sqlite_test.lua:1: in main chunk
    [C]: in ?
debian@debian:~/Desktop/SQLite Test$ 

Does this mean that Lua cannot call shared libs "out the box" and that I HAVE TO use something like Alien?

I know I can also code the shared lib in such a way that it includes the Lua header files and I can make "Lua functions"...I was just hoping I could call shared libs that are "standard" on the box.

And help or advise would be greatly appreciated ;-)

Thanks

Lynton

like image 517
Lynton Grice Avatar asked Nov 12 '10 06:11

Lynton Grice


2 Answers

Lua cannot call C libraries out of the box. It does not ship with libffi, and as such doesn't work like ctypes.

Historically, lua is embedded into an application which in turn will add to the lua tables the needed functions and provide the lua stack manipulation to pass and return parameters.

Alien is a libffi adaptation and will work.

like image 84
Yann Ramin Avatar answered Sep 17 '22 06:09

Yann Ramin


Like Yann said, Lua cannot call C libraries by default. The usual practice is to expose the wanted API by means of creating a binding library. There are several places, where you can look for existing library bindings for Lua, like the wiki, LuaRocks or LuaDist.

If no bindings exist, you may try to use Alien to bind straight to C libraries using libffi.

For your example - Sqlite3, there are at least 2 bindings:

  • generic SQL binding - LuaSql, provides binding to Sqlite3, MySQL, Oracle...
  • specialized binding - Lua-Sqlite3
like image 32
Michal Kottman Avatar answered Sep 17 '22 06:09

Michal Kottman