试图在lua中打印一个表

问题描述 投票:2回答:3

我试图在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文件时,我会转到正确的目录,然后调用

$ take sample.lua

输出为表:0x55c9fb81e190

理想情况下,我希望像列表一样打印x

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

非常感谢你的帮助!

linux lua
3个回答
0
投票

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

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


1
投票

例如:

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

如果需要处理嵌套表,请使用:

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

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


0
投票

好的,首先感谢大家发布您的建议和答案。

在Lua中打印列表似乎要做很多工作。 Python或MATLAB更容易。我想如果你能在Lua脚本中轻松编写列表,那么尝试再次打印它作为输出是没有意义的。但是对于我想像我这样的初学者可能会有这些问题。

我可以看到在Lua中轻松创建模型的用法,并在Meshup中将它们可视化,例如在构建刚体模型时。

感谢大家!:)

© www.soinside.com 2019 - 2024. All rights reserved.