lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2009/5/14 Lloyd <lloyd@cdactvm.in>:
> On Thu, 14 May 2009 15:47:39 +0530, Jerome Vuarand
> <jerome.vuarand@gmail.com> wrote:
>
>> If your functions are written in C, and you don't want to rebuild your
>> main program, you have to link these functions independently, in a
>> shared library. You can put them in a Lua C module, and load it at
>> runtime.
>
> Thanks Jerome Vuarand. I can make my C functions as shared libraries (dll or
> so). How can I make this as a Lua C module? and how can I load it at
> runtime? some hints, methods used would be very useful.

You can use either package.loadlib or require.

With loadlib, you would just have to put your lua_CFunction into a
shared library, then get it from Lua and call it. For example in foo.c
you would put:

int my_c_function(lua_State* L)
{
  const char* name = luaL_checkstring(L, 1);
  printf("Hello %s!\n", name);
  return 0;
}

and in Lua you would write:

local my_c_function = assert(package.loadlib("foo.so", "my_c_function"))
my_c_function("bob")

With require, there is an additionnal layer of code that you can place
in the share library that can do some initialization. A typical C
module looks like that (still in foo.c):

static int my_c_function(lua_State* L)
{
  const char* name = luaL_checkstring(L, 1);
  printf("Hello %s!\n", name);
  return 0;
}

static struct luaL_Reg my_c_functions[] = {
  {"my_c_function", my_c_function},
  {0, 0},
};

int luaopen_foo(lua_State* L)
{
  luaL_register(L, lua_tostring(L, 1), my_c_functions);
  return 0;
}

And in Lua you would write:

local foo = require 'foo'
foo.my_c_function("bob")

Require provide additionnal features over loadlib to locate the shared
library, and it works transparently with both Lua and compiled C
modules.