Table help! Please read

. You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I Want To Change The Key You Have To Press
  2. What is the issue? Include screenshots / videos if possible!
    I Dont Know How To Do It
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    Ive Tried Some Things But All In Vain And Extreamly Long
    After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!
game:GetService('StarterGui'):SetCoreGuiEnabled(Enum.CoreGuiType.Backpack, false)
 
 --< variables >--
local uis = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local char = workspace:WaitForChild(player.Name) -- added WaitForChild
local bp = player.Backpack
local hum = char:WaitForChild("Humanoid")
local frame = script.Parent.Frame
local template = frame.Template
local equipped = 0.2 -- icon transparencies
local unequipped = 0.7
local Changing = false
local iconSize = template.Size
local iconBorder = {x = 15, y = 5} -- pixel space between icons

local inputKeys = { -- dictionary for effective referencing
	["One"] = {txt = "1"},
	["Two"] = {txt = "2"},
	["Three"] = {txt = "3"},
	["Four"] = {txt = "4"},
	["Five"] = {txt = "5"},
	["Six"] = {txt = "6"},
	["Seven"] = {txt = "7"},
	["Eight"] = {txt = "8"},
	["Nine"] = {txt = "9"},
	["Zero"] = {txt = "0"},
}

local inputOrder = { -- array for storing the order of the keys
	inputKeys["One"],inputKeys["Two"],inputKeys["Three"],inputKeys["Four"],inputKeys["Five"],
	inputKeys["Six"],inputKeys["Seven"],inputKeys["Eight"],inputKeys["Nine"],inputKeys["Zero"],
}
	
--< functions >--
function handleEquip(tool)
	if tool then
		if tool.Parent ~= char then
			hum:EquipTool(tool)
		else
			hum:UnequipTools()
		end
	end
end

function create() -- creates all the icons at once (and will only run once)

	local toShow = #inputOrder -- # operator can only be used with an array, not a dictionary
	local totalX = (toShow*iconSize.X.Offset)+((toShow+1)*iconBorder.x)
	local totalY = iconSize.Y.Offset + (2*iconBorder.y)

	frame.Size = UDim2.new(0, totalX, 0, totalY)
	frame.Position = UDim2.new(0.5, -(totalX/2), 1, -(totalY+(iconBorder.y*2)))
	frame.Visible = true -- just in case!

	for i = 1, #inputOrder do

		local value = inputOrder[i]		
		local clone = template:Clone()
		clone.Parent = frame
		clone.Label.Text = value["txt"]
		clone.Name = value["txt"]
		clone.Visible = true
		clone.Position = UDim2.new(0, (i-1)*(iconSize.X.Offset)+(iconBorder.x*i), 0, iconBorder.y)
		clone.ImageTransparency = unequipped

		local tool = value["tool"]
		if tool then
			clone.Tool.Image = tool.TextureId
		end
		clone.Tool.MouseButton1Down:Connect(function() -- click icon to equip/unequip
			for key, value in pairs(inputKeys) do
				if value["txt"] == clone.Name then
					if Changing == false then
						Changing = clone
					else
						if clone ~= Changing then	
							print(Changing.Label.Text)
							-- Changes The Keycodes Between The Changing And The Clone
							local OldClonePos = nil
							local OldCloneNum = nil
							OldClonePos = clone.Position
							clone.Position = Changing.Position
							OldCloneNum = clone.Label.Text
							clone.Label.Text = Changing.Label.Text						
							Changing.Label.Text = OldCloneNum
							Changing.Position = OldClonePos
							Changing = false
							end
					end
				end 
			end
		end)

	end	
	template:Destroy()
end

function setup() -- sets up all the tools already in the backpack (and will only run once)
	local tools = bp:GetChildren()
	for i = 1, #tools do 
		if tools[i]:IsA("Tool") then -- does not assume that all objects in the backpack will be a tool (2.11.18)
		for i = 1, #inputOrder do
			local value = inputOrder[i]
			if not value["tool"] then -- if the tool slot is free...
				value["tool"] = tools[i]	
				break -- stop searching for a free slot
			end
		end
		end
	end
	create()
end

