Archived

This topic is now archived and is closed to further replies.

Please be aware that the content of this thread may be outdated and no longer applicable.

Jessie223

i think the AddComponent method should return the component

Recommended Posts

Jessie223    790

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)

 

Share this post


Link to post
Share on other sites
Zarklord    635
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

 

Share this post


Link to post
Share on other sites
Ultroman    655

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.

Share this post


Link to post
Share on other sites