您的位置:首页 > 运维架构 > Linux

linux下C调用lua的第一个程序

2015-08-24 00:07 716 查看

linux下C调用lua的第一个程序

linux的环境是Fedora 18,运行在VM workstation中,以开发模式安装,自带了lua 5.1.4,可以在命令行上直接用lua命令进入到lua环境中。
写第一个lua程序,C语言程序
//add.c
#include <stdio.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
/*the lua interpreter*/
lua_State* L;
int
luaadd(int x, int y)
{
int sum;
/*the function name*/
lua_getglobal(L,"add");
/*the first argument*/
lua_pushnumber(L, x);
/*the second argument*/
lua_pushnumber(L, y);
/*call the function with 2 arguments, return 1 result.*/
lua_call(L, 2, 1);
/*get the result.*/
sum = (int)lua_tonumber(L, -1);
/*cleanup the return*/
lua_pop(L,1);
return sum;
}
int
main(int argc, char *argv[])
{
int sum;
/*initialize Lua*/
L = lua_open();
/*load Lua base libraries*/
luaL_openlibs(L);
/*load the script*/
luaL_dofile(L, "add.lua");
/*call the add function*/
sum = luaadd(10, 15);
/*print the result*/
printf("The sum is %d \n",sum);
/*cleanup Lua*/
lua_close(L);
return 0;
}
lua的代码:
function add(x,y)
return x + y
end
使用GCC编译,告找不到文件lua.h!
需要手动安装lua
1、lua5.1.4需要使用readline,下载文件readline-6.2.tar.gz,使用命令:tar -zxvf readline-6.1.tar.gz 解包。
2、进入目录,生成make文件:./configure ,编译: make,安装: make install
3、原文说还需要ncurses,因为以前这个包装过,所以这次没有。
4、下载并解包文件lua-5.1.4.tar.gz:tar -xzvf lua-5.1.4.tar.gz
5、进入目录lua-5.1.4,编译:make linux,安装:make install
成功后将lua和lua.h文件都安装好了,但lua的安装位置和以前fedora自带的位置是不一样的,这次安装在了/usr/local/bin下了,不过不影响使用。
然后再次编译,试过不需要那么复杂的命令,实际上只需要:gcc -lm add.c -o add /usr/local/lib/liblua.a -ldl
还是给个全的命令吧:gcc -I/usr/local/include/ -L/usr/local/lib/ -lm add.c -o add /usr/local/lib/liblua.a -ldl
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: