How to deal with function with tons of arguments?

  1. What do you want to achieve? Need help dealing with passing many arguments into function
  2. What is the issue? Whenever I pass to many arguments code become unreadable and to long
  3. What solutions have you tried so far? Passing arguments in as a table

Sometimes when I code, I get to a problem where the arguments I pass into a function becomes to many causing the code to become a bit unreadable. They way I have dealt with this is packaging all the arguments into a table, and then passing the table inside the function and then unpacking the table into the function in a fashion similar to this.

I want to know if this is a good way to pass many arguments into a function, I could maybe use global variables, but idk if its good thing to do. I wanne know what you guys think of doing it this way, or if there is a better way of passing many arguments into a function.

local function someFunction(arguments)
	local health = arguments.health
	local speed = arguments.speed
	local jumpPower = arguments.jumpPower
	local height = arguments.height
	--some function logic
end
local arguments = {
	health = 50,
	speed = 12,
	jumpPower = 32,
	height = 59,
}
someFunction(arguments)

I think I could also maybe do some object oriented program style, where I could pass the obj. So kinda like function(this) and then when using the variables I could do this.Health, this.Speed etc. Is that a better way of doing it maybe?

umm, is 4 arguments a ton?
or is this just an exampleā€¦

seems like either way is fine, do what you like. For performance and things, it would probably relate to how often are you calling the function, and what is the overhead of ā€˜unpackingā€™ the tableā€¦ which my guess it probably minimal to non existent.

I kind of like your table method

1 Like

Honestly, I donā€™t see a reason behind the ā€œunpackingā€ part, you can just use less letters for the table variable(like a or args instead of arguments) to make it take less space.

Also if something starts having many properties that define it, you may want to consider converting it to an object/class. That way you will be able to set defaults, decide which arguments are necessary to construct said object and also add functions to modify said values later on if you want(for example a function named setSpeed).

1 Like

Hmm I see, so kinda using metatable then or? And then using self.health, self.speed, self.jumpPower etc?

1 Like

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