Lua编程示例(六): C语言调用Lua函数
C++端:
#include"stdafx.h" lua_State*L; voidload_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,"loadfileerror!%s",lua_tostring(*L,-1)); } } int_tmain(intargc,_TCHAR*argv[]) { load_lua(&L,"raw.lua");//此处若直接传入L会出错 lua_getglobal(L,"gettable"); if(lua_pcall(L,0,1,0)!=0){ luaL_error(L,"pcallwrong%s",lua_tostring(L,-1)); } luaL_checktype(L,1,LUA_TTABLE); intn=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); inti; for(i=1;i<=n;i++){ lua_rawgeti(L,1,i); printf("%s\n",lua_tostring(L,-1)); } return0; }
lua脚本:
functiongettable() tb={"aa","bb","cc","dd"} returntb end
运行输出的结果为:
n=4 n=5 aa bb cc dd ee