This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
pinksheep00's profile picture

arranging tables

Started by pinksheep00, 22 March 2013 - 03:21 AM
pinksheep00 #1
Posted 22 March 2013 - 04:21 AM
How can I arrange a table by using a part of the table.

for example i want to arrange the starting from the table with the status n/a to be the first, then the "close" then the "inactive and "active"


local t = {
{name = "Forward", status = "inactive"},
{name = "Back", status = "active" },
{name = "Up", status = "close" },
{name = "Down", status = "n/a" }
}
for i = 1, #t do
print(t[i].name)
end
theoriginalbit #2
Posted 22 March 2013 - 04:24 AM
Like this? o.O or am I not understanding?

local t = {
  {name = "Down", status = "n/a" },
  {name = "Up", status = "close" },
  {name = "Forward", status = "inactive"},
  {name = "Back", status = "active" },
}
for i = 1, #t do
  print(t[i].name)
end
pinksheep00 #3
Posted 22 March 2013 - 04:30 AM
I knew someone would reply with that answer xD
well what I want is to rearrange them using the table function or something because the status are changing by conditions.
something like this


if redstone.getOutput(left) == false then
  t[2] = close
  arrange()
end
theoriginalbit #4
Posted 22 March 2013 - 04:33 AM
well what I want is to rearrange them using the table function or something because the status are changing by conditions.
oh ok i get you. sorry that should have been apparent. lol. lets blame it on the fact that its almost 3am…
Kingdaro #5
Posted 22 March 2013 - 04:33 AM
Took me a while, but I get what you mean. You can use table.sort with a function.


table.sort(t, function( a, b ) 
  return a.status < b.status
end)

But you seem to have an odd order here which isn't alphabetical. In this case, I would define a custom string to keep the order you want, then use :find() within table.sort and compare the positions.


local order = "n/a close inactive active"

table.sort(t, function( a, b )
  return (order:find(a.status) or math.huge) < (order:find(b.status) or math.huge)
end)

The "or math.huge" bit makes it so that if an element isn't found in the string, it'll automatically be ordered last in the table.
PixelToast #6
Posted 22 March 2013 - 04:37 AM
as in
table.sort(table,function(a,b)
local function cnv(c)
local c=(c.status):gsub("n/a","a") c=c:gsub("close","b") c=c:gsub("innactive","c") c=c:gsub("active","d") return c
end
return cnv(a)<cnv(b)
end)
or something like that