How should I go about calling a function through a variable's name?

I’ve been testing around with some code, specifically nested functions. I’ve gotten a script written down which follows the following steps:

  1. A GetHit Remote event is fired with the player who sent it, the players position, and the type of attack.
  2. The Server recieves this, and fires a nested function with the same name as the type of attack.
  3. The Server continues on with the rest of its functions.

However, I can’t seem to call the function, recieving this error when attempting to do so:
ServerScriptService.Script:165: invalid argument #1 to ‘spawn’ (function or thread expected)

Here is the code:

LocalScript:

getHit:FireServer(atkPosition, "normalAttack")

ServerScript:

getHit.OnServerEvent:Connect(function(player, cframe, func)
	local hitbox
	local function normalAttack()
		hitbox = getHitter:Clone()
		hitbox.CFrame = cframe
		hitbox.Parent = workspace
		game.Debris:AddItem(hitbox, 0.5)
		getTouch()
	end
	task.spawn(func)
end)```

It wont work because you are sending a string for func through the event and then trying to use task.Spawn on a string. You should add an if statement that finds out what function the string is representing and then choose the function that the string represented

Dang nabbit, i was hoping to get away from elseif statments, oh well.

if the function was in a table, it would be possible. Something like this:

local functionTable = {}


function functionTable.myFunc(message : string) : nil
	print(message)
end

local functionName = "myFunc"
functionTable[functionName]("test")
2 Likes

Aye, thanks for the note. Although, its probably best I just capped this post of mine.

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