Lua的使用入门之C/C++与lua函数的混合调用

来源:互联网 发布:端口范围 编辑:程序博客网 时间:2024/06/03 12:09

参考文章:http://www.oschina.net/code/snippet_243525_25045#41626

lua与c/c++遵循相应规范的条件下可以相互调用.

1.在c/c++中定义一个lua接口的函数:

//要在lua中调用的c函数

int l_hello(lua_State* pState)
{
cout<<"This is c function: l_hello"<<endl;
return 0;
}

// lua函数对应的lua中注册和调用的l_hello函数基址的别名
lua_register_t lua_cfunction_list[] = {
"hello", l_hello, // [1]
NULL // [2]
};

2.在c中编写l写到ua状态机的函数注册函数:

// 将c函数注册到lua状态机中
void register_functions(lua_State* L)
{
lua_register_t* p = lua_cfunction_list;
while (p->name) {
lua_pushcfunction(L, p->pfunc);// 将函数压栈->l_hello
lua_setglobal(L, p->name);//将函数名设为lua文件中调用c函数l_hello的函数别名
++p;
}
}

3.lua中编写调用c函数l_hello的函数:

main_lua.lua:

print("loading file: main_lua.lua...");
function MainEntry(...)
    print("this is MainEntry()");
hello();// 调用的c函数l_hello
for i,v in ipairs(arg) do
   print(i.."="..tostring(v));
end
end

4.在c中调用MainEntry:

lua_getglobal(L, "MainEntry");
if (lua_type(L, -1) == LUA_TFUNCTION)
{
for (int i = 0; i < argc; i++)
{
lua_pushstring(L, argv[i]);
}
lua_pcall(L, argc, 0, 0);// 调用lua函数

}

由此可见,lua/c混合调用就是c->lua->c,重要的逻辑判断函数在lua中编写,而调用lua函数的主体c代码主要是执行一些数据存取、检查设定等工作。


代码链接:

http://download.csdn.net/detail/yuanmushen/6646875