使用默认打印行为在C++中重新路由Lua打印
Rerouting Lua print in C++ with default print behavior
我使用这个问题的答案将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);
相关文章:
- Printf 命令不打印时添加了查找常见除数的新代码
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- (C++) 使用诅咒打印从文件中读入的新行
- 为什么当测试用例数为 1 时,我的程序不输入而是打印新行?
- 如何按姓氏排序并打印新数组
- 为什么在编辑 fastq 文件并将输出写入新的 fastq 文件时引入不可打印字符?
- C ++有趣的语法,用于在std::cout中打印新行
- 从文本文件打印后如何摆脱新线条,并在打印时摆脱结局空间
- 为什么打印新的int[]会给我一个C ++的地址
- 递归功能,以打印每个新位置以进行控制
- 在C++使用新方法打印2d阵列
- 仅在向量末尾打印新行 - "if"语句在"for"循环之外
- 试图打印数组,但在打印之前正在输入一条新线路
- 使用默认打印行为在C++中重新路由Lua打印
- 使用打印功能输出到新文件
- 链表只打印添加新节点后的最后一个元素
- c++删除排序数组中的重复项-打印新数组
- 读取整数并在按新行时打印,直到C++文件末尾
- C++打印矢量添加新行
- 我想在新行打印阵列的每个插槽