Reputation: 73
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!
Upvotes: 5
Views: 9209
Reputation:
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) )
Upvotes: 1
Reputation: 1671
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.
Upvotes: 7