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
.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With