关于C#:从Lua堆栈安全读取字符串

Safely reading string from Lua stack

如何安全地从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仅在需要将数字转换为字符串时才分配内存。


好吧,当您调用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


您可以使用lua_isstring函数检查是否可以将值转换为没有错误的字符串。