linux c程序调用lua代码的实例

本文介绍如何使用C语言与Lua脚本进行交互,通过编写一个简单的C函数来调用Lua中预定义的加法函数,实现两个整数的相加并打印结果。同时展示了编译和运行过程,以及最终输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C代码(add.c):

#include <stdio.h>
#include <string.h>

#include <lua5.1/lua.h>
#include <lua5.1/lualib.h>
#include <lua5.1/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;
} /* -----End of main()----- */


lua代码(add.lua)
#!/usr/bin/lua

function add(...)
    local s = 0
    for i, v in ipairs{...} do
        s = s + v
    end
    return s
end

编译:

[fulinux@ubuntu ccalllua]$ gcc add.c -llua5.1


运行:

[fulinux@ubuntu ccalllua]$ ./a.out 
The sum is 25


代码所在位置:https://git.oschina.net/fulinux/lua


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fulinux

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值