Jump to content

i think the AddComponent method should return the component


Recommended Posts

i'm not sure if this belongs in the suggestions subforum, so i'm putting it here in the modding forum instead

anyway, this only requires one line of code in entityscript.lua:

function EntityScript:AddComponent(name)
	'...stuff...'
  
	return loadedcmp
end

there's no drawbacks from this afaik, and it should make dealing with components when making prefabs look cleaner:

'for example, this is how you would usually use components currently:'

inst:AddComponent("level")
inst.components.level.name = "Wilson"
inst.components.level.level = 10
inst.components.level:SetOnLevelUp(onlevelup)
inst.components.level:SetOnLevelDown(onleveldown)
inst.components.level:Enable(true)

'if the AddComponent method returns the component, you can shorten it to this:'
local level = inst:AddComponent("level")
level.name = "Wilson"
level.level = 10
level:SetOnLevelUp(onlevelup)
level:SetOnLevelDown(onleveldown)
level:Enable(true)

'though currently, you can do this right now, but it doesnt look as good especially with lots of components:'
inst:AddComponent("level")
local level = inst.components.level
level.name = "Wilson"
level.level = 10
level:SetOnLevelUp(onlevelup)
level:SetOnLevelDown(onleveldown)
level:Enable(true)

 

Edited by Jessie223
Link to comment
Share on other sites

  • Developer
On 12/29/2019 at 10:19 AM, Jessie223 said:

--snip--

I personally dislike this coding style, and think it makes stuff uglier, but a simple function replacement would allow you to do this:
 

local _AddComponent = EntityScript.AddComponent
function EntityScript:AddComponent(name, ...)
	_AddComponent(self, name, ...)
  	return self.components[name]
end

 

  • Like 1
Link to comment
Share on other sites

Thing is, for all those instances where you don't need to access the component immediately after, it introduces a redundant return value, and you still have to check for it not being nil if you want to use it.

I don't dislike this type of coding on principle. It has its place. Specifically in situations where you know that you will want to, or need to, access the added component immediately after adding it in the majority of cases.

Edited by Ultroman
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
  • Create New...