lua-users home
lua-l archive

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


On Wed, Apr 25, 2007 at 01:07:02AM -0400, Jérôme VUARAND wrote:
> I'm writing a binary module, and I'd like it to integrate gracefully
> into the module system. So I tried to call the "module" Lua function
> from my luaopen_module C function. I used the code below. I first call
> "module" with the module name and package.seeall as parameters, and
> then I put my functions in LUA_ENVIRONINDEX (which module is supposed
> to have replaced with the module table).
> 
> Unfortunately, it doesn't seem to work. After loading the module,
> module.new is nil. So is "module" supposed to work for C modules, and
> if so how can I use it ?

It should work fine with C modules. This worked for me:

#include <lua.h>
#include <lauxlib.h>

static int lua__new (lua_State *L) {
  lua_pushstring(L, "it works!");
  return 1;
}

static const struct luaL_reg module_functions[] = {
  {"new", lua__new},
  {NULL, NULL}
};

int luaopen_lmodule(lua_State *L)
{
   lua_getglobal(L, "module");
   lua_pushvalue(L, 1);
   lua_getglobal(L, "package");
   lua_getfield(L, -1, "seeall");
   lua_replace(L, -2);
   lua_call(L, 2, 0);
   lua_pushvalue(L, LUA_ENVIRONINDEX);
   luaL_register(L, NULL, module_functions);
   return 0;
}


$ lua
Lua 5.1.1  Copyright (C) 1994-2006 Lua.org, PUC-Rio
> require"lmodule"
> = package.loaded.lmodule
table: 0x3078e0
> table.foreach(lmodule, print)
new     function: 0x307570
_M      table: 0x3078e0
_NAME   lmodule
_PACKAGE
> = lmodule.new()
it works!

Cheers,
Luis.

-- 
A mathematician is a device for turning coffee into theorems.
        -- P. Erdos 

-- 
Luis Carvalho
Applied Math PhD Student - Brown University
PGP Key: E820854A <carvalho@dam.brown.edu>