LUA OOP Clarification

Started by
0 comments, last by ddn3 14 years, 2 months ago

        --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!!
Advertisement
the function new should be something like this.

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


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

This topic is closed to new replies.

Advertisement