Juraj Blaho
Juraj Blaho

Reputation: 13461

Safely reading string from Lua stack

How is it possible to safely read string value from Lua stack? The functions lua_tostring and lua_tolstring both can raise a Lua error (longjmp / exception of a strange type). Therefore the functions should be called in protected mode using lua_pcall probably. But I am not able to find a nice solution how to do that and get the string value from Lua stack to C++. Is it really needed to call lua_tolstring in protected mode using lua_pcall?

Actually using lua_pcall seems bad, because the string I want to read from Lua stack is an error message stored by lua_pcall.

Upvotes: 5

Views: 7550

Answers (4)

vipygd
vipygd

Reputation: 78

Ok, When you call lua_pcall failed, it will return an error code. When you call lua_pcall successfully, you will get zero. So, first you should see the returned value by lua_pcall, then use the lua_type to get the type, at last, use the lua_to* functions the get the right value.

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);
            // ...
        }
}

It's all. Good luck.

Upvotes: 2

lhf
lhf

Reputation: 72312

Use lua_type before lua_tostring: If lua_type returns LUA_TSTRING, then you can safely call lua_tostring to get the string and no memory will be allocated.

lua_tostring only allocates memory when it needs to convert a number to a string.

Upvotes: 7

d33tah
d33tah

Reputation: 11561

Here's how it's done in OpenTibia servers:

std::string LuaState::popString()
{
    size_t len;
    const char* cstr = lua_tolstring(state, -1, &len);
    std::string str(cstr, len);
    pop();
    return str;
}

Source: https://github.com/opentibia/server/blob/master/src/lua_manager.cpp

Upvotes: 0

Zacrath
Zacrath

Reputation: 556

You can use the lua_isstring function to check if the value can be converted to a string without an error.

Upvotes: 0

Related Questions