博客首页 注册 建议与交流 排行榜 加入友情链接
推荐 投诉 搜索: 帮助

苦丁茶

tomcent.cublog.cn
Linux下Lua调用c函数(2)
lua第二种调用C函数的方法:
 
luadd.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_tointeger(L, -1);
    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);

    /* pause */
    printf( "Press enter to exit..." );
    getchar();

    return 0;
}

 

add.lua 文件:

 

-- add two numbers

function add ( x, y )
    return x + y
end

 

编译:

    注意:liblua.so 一定要放到存在/usr/lib 或/lib目录下面
         (Lua官网可能提供的是liblua.5.1.so 可以cp多一个liblua.so)

#gcc luaadd.c -llua -ldl -o luaadd

 

发表于: 2008-01-07,修改于: 2008-01-07 11:14,已浏览240次,有评论0条 推荐 投诉

给我留言
版权所有 ChinaUnix.net 页面生成时间:0.01586