Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Changing values within a userdata created with newproxy?

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

✓ Accepted answer

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.

1 comment

0

Thanks! Tt worked, and i'll keep that in mind.

This discussion is preserved as it was. New answers, comments, and votes are closed.