欢迎来到代码驿站!

当前位置:首页 >

Lua编程示例(六): C语言调用Lua函数

时间:2021-05-09 07:44:32|栏目:|点击:

C++端:

#include "stdafx.h"

lua_State *L;
void load_lua(lua_State **L,char *filename){
 *L=luaL_newstate();
 luaL_openlibs(*L);
 if(luaL_loadfile(*L,filename) || lua_pcall(*L,0,0,0)){
 luaL_error(*L,"load file error! %s",lua_tostring(*L,-1));
 }
}
int _tmain(int argc, _TCHAR* argv[])
{
 load_lua(&L,"raw.lua"); //此处若直接传入L会出错
 lua_getglobal(L,"gettable");
 if(lua_pcall(L,0,1,0) !=0){
 luaL_error(L,"pcall wrong %s",lua_tostring(L,-1));
 }
 luaL_checktype(L,1,LUA_TTABLE);
 int n=lua_objlen(L,1);
 printf("n = %d\n",n);
 lua_pushstring(L,"ee");
 lua_rawseti(L,1,5); //t[n]=v,n为第三个参数,v是栈顶元素
 n=lua_objlen(L,1);
 printf("n = %d\n",n);
 int i;
 for(i=1;i<=n;i++){
 lua_rawgeti(L,1,i);
 printf("%s\n",lua_tostring(L,-1));
 }
 return 0;
}

lua脚本:

 

function gettable() 
  tb={ "aa","bb","cc","dd"} 
  return tb 
end 

运行输出的结果为:

n = 4 
n = 5 
aa 
bb 
cc 
dd 
ee

上一篇:Webpack基础教程之名词解释

栏    目:

下一篇:docker 容器上编译 go 程序提示找不到文件问题

本文标题:Lua编程示例(六): C语言调用Lua函数

本文地址:http://www.codeinn.net/misctech/117857.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有