linux c程序调用lua代码的实例
2015-09-22 17:09
711 查看
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)
编译:[fulinux@ubuntu ccalllua]$ gcc add.c -llua5.1
运行:
[fulinux@ubuntu ccalllua]$ ./a.out
The sum is 25
代码所在位置:https://git.oschina.net/fulinux/lua
#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
相关文章推荐
- Linux-CentOS7 安装VMware Workstation 12
- Linux线程同步之读写锁(rwlock)
- 第十二节 Linux下软件安装
- linux 禁止帐号密码验证 使用key验证方式登录SSH
- centos安装c编译库
- Linux进程同步之记录锁(fcntl)
- centos7.0体验与之前版本的不同
- 【Linux】VMware中Redhat9下安装VMTools
- 更改CentOS 6.5 yum源
- linux应用编程笔记(1)gdb调试方法及如何找出dbg.c程序中的错误
- linux中对文件名包含空格时处理异常的解决方法
- CentOS7下安装配置vncserver
- Unix/Linux压缩命令 bzip/bzip2/zip/compress/dd/cpio/
- Windows 下安装 Linux Ubuntu 系统注意事项
- 一些容易被忽视的linux命令(二)
- VirtualBox中安装CentOS使得在ssh和外网都能正常链接
- Centos破解Root密码的两种方法
- Linux的chattr与lsattr命令详解
- Ubuntu server 14.04.3 subversion 搭建
- linux服务器病毒