Safely reading string from Lua stack
如何安全地从Lua堆栈中读取字符串值?函数
实际上使用
在
好吧,当您调用lua_pcall失败时,它将返回一个错误代码。成功调用lua_pcall时,您将获得零。因此,首先应该通过lua_pcall查看返回的值,然后使用lua_type获取类型,最后使用lua_to *函数获取正确的值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | int iRet = lua_pcall(L, 0, 0, 0); if (iRet) { const char *pErrorMsg = lua_tostring(L, -1); // error message cout<<pErrorMsg<<endl; lua_close(L); return 0; } int iType = lua_type(L, -1); switch (iType) { //... case LUA_TSTRING: { const char *pValue = lua_tostring(L, -1); // ... } } |
全部。
祝你好运。
这是在OpenTibia服务器中完成的方式:
1 2 3 4 5 6 7 8 | std::string LuaState::popString() { size_t len; const char* cstr = lua_tolstring(state, -1, &len); std::string str(cstr, len); pop(); return str; } |
来源:https://github.com/opentibia/server/blob/master/src/lua_manager.cpp
您可以使用