Lua 5.3.3 在C语言中保存Lua中的函数 并调用它
2016-11-19 13:45
441 查看
/***************************************************C++ main.cpp**************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "lua.hpp"
using namespace std;
int FOO = LUA_REFNIL;
int dosomething(lua_State *L)
{
cout << "insid c code" << endl;
FOO = luaL_ref(L, LUA_REGISTRYINDEX);//将从Lua脚本中传入的Lua函数保存起来
return 0;
}
int main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_register(L, "dosomething", dosomething);//给Lua中注册一个c函数
if (0 != luaL_dofile(L, "main.lua")) //加载lua代码
{
cout << lua_tostring(L, -1) << endl;
}
lua_rawgeti(L, LUA_REGISTRYINDEX, FOO);//将保存的Lua函数FOO放在栈顶
if (lua_isfunction(L, -1))
{
lua_pcall(L, 0, 0, 0);//执行Lua函数
}
return 0;
}
--Lua 代码
function foo() //foo Lua函数 在c中要被保存和调用的那一个
print("foo")
end
dosomething(foo) //执行c代码 将Lua函数foo作为参数传进入
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "lua.hpp"
using namespace std;
int FOO = LUA_REFNIL;
int dosomething(lua_State *L)
{
cout << "insid c code" << endl;
FOO = luaL_ref(L, LUA_REGISTRYINDEX);//将从Lua脚本中传入的Lua函数保存起来
return 0;
}
int main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_register(L, "dosomething", dosomething);//给Lua中注册一个c函数
if (0 != luaL_dofile(L, "main.lua")) //加载lua代码
{
cout << lua_tostring(L, -1) << endl;
}
lua_rawgeti(L, LUA_REGISTRYINDEX, FOO);//将保存的Lua函数FOO放在栈顶
if (lua_isfunction(L, -1))
{
lua_pcall(L, 0, 0, 0);//执行Lua函数
}
return 0;
}
--Lua 代码
function foo() //foo Lua函数 在c中要被保存和调用的那一个
print("foo")
end
dosomething(foo) //执行c代码 将Lua函数foo作为参数传进入
相关文章推荐
- C语言调用Lua函数
- C语言中调用Lua函数实例
- C语言调用Lua函数
- C++保存和调用lua函数
- C语言调用Lua函数
- Lua教程(四):在Lua中调用C语言、C++的函数
- Lua教程(四):在Lua中调用C语言、C++的函数
- Lua 调用的 C 函数保存 state 的两种方式: Storing State in C Functions 笔记
- c语言里面的调用显示系统时间的函数及实现过程是什么
- C语言(函数)调用过程(略译)
- 关于C语言中函数调用和参数传递机制的探讨(ZZ)
- 函数调用(C语言)
- C/C++中调用LUA函数
- 关于C语言中函数调用和参数传递机制的探讨
- C语言基本功教程系列(3) - 快速的函数调用
- c++调用lua函数
- 调用Lua函数
- 通过例子学习Lua(4)--函数的调用
- C语言中函数调用与返回值的关系是什么
- VC6.0配置LUA编译环境及LUA调用C++函数的简单示例