【问题标题】:Trying to print a table in lua试图在lua中打印一张表
【发布时间】:2019-09-03 04:02:30
【问题描述】:

我正在尝试将以下内容打印为 lua 中的输出。

inertia_x = {
{46.774, 0., 0.},
{0., 8.597, 0.},
{0., 0., 50.082}
}

x = {mass = 933.0, com = {0.0, 143.52, 0.0}, inertia_x}

print(x)

这段代码是在文本编辑器中编写的,名为 sample.lua

现在我正在使用 linux,我在存储 .lua 文件时转到正确的目录并调用

$ lua sample.lua

输出为表格:0x55c9fb81e190

我希望 x 像列表一样打印出来

这是继 Hello World 之后我的第二个 lua 程序。对 Linux 和编程也很陌生。

非常感谢您的帮助!

【问题讨论】:

  • print(x) 将只打印表 x 唯一的十六进制 id。如果你想列出表格的内容,你必须提供一些代码告诉 Lua 如何遍历表格以及如何打印它的内容。如果我可以补充:在继续之前先了解 Lua 的控制结构。循环、条件语句等

标签: linux lua


【解决方案1】:

例如:

for key, value in pairs(yourTable) do
    print(key, value)
end

如果你需要处理嵌套表,那么使用:

if type(value) == "table" then
    -- Do something
end

我将把它作为一个练习来获取上述元素并创建一个递归函数来转储嵌套表。

【讨论】:

    【解决方案2】:

    您需要检测表并递归构建表转储。试试这个:

    local inertia_x = {
    {46.774, 0., 0.},
    {0., 8.597, 0.},
    {0., 0., 50.082}
    }
    
    local x = {mass = 933.0, com = {0.0, 143.52, 0.0}, inertia_x}
    
    local function dump (  value , call_indent)
    
      if not call_indent then 
        call_indent = ""
      end
    
      local indent = call_indent .. "  "
    
      local output = ""
    
      if type(value) == "table" then
          output = output .. "{"
          local first = true
          for inner_key, inner_value in pairs ( value ) do
            if not first then 
              output = output .. ", "
            else
              first = false
            end
            output = output .. "\n" .. indent
            output = output  .. inner_key .. " = " .. dump ( inner_value, indent ) 
          end
          output = output ..  "\n" .. call_indent .. "}"
    
      elseif type (value) == "userdata" then
        output = "userdata"
      else 
        output =  value
      end
      return output 
    end
    
    print ( "x = " .. dump(x) )
    
    

    【讨论】:

    • 如果有圆圈,它就会分崩离析。
    猜你喜欢
    • 1970-01-01
    • 2018-05-19
    • 2023-03-29
    • 1970-01-01
    • 2011-11-01
    • 2011-05-27
    • 2016-07-15
    • 2016-08-07
    相关资源
    最近更新 更多