function adjust()
	for key, value in pairs(inputKeys) do
		local tool = value["tool"]
		local icon = frame:FindFirstChild(value["txt"])
		if tool then
			icon.Tool.Image = tool.TextureId
			if tool.Parent == char then -- if the tool is equipped...
				icon.ImageTransparency = equipped
			else
				icon.ImageTransparency = unequipped
			end
		else
			icon.Tool.Image = ""
			icon.ImageTransparency = unequipped
		end
	end
end

function onKeyPress(inputObject) -- press keys to equip/unequip
	local key = inputObject.KeyCode.Name
	local value = inputKeys[key]
	if value and uis:GetFocusedTextBox() == nil then -- don't equip/unequip while typing in text box
		handleEquip(value["tool"])
	end 
end

function handleAddition(adding)

	if adding:IsA("Tool") then
		local new = true

		for key, value in pairs(inputKeys) do
			local tool = value["tool"]
			if tool then
				if tool == adding then
					new = false
				end
			end
		end

		if new then
			for i = 1, #inputOrder do
				local tool = inputOrder[i]["tool"]
				if not tool then -- if the tool slot is free...
					inputOrder[i]["tool"] = adding
					break
				end
			end
		end

	adjust()
	end
end

function handleRemoval(removing) 
	if removing:IsA("Tool") then
		if removing.Parent ~= char and removing.Parent ~= bp then

			for i = 1, #inputOrder do
				if inputOrder[i]["tool"] == removing then
					inputOrder[i]["tool"] = nil
					break
				end
			end
		end

		adjust()
	end
end

--< events >--
uis.InputBegan:Connect(onKeyPress)

char.ChildAdded:Connect(handleAddition)
char.ChildRemoved:Connect(handleRemoval)

bp.ChildAdded:Connect(handleAddition)
bp.ChildRemoved:Connect(handleRemoval)

--< start >--
setup()

script.Parent.Frame.Background.MouseLeave:Connect(function()
	Changing = false
end)

I Need To Flip The Changing And Clones keycode i dont know how to do that but i need to change say your fliping slot 1 to slot 2 i need to make The inputKeys[“One”][txt] and inputKeys[“Two”][txt] i just dont know how to do that as the numbers are in “”

Thanks For Any Help

you can add an extra argument to the table nested inside as an order parameter using an actual number, then sort them out when doing __index on inputOrder or so, I did not understand what you wanted completely because your wording was a bit weird, so if you could explain it again it would help

So this is an inventory system. Im working on a sysyem to alow inventory sorting sort of like fortnite. At the moment i need to change that key so for example in a swap between slot 1 and 2
Before:
One = “1”
Two = “2”
After:
One = “2”
Two = “1”

I have an idea to use tostrings and tonumbers but sadly im in the car if you would like me to explain my idea let me know it is along the lines of what you said

ahh I see, I’d honestly not use a string and use a number instead then

Ok my idea tell me if this would work is take the numbers out of there quotations and then when i need to check stuff with names put them in a tostring. Sadly im heading to school.

PS am i alowed to reference the string with inputkeys[1] even though i have that 1 = to “One” if not whats a workaround

1 Like

At school as well, I’ll peek on this again once home

Alr i have access to my phone now but i cant test anything cuz im going to the horse barn

Dam, alright, message in here when u can so I can try and help

Sorry i havent checked my phone. So i stoped at home and i had 3 minutes so i booted up my pc and changed all thoes variables to numbers! I think im 2 lines of code away from my solution and ik what they are! They are
Inputkeys[changing] = clone
Inputkeys[i] = changing
Somthing like that and i may of changed it

Ive tried my idea and it didnt work

If you want to work with numbers (0,1,2…) instead of the “one”, “two”, “three”, you could recreate a map.
e.g.

local numbers = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}
function NumberFromNumber(num)
    if num == 0 then
        return "Zero"
    else
        return numbers[num]
    end

end

The problem with this is there are 10 slots, ide have to 100 diferent combinations of if statements

Can you explain what you’re actually trying to do here?

From your first post it sounded like you wanted to do change which items would be equipped when you pressed numeric keys e.g.

  1. KeyCode.One = EquipItem1 → swapped with (2) so this would now be KeyCode.One = EquipItem2
  2. KeyCode.Two = EquipItem2 → swapped with (1) so this would now be KeyCode.Two = EquipItem1

But now you’re saying you can have up to 100 slots and mentioned an inventory system in another comment?

If it’s easier for you it might be better to show a video. No idea what the fortnite one looks like, but if that’s what you’re trying to replicate: can you send a video link of how it works with a timestamp to the point in the video?

