在C中调用Lua代码
这个程序从终端读入内容,而后按照lua块执行。
#include <stdio.h>
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
int main(){
char buff[1024];
int error;
memset(buff, 0, sizeof(buff));
lua_State *L = luaL_newstate(); // open lua
luaL_openlibs(L); // open the standard lib
while(fgets(buff, sizeof(buff), stdin) != NULL){
// if success, return 0
error = luaL_loadbuffer(L, buff, strlen(buff), "line") ||
lua_pcall(L, 0, 0, 0);
if(error){
fprintf(stderr, "%s", lua_tostring(L, -1));
lua_pop(L, 1); // pop the err msg from stack
}
}
lua_close(L);
return 0;
}
编译出现,致命错误: lua.h:没有那个文件或目录
locate lua.h,在对应的include目录下面的确没有相应的头文件,需要下载安装liblua5.2-dev,而后sudo updatedb;locate lua.h就会找到了。
/home/vonzhou/redis-2.6/deps/lua/doc/lua.html
/home/vonzhou/redis-2.6/deps/lua/etc/lua.hpp
/home/vonzhou/redis-2.6/deps/lua/src/lua.h
/usr/include/lua5.2/lua.h
/usr/include/lua5.2/lua.hpp
/usr/src/linux-headers-3.2.0-23-generic/include/config/scsi/dh/alua.h
在编译的时候制定路径,如-I /usr/include/lua5.2/ 或者在include的时候加全include <lua5.2/lua.h> 。此外,要显示的链接lua5.2的库。否则出现 undefined reference to `luaL_newstate'等其他错误。
Lua 的详细介绍:请点这里
Lua 的下载地址:请点这里