Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Changing values within a userdata created with newproxy?

Asked by
Troxure 87
5 years ago

I'm messing around trying to create a humanoid, and I can't seem to change the values in the userdata created with newproxy.

local HumanoidObjects = {
    Health = 100; -- By default
    HealthRegenRate = 1 -- Per second
};
function CreateHumanoid(Player)
    local Hum = newproxy(true);
    local Data = getmetatable(Hum);
    Data.__index = HumanoidObjects;
    return Hum;
end

--[[ ]]

local Player = game.Players.LocalPlayer;
local Humanoid = CreateHumanoid(Player);

print(Humanoid.Health); -- Prints 100
Humanoid.Health = 10; -- Gives an error saying "attempt to index local 'Humanoid' (a userdata value)"

The error is attempt to index local 'Humanoid' (a userdata value)

It's probably a stupid mistake I made myself and i'm probably not noticing it.

Any help would be appreciated, thanks!

1 answer

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

That is because you've only set a __index field, while Humanoid.Health = 10 invokes the __newindex metamethod (which does not exist in your code). Fix:

local HumanoidObjects = {
    Health = 100,
    HealthRegenRate = 1
}

function CreateHumanoid(Player)
    local Hum = newproxy(true)
    local Data = getmetatable(Hum)
    Data.__index = HumanoidObjects

    --

    function Data:__newindex(key, value)
        -- update entry of HumanoidObject
        HumanoidObjects[key] = value
    end

    --

    return Hum
end

local Player = game.Players.LocalPlayer
local Humanoid = CreateHumanoid(Player)

print(Humanoid.Health)
Humanoid.Health = 10

However

I don't recommend using newproxy for new work. I would just use Lua's dynamic table/metatable functionality. The newproxy function was really only used as a hacky solution for garbage collection callbacks before Lua 5.2.

0
Thanks! Tt worked, and i'll keep that in mind. Troxure 87 — 5y
Ad

Answer this question