Is there a Lua API function equivalent to tostring(), or do I have to do the following in my C code?
lua_getglobal(L, "tostring");
// ... push value to convert, and:
lua_call(L, 1, 1);
The long story:
I'm writing an alert(message)
function in C (callable from Lua) that would show a message to the user. But if message
isn't a string (e.g., a boolean or a nil), I want to convert it to something sane. There's a Lua function to do this, tostring()
, but I was wondering if Lua's C API provides a "direct" way to do this.
Use luaL_tolstring
From reference:
[-0, +1, e]
const char *luaL_tolstring (lua_State *L, int idx, size_t *len);
Converts any Lua value at the given index to a C string in a reasonable format. The resulting string is pushed onto the stack and also returned by the function. If
len
is notNULL
, the function also sets*len
with the string length.If the value has a metatable with a "
__tostring
" field, thenluaL_tolstring
calls the corresponding metamethod with the value as argument, and uses the result of the call as its result.
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