我正在使用 this question 的答案将 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': %s\n", "tostring", lua_tostring(L, -1));
return -1;
}
// get result
char *result = luaL_checkstring (L, -1);
关于c++ - 使用默认打印行为在 C++ 中重新路由 Lua 打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12782580/