C/C++ 调用 Lua 函数(非全局函数)
来源:互联网 发布:临淄广电网络客服电话 编辑:程序博客网 时间:2024/04/28 11:40
C/C++ 调用 Lua 函数有两种:
1, Lua 脚本里,没有local 修饰的函数,即为全局函数
2, Lua 脚本里,有local 修饰的函数,即为局部函数
其实调用函数和取Lua里的变量是一样的,网上讲得最多的是调用全局函数,这里主要讲调用非全局函数(或是变量)。
如有脚本: test.lua
--定义了一个全局表COM = {}
--定义了一个局部函数
local function add(a, b)
print("a = "..a);
print("b = "..b);
return a + b;
end
COM =
{
width = 2550,
myAdd = add,
}
有c文件: main.c
#include <stdio.h>
#include <stdlib.h>
#include "lauxlib.h"
#include "lua.h"
#include "lualib.h"
int main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
if(luaL_loadfile(L, "test.lua"))
{
printf("load file: hello.lua faild...\n");
lua_close(L);
return 1;
}
lua_pcall(L, 0, 0, 0); /* 前面这几步都基本固定 */
lua_getglobal(L, "COM"); /* 先找到表 */
if(lua_type(L, -1) != LUA_TTABLE)
{
printf("can not find table: COM \n");
lua_close(L);
return 1;
}
lua_pushstring(L, "myAdd"); /* 要找的函数名入栈 */
lua_gettable(L, -2);
if(lua_type(L, -1) != LUA_TFUNCTION) /* 找到的是否是函数 */
{
printf("find myAdd is not a function.\n");
lua_close(L);
return 1;
}
lua_pushnumber(L, 111);
lua_pushnumber(L, 222);
lua_pcall(L, 2, 1, 0); /* 传参, 执行 */
printf("call lua function add() and result: %d\n", (int)lua_tonumber(L, -1));
lua_close(L);
return 0;
}
执行结果
[root@localhost lua_call_c]# ./a.out
a = 111
b = 222
call lua function add() and result: 333
系统:CentOS 6.5
内核: Linux 2.6.32-431.el6.i686
gcc : gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-4)
- C/C++ 调用 Lua 函数(非全局函数)
- C/C++ 调用 Lua 函数(非全局函数)
- Lua调用C函数
- lua 调用c函数
- Lua调用C函数
- lua调用c函数
- Lua调用C函数
- lua调用C函数
- lua调用C函数
- lua调用C函数
- Lua调用C函数
- lua调用c函数
- lua调用C函数
- lua调用C函数
- Lua调用C函数
- lua 调用c函数
- Lua调用C函数
- Lua调用C函数
- git
- 程序调试中的常见问题及解决方法
- OpenCV2编程手册笔记之 4.5反投影直方图以检测特定图像内容
- Java 加解密技术系列之 BASE64
- Servlet是线程安全的吗?
- C/C++ 调用 Lua 函数(非全局函数)
- 百度富文本ueditor使用 以及 与 Struts2 整合时出现的问题解决
- 存储过程中使用事务与try catch
- Java 加解密技术系列之 MD5
- 网站或者软件开发流程是什么样子呢?
- atitit 板块分类 上市公司 龙头企业公司 列表 attilax总结.docx
- matlab invalid mex-file caffe_.mexw64
- 算法学习:二叉树的列表实现
- Lua 脚本调用 C 函数