lua-users home
lua-l archive

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


I would be very grateful if anyone might advise how I can build a library of C functions so that I can call them from a lua script.  I have searched and tried many different solutions but regret I cannot succeed.
 
I am using Lua5.1 in Linux.  I wish to create a wrapper to a library of C functions.  I have created a trial script.
I receive an error advisory when the 'standalone' lua script is run as follows:
attempt to call global 'prin' (a nil value)
 
My C code (mylib.c) and lua script (myrawlib.lua) is detailed below:
Thank you very much for your time.
C
 
C code starts
 
#include <stdio.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
 
// compile as:
// gcc mylib.c -shared -L/usr/local/lua5.1/lib -I/usr/local/lua5.1/include
// -llua -llualib -lm -ldl -o mylib.so
 
/* the Lua interpreter */
//lua_State *L;
//luaL_openlibs(L);
 
/*Internal function prototype */
static int l_prin (lua_State *L);
 
/* bespoke test function */
int l_prin (lua_State *L){
/* get index of arguments */
int i = luaL_checknumber(L, 1);
printf ("%d\n", i+1);
/* push the number back to satck but increased by 1 */
lua_pushnumber(L, i+1);
/* return the number of results */
return 1;
}
 
/* the array mylib */
static const struct luaL_reg mylib[] = {
{"prin", l_prin},
{NULL, NULL}
};
 
/* open library through registration process to open all functions re NULL */
LUALIB_API int luaopen_mylib (lua_State *L){
lua_newtable(L);
luaL_register(L, NULL, mylib);
return 1;
}
 
C code ends
 
Lua script starts
 
#!/usr/bin/env lua
--needs path in front of library and must explicitly state filename.so
--local p=package.loadlib("./mylib.so","prin")
local p=package.loadlib("./mylib.so","luaopen_mylib")
print(p)
print "\nHello World\n"
-- call a C function and send a number
local indicator = prin(1)
print("The result is ", indicator)
 
Lua script ends

__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com