How to print Lua table using the redefined print function?

安稳与你 提交于 2019-12-06 07:37:41

Just use luaL_tolstring to get the string representation of anything. This also respects the __tostring metamethod. The example below uses std::string_view from C++17 for zero-copy read-only string arguments.

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

Example invocation:

$ 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
---

Or you could do the conversion in 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!