Calling functions after assigning objects to players using pl:SetVar("name", default)
3 replies, posted
So, I'm trying to call this function Test() inside Upgrades, but it always returns nil. However, when I create a local object I have no issue with calling the function.
This works just fine:
[CODE]local upgrade = PlayerUpgrades:Create(pl)
upgrade:Test()[/CODE]
This throws an "attempt to call method 'Test' (a nil value)"
[CODE]pl:SetVar("Upgrades", PlayerUpgrades:Create(pl))
pl:GetVar("Upgrades", -1):Test()[/CODE]
The Class:
[CODE]PlayerUpgrades = {}
PlayerUpgrades.__index = PlayerUpgrades
function PlayerUpgrades:Create(pl)
local Upgrades = {
HealthLevel = 0,
HealthInitialCost = 10,
HealthIncrementCost = 10
}
setmetatable(Upgrades, PlayerUpgrades)
return Upgrades
end
function PlayerUpgrades:Test()
return "wtf"
end
[/CODE]
Any idea how to fix this?
I'm sorry to bug you guys with this, but I've been staring at my screen for so long, trying to find the solution, and now my eyes are strained.
The solution is probably something very simple and fundamental that I missed in the tutorials. :/
You're not using your pl variable at all in your Create function. Could you outline what you're trying to accomplish? Your metatable logic is seemingly self referencing and I'm not sure what you're trying to achieve.
[QUOTE=code_gs;52302709]You're not using your pl variable at all in your Create function. Could you outline what you're trying to accomplish? Your metatable logic is seemingly self referencing and I'm not sure what you're trying to achieve.[/QUOTE]
Sorry. Please ignore the fact that I didn't use the player entity in the constructor. It's going to be implemented later for updating on spawning in or changing teams.
I'm trying to attach a PlayerUpgrades object to the player using:
pl:SetVar("Upgrades", PlayerUpgrades:Create(pl))
What I want to be able to do is call functions from this "Upgrades" object that is based entirely on the individual player.
E.G.
pl:GetVar("Upgrades", -1):Test()
Or, if I implement an UpgradeHealth() method.
pl:GetVar("Upgrades", -1):UpgradeHealth()
My goal is to attach functions to this object that can be called after getting the object from the entity using GetVar
I don't think you should be using SetVar and GetVar. It's a lot more cleaner to just write
[lua]ply.Upgrades = PlayerUpgrades:Create(ply)[/lua]
Maybe you didn't know you could do that, but you can.
Anyways, your code works for me.
[lua]do
PlayerUpgrades = {}
PlayerUpgrades.__index = PlayerUpgrades
function PlayerUpgrades:Create(pl)
local Upgrades = {
HealthLevel = 0,
HealthInitialCost = 10,
HealthIncrementCost = 10
}
setmetatable(Upgrades, PlayerUpgrades)
return Upgrades
end
function PlayerUpgrades:Test()
return "wtf"
end
end
local pl = Entity(1)
pl:SetVar("Upgrades", PlayerUpgrades:Create(pl))
print(pl:GetVar("Upgrades", -1):Test())[/lua]
It properly prints "wtf"
Sorry, you need to Log In to post a reply to this thread.