Nested Functions vs Non-Nested Functions

The code itself works fine this is just a question on if nested functions are more taxing

Version A:

local LevelModule = {}

local maxLevel = 13


function LevelModule.addExp(level, exp, expToAdd)
	
	
	exp = exp + expToAdd
	
	local function xpNeeded(level) -- only used in the addExp function
		return level * 70
	end
	
	local function recursion()
		local neededExp = xpNeeded(level)
		if level == maxLevel then
			exp = neededExp
		elseif exp >= neededExp then
			exp = exp - neededExp
			level = level + 1
			recursion()
		end
	end
	
	recursion()
	
	return level, exp
	
end

return LevelModule

as you can see the xpNeeded function is nested inside the addExp function which makes everything more organized

Version B:

local LevelModule = {}

local maxLevel = 13

local function xpNeeded(level) -- only used in the addExp function
	return level * 70
end

function LevelModule.addExp(level, exp, expToAdd)
	
	
	exp = exp + expToAdd
	
	local function recursion()
		local neededExp = xpNeeded(level)
		if level == maxLevel then
			exp = neededExp
		elseif exp >= neededExp then
			exp = exp - neededExp
			level = level + 1
			recursion()
		end
	end
	
	recursion()
	
	return level, exp
	
end

return LevelModule

in this version the xpNeeded function is no longer nested, but it is still only used then the addExp function thus only defining it once but becomes less organized than version A

is defining a function more that once (having a nested function) costly, or is it worth nesting for the organization factor

TL:DR are nested functions worth using over non-nested functions for the sake of organization/are nested functions more taxing than non-nested functions

Note: this can all apply to the recursion function too

3 Likes

Whether it’s organized or not is up to the user. I personally think defining outside is a lot more organized and Lua-style, but regardless it usually doesn’t make a difference. Beware however, whenever “function” keyword is encountered in the code you end up allocating a new function closure.

Also, in most languages it’s generally better to parametize your functions and reduce data dependency as much as possible.

4 Likes

so something more like this?

local LevelModule = {}

local MAX_LEVEL = 13

local function xpNeeded(level)
	return level * 100
end
	
function LevelModule.addExp(level, exp, expToAdd)
	
	local neededExp = xpNeeded(level)
	exp = exp + expToAdd
	
	
	while exp >= neededExp do
		
		if level < MAX_LEVEL then
			level = level + 1
			exp = exp - neededExp
		else
			exp = neededExp	
			break
		end
		
		neededExp = xpNeeded(level)
		wait()
		
	end
	
	return level, exp
	
end

return LevelModule