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!

参考博文http://blog.csdn.net/emili/article/details/6005713需要手动安装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

 

参考文献:1、http://blog.csdn.net/emili/article/details/6005713

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值