lua-users home
lua-l archive

Correct way to write C/Lua mixed module

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


Hi All,
I'm writing a module which has mixed native C functions and Lua code. My goal is to have it available by only requiring it. My DLL exports only one function:
------------------------------8<------------------------------
extern "C"
{
 LUAMOD_API int luaopen_task( lua_State* L )
 {
 static const luaL_Reg statics[] =
 {
 { "getCurrentTimeMillis", module_getCurrentTimeMillis },
 { NULL, NULL }
 };
 // Register C functions.
 luaL_newlib( L, statics ); // table
 // Register Lua functions.
 if ( luaL_loadstring( L, s_LuaCode ) != LUA_OK ) // table function
 {
 fprintf( stderr, "%s\n", lua_tostring( L, -1 ) );
 return 0;
 }
 if ( lua_pcall( L, 0, 1, 0 ) != LUA_OK ) // table function
 {
 fprintf( stderr, "%s\n", lua_tostring( L, -1 ) );
 return 0;
 }
 lua_pushvalue( L, -2 ); // table function table@1
 if ( lua_pcall( L, 1, 0, 0 ) != LUA_OK ) // table
 {
 fprintf( stderr, "%s\n", lua_tostring( L, -1 ) );
 return 0;
 }
 return 1;
 }
}
------------------------------8<------------------------------
s_LuaCode is a C array generated with the following source code
------------------------------8<------------------------------
local function doSomething()
 -- ...
end
return function( module )
 module.doSomething = doSomething
end
------------------------------8<------------------------------
The Lua code returns a function which receives a table where the module functions are to be registered, and this function is called as part of luaopen_task.
Questions:
1. Is there a better way to handle a C/Lua mixed module? I don't need anything fancy, just register Lua and C functions.
2. Can/should I call lua_error in luaopen_task if one of the functions I call fails?
Thanks in advance,
Andre

AltStyle によって変換されたページ (->オリジナル) /