2

I am using the answer to this question to redirect lua's print to a stringstream. My function code is below.

My issue is that the code doesn't always match what lua would have printed on it's own. Most notably, when I attempt to print a function, I just get the function, rather than the function and address. Example:

> --in lua
> print(os.exit)
function: 0xabcdef01

> --in my interpreter
> print(os.exit)
function

The obvious solution is to force my custom print function to call lua's tostring prior to writing to luaout (like the default print does). However, I can't really figure out how to make this work. If anyone can help me out, I'd appreciate it a lot.

Here's my custom print:

static int l_my_print(lua_State* L) {
    int nargs = lua_gettop(L);

    for (int i=1; i <= nargs; i++) {
        int t = lua_type(L, i);
        switch (t) {
            case LUA_TSTRING: { /* strings */
                luaout << lua_tostring(L, i);
                break;
            }
            case LUA_TBOOLEAN: { /* booleans */
                luaout << (lua_toboolean(L, i) ? "true" : "false");
                break;
            }
            case LUA_TNUMBER: { /* numbers */
                luaout << lua_tonumber(L, i);
                break;
            }
            default: { /* other values */
                luaout << lua_typename(L, t);
                break;
            }
        }
        if (i!=nargs){
            luaout << "\t";
        }
    }
    luaout << endl;

    return 0;
}
Community
  • 1
  • 1
ewok
  • 20,148
  • 51
  • 149
  • 254

1 Answers1

4

You can try on default this:

lua_pushfstring(L, "%s: %p", luaL_typename(L, i), lua_topointer(L, i));

or

 luaout << luaL_typename(L, i) << ": " << lua_topointer(L, i);

This will add the name of the function and the pointer.

You can call lua function from C++ (don't guarantee to work as I have not tested it, but it should aside from grammatical errors)

lua_getglobal(L, "tostring");
lua_pushvalue (L, i);

if (lua_pcall(L, 1, 1, 0) != 0) {
        printf("error running function `%s': %s\n", "tostring", lua_tostring(L, -1));
        return -1;
}
// get result
char *result = luaL_checkstring (L, -1);
tozka
  • 3,211
  • 19
  • 23
  • this is partially helpful, as it will behave the expected way for things like functions, but the ideal solution is to simply output the result of the tostring function. What I need to do is force lua to call tostring and then push the resultant string to the stack, rather than pushing the object itself – ewok Oct 08 '12 at 13:28
  • one note: in line 2, `t` should be `i`. Other than that, it works great. Thanks! – ewok Oct 08 '12 at 13:49