Loading a C Module in Lua
I am trying to load the example lproc program (described on Programming Lua, Chapter 30) into Lua and fouling up somehow. I am following this - http://www.lua.org/pil/26.2.html to get my c module into lua. Following are the steps that I've taken:
I have an lproc.h and lproc.c (containing exactly the functions laid out in Chapter 30 of the book). I am compiling lproc.c as --- gcc -c lproc.c -DLUA-USERCONFIG=\"lproc.h\"
I made a library out of lproc.o, named the same.
And then compiled lua.c as instructed. My header files contain the macro LUA_EXTRALIBS and the method declarations.
Went to the Lua interpreter and it gave the following errors:
> require "lproc" stdin:1: module 'lproc' not found: no field package.preload['lproc'] no file './lproc.lua' no file '/opt/local/share/lua/5.1/lproc.lua' no file '/opt/local/share/lua/5.1/lproc/init.lua' no file '/opt/local/lib/lua/5.1/lproc.lua' no file '/opt/local/lib/lua/5.1/lproc/init.lua' no file './lproc.so' no file '/opt/local/lib/lua/5.1/lproc.so' no file '/opt/local/开发者_StackOverflow中文版lib/lua/5.1/loadall.so' stack traceback: [C]: in function 'require' stdin:1: in main chunk [C]: ?
It seems that the module did not get registered, what would I need to do from Lua? Time is short and I am doing something horrendously wrong, any direction would be welcome.
Thanks,
SayanHere is a complete and fully portable minimal example of building a C library for Lua (works in Lua 5.1-5.3 and LuaJIT, for any platform):
With this example.c
:
#include <lua.h>
int example_hello(lua_State* L) {
lua_pushliteral(L, "Hello, world!");
return 1;
}
int luaopen_example(lua_State* L) {
lua_newtable(L);
lua_pushcfunction(L, example_hello);
lua_setfield(L, -2, "hello");
return 1;
}
Put this rockspec file in the same directory, named example-1.0-1.rockspec
:
package = "example"
version = "1.0-1"
source = {
url = "." -- not online yet!
}
build = {
type = "builtin",
modules = {
example = "example.c"
}
}
Then, run luarocks make
. It will build the C code with the correct flags for your platform.
Your module is now ready to use!
Lua 5.3.3 Copyright (C) 1994-2016 Lua.org, PUC-Rio
> example = require("example")
> print(example.hello())
Hello, world!
>
The easiest way is to create a shared library and load your C module dynamically. This way avoids having to rebuild the Lua interpreter. There are several examples in http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/ and explanations in http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/install.html and http://lua-users.org/wiki/BuildingModules
精彩评论