如何使用重新定义的打印函数打印Lua表?
How to print Lua table using the redefined print function?
我从这篇文章中学会了如何重新定义Lua的print()
C++https://stackoverflow.com/a/4514193/5224286。
这是重新定义的打印函数,它将变量打印到我的主机程序的控制台。(通过名为post..
的函数(
int l_my_print(lua_State *L)
{
int nargs = lua_gettop(L);
for (int i = 1; i <= nargs; ++i)
{
if (lua_isnil(L, i))
poststring("nil");
else if (lua_isboolean(L, i))
lua_toboolean(L, i) ? poststring("true") : poststring("false");
else if (lua_isnumber(L, i))
postfloat(static_cast<t_float>(lua_tonumber(L, i)));
else if (lua_isstring(L, i))
poststring(lua_tostring(L, i));
else if (lua_istable(L, i))
poststring("table: "); //how to print like Lua's built-in print()?
}
endpost();
return 0;
}
此代码工作正常,除非我打印表格。(它现在只是打印table:
(
我想知道如何打印表格,就像Lua的print()
一样
。例如,当我在Lua中运行以下代码时:(在重新定义之前(
print({1,2,3});
我得到这个结果:(似乎在不断变化(
table: 0x23b8660
这是指向 Lua 表的指针的十六进制表示形式吗?
我应该如何处理我的l_my_print()
函数,以便它可以像Lua的print()
一样工作?
只需使用luaL_tolstring
即可获取任何内容的字符串表示形式。 这也尊重元方法__tostring
。 下面的示例将 C++17 中的std::string_view
用于零副本只读字符串参数。
#include <iostream>
#include <string_view>
#include <lua.hpp>
void poststring(std::string_view sv) { std::cout << sv << 'n'; }
void endpost() { std::cout << "---n"; }
int l_my_print(lua_State *L) {
int nargs = lua_gettop(L);
for (int i = 1; i <= nargs; ++i) {
poststring(luaL_tolstring(L, i, nullptr));
lua_pop(L, 1); // remove the string
}
endpost();
return 0;
}
int main() {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, l_my_print);
lua_setglobal(L, "my_print");
int i = 0;
lua_pushlightuserdata(L, &i);
lua_setglobal(L, "udata");
luaL_dostring(L, "my_print(1, 3.14, "Hello World")n"
"my_print(false, udata, {})n");
lua_close(L);
}
调用示例:
$ clang++ -Wall -Wextra -Wpedantic -std=c++17 -I/usr/include/lua5.3 test.cpp -llua5.3
$ ./a.out
1
3.14
Hello World
---
false
userdata: 0x7fff4685993c
table: 0x883300
---
或者你可以在Lua中进行转换:
--Produces a compact, uncluttered representation of a table. Mutual recursion is employed
--source: http://lua-users.org/wiki/TableUtils
function table.tostring( tbl )
local result, done = {}, {}
for k, v in ipairs( tbl ) do
table.insert( result, table.val_to_str( v ) )
done[ k ] = true
end
for k, v in pairs( tbl ) do
if not done[ k ] then
table.insert( result,
table.key_to_str( k ) .. "=" .. table.val_to_str( v ) )
end
end
return "{" .. table.concat( result, "," ) .. "}"
end
相关文章:
- 回溯C++不打印函数,因此文件
- 重写打印函数而不是覆盖基类
- 从模板创建通用打印函数,以打印基元数据类型变量的值
- 打印传递给打印函数的矢量
- 如何使用重新定义的打印函数打印Lua表?
- 调用和打印函数,在 C++ 中返回数组
- Lua C API 自定义打印函数,在字符串中传递空格时不调用
- C++二叉树打印函数实现
- 如何从主 C++ 向模板类中的方法发送打印函数
- 如果我不打印函数参数的值,则将其转换为等于零
- 打印函数模板的内容进行类指针
- C++打印函数的结果?
- 打印 C++ 函数
- 编写一个通用打印函数来打印数组
- 用于打印函数进入和退出跟踪的宏
- 每当尝试打印函数变量时,C++ cout 错误
- GDB:当没有可用的名称符号时,如何打印函数参数值
- 在lua中重新定义打印函数时出现问题
- 打印函数会返回一个意外值,原因是什么
- IntStack的C++递归打印函数