C调用LUA 函数的有关问题
C调用LUA 函数的问题
C调用LUA 函数,LUA 函数返回一个数组,C 怎么接收这个数组。下面C代码编译的运行结果是:
attempt to call a nil value
27
新手,刚刚解除LUA ,还请指点
C函数为:
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
size_t len;
lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaL_loadfile(L, "./getRinging.lua"); //加载LUA脚本
//lua_pcall(L,0,0,0); //第一次 lua_pcall 只会将LUA 脚本的内容加入到L 中,而不会执行脚本内容
lua_getglobal(L,"getRinging");
lua_pcall(L,0,0,0);
printf("%s \n",(int)lua_tolstring(L,-1,&len));
printf("%d \n",len);
lua_pop(L,1);
lua_close(L);
return 1;
}
LUA脚本代码为:
#!/bin/lua
http = require "socket.http"
cjson = require "cjson"
local URL = "http://3rd.ximalaya.com/explore/tracks?i_am=test20141119&category_id=2&tag=%E5%8F%A4%E5%85%B8&condition=daily&page=1&per_page=20&uni=xxx"
function getRinging()
local resjson = http.request(URL);
local res = cjson.decode(resjson);
list={}
for i=1,20,1 do
list[2*i - 1] = res["tracks"][i]["title"]
list[2*i] = res["tracks"][i]["play_url_32"]
end
return list
--return URL
end;
------解决思路----------------------
example code here:
C调用LUA 函数,LUA 函数返回一个数组,C 怎么接收这个数组。下面C代码编译的运行结果是:
attempt to call a nil value
27
新手,刚刚解除LUA ,还请指点
C函数为:
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
size_t len;
lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaL_loadfile(L, "./getRinging.lua"); //加载LUA脚本
//lua_pcall(L,0,0,0); //第一次 lua_pcall 只会将LUA 脚本的内容加入到L 中,而不会执行脚本内容
lua_getglobal(L,"getRinging");
lua_pcall(L,0,0,0);
printf("%s \n",(int)lua_tolstring(L,-1,&len));
printf("%d \n",len);
lua_pop(L,1);
lua_close(L);
return 1;
}
LUA脚本代码为:
#!/bin/lua
http = require "socket.http"
cjson = require "cjson"
local URL = "http://3rd.ximalaya.com/explore/tracks?i_am=test20141119&category_id=2&tag=%E5%8F%A4%E5%85%B8&condition=daily&page=1&per_page=20&uni=xxx"
function getRinging()
local resjson = http.request(URL);
local res = cjson.decode(resjson);
list={}
for i=1,20,1 do
list[2*i - 1] = res["tracks"][i]["title"]
list[2*i] = res["tracks"][i]["play_url_32"]
end
return list
--return URL
end;
------解决思路----------------------
example code here:
lua_pcall(L, 0, 1, 0); // TODO: check the return value, should be LUA_OK
if (lua_istable(L, -1)) {
// stack(L): result_table [TOP]
int index = lua_absindex(L, -1);
lua_pushnil(L); // stack(L): result_table, nil [TOP]
while (lua_next(L, index)) {
// stack(L): result_table, key, value [TOP]
int l;
const char *s = lua_tolstring(L, -1, &l);
printf("%s (len=%d)\n", s, l);
lua_pop(L, 1); // stack(L): result_table, key [TOP]
}
// stack(L): result_table [TOP]
}