Can ints be passed to functions in ContextActionService:BindAction()?

The for loop below passes an int: the loop index, to a function through :BindActioin() but it doesn’t work without tonumber() and tostring:

local function gearKeys(actionName, inputState)
    if inputState == Enum.UserInputState.Begin then 
    -- you custom logic below
    toggleGear(items[tonumber(actionName)][1]) return Enum.ContextActionResult.Sink
end end
for i, n in {"Four", "Six", "Eight", "Nine", "Zero"} do 
    game:GetService("ContextActionService"):BindAction(tostring(i), gearKeys, false, Enum.KeyCode[n]) end

There’s a better way of doing this that doesn’t require making 5 different actions

local keys = {"Four", "Six", "Eight", "Nine", "Zero"} do
    for i, id in keys do -- loop through the initial values and update them
       keys[i] = Enum.KeyCode[id] -- switch the item in the table to the enum equivalent
    end
end

local function gearKeys(actionName: string, inputState: Enum.UserInputState, inputObject: InputObject)
    if inputState == Enum.UserInputState.Begin then
        -- table.find returns the table index where the provided value was found in
        -- for example, table.find(keys, Enum.KeyCode.Four) will return 1 because that's where it is in the list
        toggleGear(items[table.find(keys, inputObject.KeyCode)][1])
        return Enum.ContextActionResult.Sink
    end
    return Enum.ContextActionResult.Pass -- remember to pass the input if this isn't going to do anything
end

game:GetService("ContextActionService"):BindAction("ItemSwitch", gearKeys, false, table.unpack(keys))

But you’ve seemed to have answered your own question:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.