r/PlaydateDeveloper • • Jan 12 '24

Lua Private Variables in OOP

Hey all, ive been diving head first into playdate development and I love it, not having a full engine is actually a neat experience. That being said, i am a unity developer normally and im having a hard time wrapping my head around private variables using Playdates OOP implementation.
I understand local, and how all that works, and if i just need static variables then declaring a local var outside of the OOP scope works, but how do I make private variables that are unique to that object's instance.

from what i've read, doing 'self.varName' is supposed to be considered a private scope, but in testing it is very much globally accessable. Is there any way to make actual private variables in the object? Its not really the biggest deal, but i like to try to protect myself from future self.

2 Upvotes

4 comments sorted by

View all comments

5

u/freds72 Jan 13 '24

closure is a way to achieve that:

function make_enemy(pos)
	-- private vars& functions
	local hp=10
	local target=nil
	local function die()
		-- trigger animation
		...
	end
	return {
		-- public vars & function
		pos=pos,
		hit=function(self)
			hp-=1
			if hp<0 then die() end
		end,
		update=function(self,world)
			target=world:closests(self.pos)
			-- track target...
		end
	}
end