Jump to content

[OOP] Variable returns nil\Class definition


Recommended Posts

I have always been struggling with OOP, I thought I might have understood, but no.

It's very simple. I want something like: Missions.name to return the name of the said index. The table output runs just fine, but once I want to use the variable type, I get nil.

What am I missing?

_Missions = { 
--sabotage 
    { 
        name="sabotage", 
        short="sabotage", 
        isElite = 1, 
        minPly = 5, 
        maxPly = 10 
    }, 
    --Resupply 
    { 
        name="Resupply", 
        short="resupply", 
        isElite = 0, 
        minPly = 1, 
        maxPly = 5 
    }, 
    --Fortify 
    { 
        name="Fortify", 
        short="fortify", 
        isElite = 0, 
        minPly = 1, 
        maxPly = 5 
    }, 
    --Grand Theft Auto 
    { 
        name="Grand Theft Auto", 
        short="gta", 
        isElite = 0, 
        minPly = 1, 
        maxPly = 4 
    } 
} 
  
addEventHandler("onResourceStart", resourceRoot,  
    function() 
        for i in ipairs(_Missions) do 
            _Mission = Element.create("Mission") 
            _Mission.setID(_Mission, i) 
            _Mission.name = _Missions[i].name 
            _Mission.short = _Missions[i].short 
            _Mission.minPly = _Missions[i].minPly 
            _Mission.maxPly = _Missions[i].maxPly 
            outputServerLog(_Mission.name) 
        end 
    end 
    ) 

Link to comment

Problem is in your ipairs statement.

for [key,] value in ipairs 

If you only specify 1 variable, it will be the value (In your case it is the actual Lua table), not the index number

addEventHandler("onResourceStart", resourceRoot, 
    function() 
        for i,v in ipairs(_Missions) do 
            _Mission = Element.create("Mission") 
            _Mission.id = i --Changing the 'id' attribute is just the same as using _Mission.setID(_Mission, …) or _Mission:setID(…) where … is the actual ID string. 
            _Mission:setData("name", v.name) --You can't set custom attributes at this very stage of MTA's OOP, use element data instead 
            _Mission:setData("short", v.short) 
            _Mission:setData("minPly", v.minPly) 
            _Mission:setData("maxPly", v.maxPly) 
            outputServerLog(i.name) 
        end 
    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...