使用默认打印行为在C++中重新路由Lua打印

Rerouting Lua print in C++ with default print behavior

本文关键字:打印 新路由 路由 Lua C++ 默认      更新时间:2023-10-16

我使用这个问题的答案将lua的print重定向到字符串流。我的函数代码如下。

我的问题是,代码并不总是与lua自己打印的内容相匹配。最值得注意的是,当我尝试打印函数时,我只得到函数,而不是函数和地址。示例:

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

显而易见的解决方案是强制我的自定义打印函数在写入luaout之前调用lua的tostring(就像默认打印一样)。然而,我真的不知道该怎么做。如果有人能帮我,我将不胜感激。

这是我的自定义打印:

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;
}

您可以在默认情况下尝试以下操作:

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

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

这将添加函数的名称和指针。

你可以从C++中调用lua函数(不保证能工作,因为我还没有测试过它,但除了语法错误之外,它应该能工作)

lua_getglobal(L, "tostring");
lua_pushvalue (L, i);
if (lua_pcall(L, 1, 1, 0) != 0) {
printf("error running function `%s': %sn", "tostring", lua_tostring(L, -1));
return -1;
}
// get result
char *result = luaL_checkstring (L, -1);