I didnt mean i had 100 slots i said that i had 10 slots with 2 diferent variables meaning i would need 100 if statements

Im trying to make a swap mechanic for my inventory system what i have working right noe is it swaps the position of the 2 boxes the items are in and the changing the number of keycode it shows needs to be changed the problem is it keeps the keycode and i need to swap the keycodes. Here is a game with the current system in it(i cant send videos gor like 9hrs cuz school) https://www.roblox.com/share?code=149b7e386634a143b421be69f0b9b7ab&type=ExperienceDetails&stamp=1715255988349

Im on mobile rn btw

As you can see in that you can successfully switch the slots but it doesnt switch the keybinds between the 2 slots

Sorry for the confusion i have dislexia(look it up) so its harder for me to express thoughts in a way others understand and sorry for the lenghth of this but hope it clarifies

You just click on an item and then drag it to another one and it swaps with the fortnite one(i dont want the drag)

Experience is private so I can’t visit it sorry but I see, that makes more sense - it sounds like what I initially expected it to be when I first read your post; thanks for explaining.

To confirm:

  1. You want a GUI that shows the tools and the key codes used to equip the item
  2. You want users to be able to equip that item by pressing the key code shown in the GUI
  3. You want users to be able to swap the position of those items and for both the GUI and the key code used to update based on the new position. Based on your code, it looks like you want them to be able to swap tools by:
    • User clicks a tool in their toolbar - this sets the first swap item
    • User clicks another tool in the toolbar - this sets the second swap item; which makes them swap places

Is that right? Just want to double check before I help you with an example


No worries, you don’t have to apologise at all! I just wanted to make sure I understood what you were doing so I could try to help


Edit:

Got distracted by something else, but here:

Example
local Players = game:GetService('Players')
local RunService = game:GetService('RunService')
local StarterGui = game:GetService('StarterGui')
local UserInputService = game:GetService('UserInputService')

-- disable our core gui
--
--   NOTE: this can actually fail so you might want to consider wrapping this
--         in a pcall and repeating it until you're successful
--
StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.Backpack, false)


--[!] const

-- max tool slot size
local TOOL_MAX_SLOTS = 10

-- i.e. GUI-related tool slot settings
local TOOL_SIZE = 50            -- tool icon size
local TOOL_BORDER_OFFSET = 15   -- gap between icons
local TOOL_BOTTOM_OFFSET = 20   -- offset from bottom of screen

-- keycode values, see here: https://create.roblox.com/docs/reference/engine/enums/KeyCode
--
--    where:
--      48 = Zero
--      49 = One
--       n = ...
--      57 = Nine
--
local NUMERIC_KEYCODE_ZRO = 48
local NUMERIC_KEYCODE_MIN = 49
local NUMERIC_KEYCODE_MAX = 57

-- i.e. the range of Enum.KeyCode[name].Value that represents numeric keycodes
local NUMERIC_KEYCODE_RANGE = NumberRange.new(NUMERIC_KEYCODE_MIN, NUMERIC_KEYCODE_MAX)

-- i.e. set up a dictionary that maps the value to a specific keycode
local KEYCODE_VALUES = { }
for _, keycode in next, Enum.KeyCode:GetEnumItems() do
  KEYCODE_VALUES[keycode.Value] = keycode
end


--[!] utils

-- checks whether a character is alive, and has valid character instances e.g. humanoid + rootpart
local function tryGetCharacterInstances(character)
  if typeof(character) ~= 'Instance' or not character:IsA('Model') or not character:IsDescendantOf(workspace) then
    return false
  end

  local humanoid = character:FindFirstChildOfClass('Humanoid')
  local humanoidState = humanoid and humanoid:GetState() or Enum.HumanoidStateType.Dead
  local humanoidRootPart = humanoid and humanoid.RootPart or nil
  if humanoidState == Enum.HumanoidStateType.Dead or not humanoidRootPart then
    return false
  end

  return true, humanoid, humanoidRootPart
end

-- wait until we find a valid character
local function awaitCharacter(player)
  if typeof(player) ~= 'Instance' or not player:IsA('Player') then
    return nil
  end

  local character
  while not character do
    if not player or not player:IsDescendantOf(Players) then
      break
    end

    local char = player.Character
    if not char then
      player.CharacterAdded:Wait()
      continue
    end

    local valid = tryGetCharacterInstances(char)
    if not valid then
      RunService.Stepped:Wait()
      continue
    end

    character = char
  end

  return character
