Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely reading string from Lua stack

Tags:

c++

lua

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.

like image 696
Juraj Blaho Avatar asked Mar 21 '13 09:03

Juraj Blaho


2 Answers

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.

like image 135
lhf Avatar answered Nov 11 '22 06:11

lhf


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.

like image 32
vipygd Avatar answered Nov 11 '22 05:11

vipygd