Sign in to follow this  
blenderer

LUA OOP Clarification

Recommended Posts

blenderer    100
        --OOP Sandbox

	player = {name, level, class}
	function player:new()
		setmetatable(self)
		self.__index = self
	end
	
	testplayer = player:new()
	testplayer.name = "testplayer" --errors are coming from these lines
	testplayer.level = 80                -- here
	testplayer.class = "Warrior"     --and here
Okay, I have been trying to learn and research how to do basic classes and Object Oriented Programming with LUA, but the guides/references on the web are a bit confusing. I understand why LUA is different than other languages but I am having trouble figuring out syntax and other stuff. All I want to do is create a basic class and create objects out of it. I want to reference stuff like:
print testplayer.name
but I am getting an error in the first code block saying
attempt to index global 'testplayer' (a nil value)
What does this error mean and how do I fix it? Thanks so much in advance!!

Share this post


Link to post
Share on other sites
ddn3    1610
the function new should be something like this.


player = {}
function player :new() -- The constructor
local object = {name, level, class}
setmetatable(object, {
__index = player
})
return object
end




notice that it returns the created object (with the approraite metatable __index set to player);

Now you can create a new player instance and set its memebers using



local inst = player:new();
inst.name="User123";




This should work, this is how it build my classes.

Good Luck!

-ddn

Share this post


Link to post
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

Sign in to follow this