end


--[!] methods

-- used to create the tool slot UI frames
-- since I don't have them already made like yourself
--
local function createToolSlot(parent, index, keyCode)
  local position = index - math.ceil(TOOL_MAX_SLOTS*0.5)

  -- NOTE: you can just swap this out with your current code
  local frame = Instance.new('ImageButton')
  frame.Name = 'Toolslot' .. index
  frame.Size = UDim2.fromOffset(TOOL_SIZE, TOOL_SIZE)
  frame.Position = UDim2.new(0.5, position*(TOOL_SIZE + TOOL_BORDER_OFFSET*0.5), 1, -TOOL_BOTTOM_OFFSET)
  frame.AnchorPoint = Vector2.new(0.5, 1)
  frame.BorderSizePixel = 1
  frame.BackgroundTransparency = 0
  frame.Image = ''
  frame.ImageTransparency = 1

  local posLabel = Instance.new('TextLabel')
  posLabel.Name = 'PositionLabel'
  posLabel.Size = UDim2.fromOffset(13, 13)
  posLabel.Position = UDim2.fromScale(0, 0)
  posLabel.AnchorPoint = Vector2.new(0, 0)
  posLabel.BorderSizePixel = 1
  posLabel.BackgroundTransparency = 1
  posLabel.Text = tostring(index)
  posLabel.Parent = frame

  local keyLabel = Instance.new('TextLabel')
  keyLabel.Name = 'KeyCodeLabel'
  keyLabel.Size = UDim2.new(1, 0, 0, 13)
  keyLabel.Position = UDim2.fromScale(0.5, 1)
  keyLabel.AnchorPoint = Vector2.new(0.5, 1)
  keyLabel.BorderSizePixel = 1
  keyLabel.BackgroundTransparency = 1
  keyLabel.Text = keyCode.Name
  keyLabel.Parent = frame

  local toolLabel = Instance.new('TextLabel')
  toolLabel.Name = 'ToolLabel'
  toolLabel.Size = UDim2.new(1, 0, 0, 25)
  toolLabel.Position = UDim2.fromScale(0.5, 0.5)
  toolLabel.AnchorPoint = Vector2.new(0.5, 0.5)
  toolLabel.BorderSizePixel = 1
  toolLabel.TextColor3 = Color3.fromHSV(0.98, 0.7, 0.75)
  toolLabel.BackgroundTransparency = 1
  toolLabel.Text = ''
  toolLabel.Parent = frame

  frame.Parent = parent
  return frame, toolLabel
end


-- used to check whether the tool is still within the
-- player's backpack / their character; and if not, will remove
-- it from the slots e.g. in cases where they pressed backspace to drop the tool
--
local function handleToolRemoval(player, toolSlots, object, connection)
  -- make sure we've not just equipped the tool
  local character = player.Character
  if object:IsDescendantOf(player) or (character and object:IsDescendantOf(character)) then
    return
  end

  -- find the tool slot so we can remove it
  local toolSlot
  for i = 1, TOOL_MAX_SLOTS, 1 do
    local slot = toolSlots[i]
    if slot.Tool == object then
      toolSlot = slot
      break
    end
  end

  -- if the toolslot exists then let's reset the slot
  if toolSlot then
    toolSlot.Tool = nil
    toolSlot.Label.Text = ''
  end

  -- stop listening to this tool's ancestry since it's been not related to our player now
  if connection and connection.Connected then
    connection:Disconnect()
  end
end


