Jump to content

[OOP] Lua private fields


Piorun

Recommended Posts

I have this code

  
Items = {} 
Items.__index = Items 
  
function Items.new(name) 
    local self = setmetatable({},Items) 
    self.name = name 
    return self 
end 

I want to make field name to be private (only accessible by class, not globally). How?

Link to comment
  • MTA Team

You could make a local variable in your class file and save the instance/object data inside it. The disadvantage is that you have to access the data through that variable in every function/method.

  
Items = {} 
local ItemsMetatable = { __index = Items } 
local ItemsData = {} 
  
function Items.new(name) 
    local data = {} 
    data.name = name 
     
    local object = {} 
    -- object.__data = data -- Can be accessed in other files 
    setmetatable(object, ItemsMetatable) 
  
    ItemsData[object] = data 
     
    return object 
end 
  
function Items:getName() 
    return ItemsData[self].name 
    -- OR: self.__data.name (unsafe) 
end 
  

Link to comment

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
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...