4

I am trying to print the following as output in 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)

This code was written in a text editor and named sample.lua

Now I am using linux and I go to the correct directory while the .lua file is stored and I call

$ lua sample.lua

and output is table: 0x55c9fb81e190

I would ideally like to get x printed like a list

This is my 2nd lua program after Hello World. Very new to Linux and programming as well.

I would greatly appreciate your help!

Piglet
  • 27,501
  • 3
  • 20
  • 43
Marty
  • 63
  • 1
  • 7
  • 1
    Possible duplicate of [How to dump a table to console?](https://stackoverflow.com/questions/9168058/how-to-dump-a-table-to-console) – Piglet Apr 12 '19 at 12:21
  • print(x) will just print a hexadecimal id unique to the table x. If you want to list the contents of the table you have to provide some code that tells Lua how to traverse the table and how to print its contents. and if I may add: get to know the control structures of Lua befor you continue. loops, conditional statements and so on – Piglet Apr 12 '19 at 12:22

2 Answers2

4

For example:

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

If you need to handle nested tables, then use:

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

I'll leave it as an exercise to take the above elements and make one, recursive function to dump nested tables.

brianolive
  • 1,573
  • 2
  • 9
  • 19
1

You need to detect table and recursively build the table dump. Try this :

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