-- used to add the tool to the next best slot
-- if not already present
--
local function handleToolAdded(player, toolSlots, object)
  if not object:IsA('Tool') then
    return
  end

  -- make sure we don't already exist
  -- otherwise select next best empty slot
  local bestSlot
  for i = 1, TOOL_MAX_SLOTS, 1 do
    local slot = toolSlots[i]
    if slot.Tool == object then
      return
    elseif not bestSlot and not slot.Tool then
      bestSlot = i
    end
  end

  if bestSlot then
    -- i.e. we're a new tool
    bestSlot = toolSlots[bestSlot]
    bestSlot.Tool = object
    bestSlot.Label.Text = object.Name

    -- watch the ancestry of the object (i.e. it's parent)
    -- to check when the player removes the tool from its backpack
    -- and/or its character
    local watchdog
    watchdog = object.AncestryChanged:Connect(function ()
      handleToolRemoval(player, toolSlots, object, watchdog)
    end)
  end
end


--[!] setup
local player = Players.LocalPlayer
local backpack = player:WaitForChild('Backpack')
local character = awaitCharacter(player)
local screenGui = script.Parent


-- states
local toolSlots = table.create(TOOL_MAX_SLOTS)  -- i.e. all of the tool slots
local toolSlotMap = { }                         -- i.e. a map between a keycode and a tool slot

local selectedToolSlot                          -- the tool slot we're trying to swap
local isChangingKeybinds = false                -- whether we're trying to change our keybinds


-- set up our keybind slots
for i = 1, TOOL_MAX_SLOTS, 1 do
  -- get the KeyCode from the slot number
  local keyCode
  if i == TOOL_MAX_SLOTS then
    keyCode = KEYCODE_VALUES[NUMERIC_KEYCODE_ZRO]
  else
    keyCode = KEYCODE_VALUES[NUMERIC_KEYCODE_MIN + (i - 1)]
  end

  -- set up the slot
  local slot, toolLabel = createToolSlot(screenGui, i, keyCode)

  -- append to our list
  toolSlots[i] = {
    Tool = nil,
    Slot = slot,
    Label = toolLabel,
    Index = i,
    KeyCode = keyCode,
  }
  toolSlotMap[keyCode] = i

  -- set up the listener
  slot.MouseButton1Click:Connect(function ()
    -- set the selected one to our current slot
    -- if we aren't already trying to change it
    if not isChangingKeybinds then
      isChangingKeybinds = true
      selectedToolSlot = i
      return
    end

    -- swap our slots around
    local swapSlot = toolSlots[selectedToolSlot]
    local thisSlot = toolSlots[i]
    isChangingKeybinds, selectedToolSlot = false, nil

    -- swap our tool reference around
    thisSlot.Tool, swapSlot.Tool = swapSlot.Tool, thisSlot.Tool

    -- swap the label text around
    thisSlot.Label.Text, swapSlot.Label.Text = swapSlot.Label.Text, thisSlot.Label.Text
  end)
end


-- set up our input action(s)
UserInputService.InputBegan:Connect(function (input, gameProcessed)
  -- ignore if not keyboard input and/or it's used by something else e.g. a textbox
  local inputType = input.UserInputType
  if gameProcessed or inputType ~= Enum.UserInputType.Keyboard then
    return
  end

  -- ignore if we're dead
  local isValid, humanoid = tryGetCharacterInstances(character)
  if not isValid then
    return
  end

  -- try to get the slot from the keycode and ignore if it doesn't exist
  local keyCode = input.KeyCode
  local slotIndex = toolSlotMap[keyCode]
  local toolSlot = slotIndex and toolSlots[slotIndex] or nil
  if not toolSlot then
    return
  end

  -- if we haven't got a tool for this slot we can ignore it
  local tool = toolSlot.Tool
  if not tool then
    return
  end

  -- equip it if we're not using it;
  -- otherwise unequip it
  if tool.Parent ~= character then
    humanoid:EquipTool(tool)
  else
    humanoid:UnequipTools()
  end
end)


-- set up our listener(s)
--    - we need to make sure we look at those already
--      in the backback too
--
--    - we also need to make sure any tools added to the char
--      via pickup get added
--
for _, object in next, backpack:GetChildren() do
  handleToolAdded(player, toolSlots, object)
end

backpack.ChildAdded:Connect(function (object)
  handleToolAdded(player, toolSlots, object)
end)

character.ChildAdded:Connect(function (object)
  handleToolAdded(player, toolSlots, object)
end)

Bingo! Sorry that game was private il unprivate it when i get home once i do that you can see what i have and it should be crystal clear ehat you listed above is right and thanks for the help! I gtg get my hair cut tho so cya

Alr i just unprivated it, I did some testing and we need to swap the inputorder keys not the input keys i think im on the verge of a solution tho(ive thought that a couple times)

i tried that code and it worked the problem is i wana integrate it into my own ui il work on it

Ok im happy with the ui you have made it kinda fits the style for the game idea ty for making it!! TYSM FOR THE HELP!!