Function in table, how do I make it run the function?

How do I use this function?

-- // Functions are here
Attacks = {

	["Testing Stand"] = {
		["R"] = function()
			print("hi")
		end;
		["E"] = function()
			print("hi")
		end;
		["C"] = function()
			print("hi")
		end;
	}



}

-- // the part where I want the function to work
function idk.MoveInput(plr,stand,standname,key)
	local attacks = nil
	for standnamer,literallynothing in pairs(Attacks) do
		if standnamer == standname then
			attacks = literallynothing
		end
	end
	if attacks ~= nil then
		--print(attacks)
		for movekey,func in pairs(attacks) do
			if movekey == key then
			
				--move(func,plr,stand,key)
			end
		end
	end
end

This would make my project so much easier to work with.

I don’t think it’s possible instead you could use module scripts

Try this.

local attacks = {
	['Testing Stand'] = {
		['R'] = function()
			print('R')
		end,
		['E'] = function()
			print('E')
		end,
		['C'] = function()
			print('C')
		end,
	}
}

function idk.MoveInput(player, stand, name, key)
	local attacks
	for i, v in pairs(attacks) do
		if i == name then
			attacks = v
		end
	end
	if typeof(attacks) == 'table' then
		local attack = attacks[key] -- assuming key is KeyCode, use key.Name instead.
		if typeof(attack) == 'function' then
			attack()
		end
	end
end

Alright here’s an edit with some explanation.
What you have here is a mode based control mapping and you can use this for KeyCode mostly or if you want to support different types of input you can have input conversion methods to convert your other input methods to keyboard (such as if someone presses A on Xbox Controller you’d translate it to Space Bar).

By setting a mode, you can retrieve the functions that mode contains by indexing the mode attack list with the mode id (that being 1 in the script below).

local mode_based_attacks = {
	[1] = {
		['A'] = function()
			
		end,
	}
}

local userinputservice = game:GetService("UserInputService")
local currentmode = 1

userinputservice.InputBegan:Connect(function(input, processed)
	if processed ~= true then
		local attacks = mode_based_attacks[currentmode]
		local attack = typeof(attacks) == 'table' and attacks[input.KeyCode.Name]
		if typeof(attack) == 'function' then
			attack()
		end
	end
end)
1 Like