Francisco LumeSkaarf
Francisco LumeSkaarf

Reputation: 23

OOP Help - How do I get this code block to recognize one of its arguments?

I'm learning Lua and how to implement OOP. Trying out a test example of an object seems to return one of the argument of the object as 'null' despite being assigned one.

function Character(Name, Level, Class)   --Constructor
    return {GetName = T.GetName, GetLevel = T.GetLevel, GetClass = T.GetClass}
  end
end
-- Snippets
Player = Character("Bob", 1, "Novice")

When I try printing Player.GetName() it returns null instead of Bob. Where have I gone wrong?

Here is the full code.

Upvotes: 2

Views: 479

Answers (1)

Nifim
Nifim

Reputation: 5021

OOP in Lua takes a bit more than what you have done there, you will want to make use of metatables and upvalues.

-- How you could define your character structure.
local Character = {}

function Character.GetName(self)
  return self.name
end

function Character.new(Name, Level, Class)
  local _meta = {}
  local _private = {}
  _private.name = Name
  _private.level = Level
  _private.class = Class

  _meta.__index = function(t, k) -- This allows access to _private
    return rawget(_private, k) or rawget(Character, k)
  end

  _meta.__newindex = function(t, k, v) -- This prevents the value from being shaded
    if rawget(_private, k) or rawget(Character, k) then
      error("this field is protected")
    else 
      rawset(t, k, v)
    end
  end
  return  setmetatable({}, _meta) --return an empty table with our meta methods implemented 
end

This creates a local table _private when you create a new instance of a Character. That local table is an upvalue to the _meta.__index and it cannot be accessed outside the scope of the Character.new function. _private can be accessed when __index is called because it is an upvalue.

-- How to use the character structure 
player = Character.new("Bob", 10, "Novice")
npc = Character.new("Alice", 11, "Novice")
print(player:GetName())

I use player:GetName(), but in all honesty you can just do player.name as well.

Resources for more on this topic:

http://tutorialspoint.com/lua/lua_metatables.htm

http://lua-users.org/wiki/ObjectOrientationTutorial

Upvotes: 1

Related Questions