Lua编程示例(六): C语言调用Lua函数
程序员文章站
2022-03-07 10:36:42
c++端:
#include "stdafx.h"
lua_state *l;
void load_lua(lua_state **l,char *fil...
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
下一篇: Python取整数