安全地从Lua堆栈中读取字符串

Safely reading string from Lua stack

本文关键字:读取 字符串 堆栈 Lua 安全      更新时间:2023-10-16

如何安全地从Lua堆栈读取字符串值?函数lua_tostringlua_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