Npc/monster attributes (Tags, DataStore, ?)

I have a common Npc/monster script, but I changing it to replace the hard coded constants with either DataStore or “Tags”

I want to populate those values (speed, HP, etc) when each object is cloned and added to the workspace.

I don’t think Lua has a constructor concept so I was thinking my choices were either leveraging DataStore or tags.

What is the recommended design for this?

By tag I mean this:
local tag = Instance.new(“IntValue”)
tag.Name = “speed”
tag.Parent = npcClonedObject
tag.Value = value

thanks

1 Like

Using IntValues (and similar instances) is a valid way of doing it, unless you want to hide the contained information from clients.
If you want to use constructors in an object-oriented sense, this can be accomplished with metatables. There are lots of tutorials online and on this forum on how to achieve this (for example: All about Object Oriented Programming). If you do go down this route, please remember that metadata about tables are not replicated across the client-server boundary, so you will need to handle client-server replication more carefully.

1 Like

You can implement objects in lua.

1 Like

With a constructor or “protected/public” properties?
I’m a newb and probably don’t have things designed correctly.

Currently I have two models (NPC1, NPC2) in ServerStorage with a local script for each (this is where speed is defined as a constant) and I have a Module script NpcHelper in ServerScriptService that has shared Npc functions like FindTarget, FollowTarget, etc.

Currently I’m cloning each NPC model and adding to workspace.
If I wanted to clone 10 NPC1/2 models where/how would set the Speed value ?

Sorry if this too confusing. Any example/link of how to initialize values would help.

thanks.

1 Like

I posted a link about how you can achieve object-oriented programming already: All about Object Oriented Programming
It goes into good detail about how you would initialize fields and methods for objects.

1 Like

You just made my day.

You article does a great job of explaining how to achieve encapsulation with Lua.
Do you happen to have a sample project with that code. Would love to have a working example to play around with.

I see some other links in that post describing that Lua can may also achieve object composition/inheritance. Any good working examples of that as well ?

I’m guessing Lua probably does not support polymorphism.

thanks again.

1 Like

The article also goes into how inheritance can be achieved. I don’t think it goes into how you can call a supermethod, but this can be done by

function ChildClass:method(...)
    ParentClass.method(self, ...)
end

Regarding polymorphism, since Lua has very weak type checking, you can just override the definition of a method. I don’t think I can give better or more concise examples than the article, but if you want to see some of my code just send me a pm :smile:

1 Like