Reputation: 3413
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.
Upvotes: 6
Views: 3348
Reputation: 13859
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.
Upvotes: 4