How to implement Static fields and methods in Roblox OOP

Hi all, I was wondering how I could implement static fields and methods inside of my party class. Just like in java, static fields are shared by all classes, and when is value is manipulated, it updates for every instance of a class. On the other hand, static methods can be invoked through the classes declaration, rather than through an instance of a class.

This would be really useful for my party class, as I would like a static variable of an array holding all ongoing parties in the server, shared by each instance of the class. This way each instance of the class can access and read from each element of the array, being able to check for conditions such as, Is a member of my party in another party ?

My party class looks like this:

function party.new(
	map_name, map_spawn, home_spawn, ...)

	local party_members

	local self = { 
		party_id = math.random(0, 10000),
		party_members={} or ...,
		map_name=map_name,
		map_spawn=map_spawn,
		home_spawn=home_spawn
	}
	
	warn("A party has formed [ "..self.party_id.." ] [ "..self.map_name.." ]")
	
	return setmetatable(self, proxy)
end

And for now, I have added a table holding all ongoing parties at the top of the script like this:

party_instances = { }

And I am adding instances of the class by using this statement in the constructor ()
above)

party_instances["Party"..#party_instances+1] = self

  • Is this a good approach ?
  • Should I change this to something else ?

Sorry If I haven’t explained this very well, Its quite hard to explain.

For a slight correction of the meaning of static, it is actually a modifier for sharing variable between objects of the same class.

To actually do this, I usually set a local variable in the global scope and kick it around from either the constructor or any set method. Unless you want to access this variable directly(no get method), try separating the class from the module somehow, and set a module variable for the static ones. As long it is not part of the product, it will be static.

The way you do this is also a valid solution for an equivalent of static.


For this line:

party_instances["Party"..#party_instances+1] = self

I actually set the object into it rather than the properties only, meaning after calling setmetatable.

1 Like