安全地从Lua堆栈中读取字符串
Safely reading string from Lua stack
如何安全地从Lua堆栈读取字符串值?函数lua_tostring
和lua_tolstring
都可能引发Lua错误(奇怪类型的longjmp/异常)。因此,可能需要使用lua_pcall
在保护模式下调用函数。但我不能找到一个很好的解决方案,如何做到这一点,并获得字符串值从Lua堆栈到c++。真的需要使用lua_pcall
在保护模式下调用lua_tolstring
吗?
实际上使用lua_pcall
似乎很糟糕,因为我想从Lua堆栈中读取的字符串是lua_pcall
存储的错误消息。
在lua_tostring
之前使用lua_type
:如果lua_type
返回LUA_TSTRING
,那么您可以安全地调用lua_tostring
来获取字符串,并且不会分配内存。
lua_tostring
只在需要将数字转换为字符串时分配内存
Ok,当调用lua_pcall失败时,它将返回一个错误代码。当您成功调用lua_pcall时,您将获得零。因此,首先您应该看到lua_pcall的返回值,然后使用lua_type获取类型,最后使用lua_to*函数获取正确的值。
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);
// ...
}
}
所有。好运。
您可以使用lua_isstring
函数检查值是否可以转换为字符串而不会出现错误
在OpenTibia服务器上是这样做的:
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
相关文章:
- 如何使用Luacneneneba API正确读取字符串和表参数
- 如何从二进制文件中读取字符串
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 读取字符串文本输入以创建 2D 矢量
- 罗马数字到阿拉伯语 (vinculum) - 读取字符串中的字符
- C++:从文件中读取字符串和整数,并获得最大数字
- C++,从文件中读取字符串,分段错误
- 如果语句错误地读取字符串,则始终在第一个条件返回
- 如何从内存中读取字符串?
- 如何创建一个C++程序来读取字符串数组中的信息,然后将其排序到类中?
- 我需要C++读取字符串数组中每个单词的第一个字母
- 读取字符串C++的字符时出错
- 读取字符串直到标志 (C++)
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++输入文件流无法从文件中读取字符串
- 读取字符串字符时出错
- 如何读取<字符串,矢量<对<int,字符串的映射>>>
- 如何使此函数使用 getline 读取字符串并使用 int 执行相同的行为?
- C++ 使用 Strtok 读取字符串字符时出错
- 使用 getline 读取字符串,但每行中都有换行符