从 Lua 获取值 |
|
问题: 如何从 C 端获取由 lua_dostring
执行的 Lua 代码块的返回值,例如获取 Lua dostring 函数返回的结果?
(lhf) 与任何函数的返回值一样。以下是一个示例
lua_State *L=lua_open(0); printf( "%d\n", lua_gettop(L) ); lua_dostring(L, "return 1,'a'" ); printf( "%d\n", lua_gettop(L) ); printf( "%s\n", lua_tostring(L,-2) ); printf( "%s\n", lua_tostring(L,-1) );
lua_dostring
之前 lua_gettop(L)
与调用它之后 lua_gettop(L)
之间的差值,即从 -1 到 -k 的索引。
returnone.c
#include <lua.h> #include <lualib.h> int main() { lua_State *L=lua_open(); printf( "%d\n", lua_gettop(L) ); lua_dostring(L, "return 1,'a'" ); printf( "%d\n", lua_gettop(L) ); printf( "%s\n", lua_tostring(L,-2) ); printf( "%s\n", lua_tostring(L,-1) ); return 0; }
构建
gcc -o returnone returnone.c -I/usr/include/lua50 -llua50 -llualib50
运行:# ./returnone
0 2 1 a
lua_dostring()
不再存在
returnone.c
#include <lua.h> #include <lualib.h> #include <lauxlib.h> int main() { lua_State *L = luaL_newstate(); char buff[] = "return 1,'a'"; int error; printf( "%d\n", lua_gettop(L) ); error = luaL_loadbuffer(L, buff, strlen(buff), "my test") || lua_pcall(L, 0, LUA_MULTRET, 0); if (error) { fprintf(stderr, "%s", lua_tostring(L, -1)); lua_pop(L, 1); /* pop error message from the stack */ } printf( "%d\n", lua_gettop(L) ); printf( "%s\n", lua_tostring(L,-2) ); printf( "%s\n", lua_tostring(L,-1) ); return 0; }