Niccolo M.
Niccolo M.

Reputation: 3413

Lua's tostring() in C?

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

Answers (1)

Seagull
Seagull

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 not NULL, the function also sets *len with the string length.

If the value has a metatable with a "__tostring" field, then luaL_tolstring calls the corresponding metamethod with the value as argument, and uses the result of the call as its result.

Upvotes: 4

Related Questions