Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua's tostring() in C?

Tags:

lua

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.

like image 799
Niccolo M. Avatar asked Mar 23 '14 15:03

Niccolo M.


1 Answers

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.

like image 148
Seagull Avatar answered Sep 22 '22 11:09

Seagull