• Advertisement
Sign in to follow this  

LUA OOP Clarification

This topic is 2903 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

        --OOP Sandbox

	player = {name, level, class}
	function player:new()
		self.__index = self
	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
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

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();

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

Good Luck!


Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement