sol2
sol2 copied to clipboard
C++ equivalent of Lua `tonumber(obj)` and `tostring(obj)`
I would have a use for the equivalent of tostring in C++ code that doesn't just work on usertypes, but on builtin types, too. Rather than going through Lua, wouldn't it be nice to have this provided automatically, for example as member functions of sol::object? By analogy, the Lua function tonumber would qualify, too. The desired semantics would be as close to the Lua function of the same name as practical, except that the return types wouldn't be sol::object, but the C++ types directly, for example std::string.
Or is this feature already there, and I missed it?
I have seen #1005, but it seems that issue is only about usertypes.
You can already do this using the lua C api and the function luaL_tolstring (see here). I don't believe sol has a utility function to call this, but you can probably do something like this:
std::string sol_object_to_string(const sol::state& lua, const sol::object& object)
{
std::string result_str;
// Push the object to the stack and get its string representation.
object.push();
size_t lua_str_len;
const char* lua_str = luaL_tolstring(lua, -1, &lua_str_len);
// If the call was successful make an std::string out of it and pop from the stack.
if (lua_str)
{
result_str = std::string(lua_str, lua_str_len);
lua_pop(lua, 1);
}
object.pop();
return result_str;
}