Table Only Showing One Value

I made a script that sorts parts with the same x value into a table but it only shows one of the three that should show up

local XPositions = {}
local XPositionTabels = {}
for i,v in pairs(game.Workspace.Leds:GetChildren()) do
	local value = v.Position.X
	value *= 1000
	value = math.floor(value)
	value =  value / 1000
    local numstring = tostring(value)
	if table.find(XPositions,value) then
        local tableval = table.find(XPositionTabels,numstring)
		table.insert(tableval,v.Name)
        else
		XPositionTabels[value] = {v.Name}
		table.insert(XPositions,numstring)
	end
end

If you are sorting a table why not just use table.sort() ?

https://developer.roblox.com/en-us/api-reference/lua-docs/table

It’s probably because you are inserting numstring but looking for value

    local numstring = tostring(value)
	if table.find(XPositions, numstring) then
        local tableval = table.find(XPositionTabels, numstring)
		table.insert(tableval,v.Name)
    else
		XPositionTabels[value] = {v.Name}
		table.insert(XPositions,numstring)
	end

There are other issues, but now the if statement will at least run sometimes. I don’t understand what you want these tables to look like.

1 Like

this is how i would group all the leds with position.X

-- make a empty leds table
local leds = {}

-- loop every child in game.Workspace.Leds
for i,child in ipairs(game.Workspace.Leds:GetChildren()) do
    -- use the X position to make a key
    local key = math.round(child.Position.X * 1000) / 1000
    -- if the leds table does not have a the key then create a empty table using the key
    if leds[key] == nil then leds[key] = {} end
    -- insert the child into the inner table
    table.insert(leds[key], child)
end

-- to see if are code worked lets print it out by first looping every x position in the leds table
for x, list in pairs(leds) do
    print("-------", x)
    -- now lets loop the inner table with all the leds in this X position
    for i, led in ipairs(list) do
        print(led.Name)
    end
end
1 Like

How could I also make it sort them by the x value?
I tried to use table.sort but it didn’t work

It would not be possible to sort the leds table because it’s a dictionary because the keys have holes you may also notice I used pairs and not ipairs to loop leds

You would need to make a second table that looks something like this

positions = {
     [1] = 38,
     [2] = 94,
     [3] = 294,
     [4] = 74934,
}

for i, x in ipairs(positions) do
    for i, led in ipairs(leds[x]) do
        print(led.Name)
    end
end
1 Like