Why are these values nil?

function DataMetatable.new(name, save)
	if type(name) ~= "string" then return end
	local self = setmetatable({}, DataMetatable)
	self.Name = name
	print(self.Name)
	for _type, value in pairs(save) do
		self[_type] = value
	end
	return self
end

self.Name and self[_type] are nil, why?

1 Like

Both printed for me as non-nil values, there must be something wrong with the second argument supplied or something.

DataMetatable = {}

 function DataMetatable.new(name, save)
	if type(name) ~= "string" then return end
	local self = setmetatable({}, DataMetatable)
	self.Name = name
	print(self.Name)
	for _type, value in pairs(save) do
		self[_type] = value print(self[_type])
	end
	return self
end
 DataMetatable.new("str", {a = "b", b = "c"})

How did you infer they’re nil?

1 Like
local DataMetatable = {
	__newindex = function(_table, key, value)
		print(key, value)
		if key == "leaderstats" then
			pcall(function()
				Players[_table.Name][key].Value = value 
			end)
		end
	end
}

function DataMetatable.new(name, save)
	if type(name) ~= "string" then return end
	local self = setmetatable({}, DataMetatable)
	self.Name = name
	print(self.Name)
	for _type, value in pairs(save) do
		self[_type] = value
		print(self[_type])
	end
	return self
end

apparently it prints nil when i put in metamethods, do you know why?

1 Like

but that’s not what i’m asking, i’m asking why is it printing nil

You’re overriding the __newindex metamethod, which determines what behavior yourTable[something] = whatever does. Since you aren’t ever actually having the value be set in the __newindex function, it’s still nil.

3 Likes

The reason is because you’re using it unnecessarily but more importantly because __newindex will trigger every time you assign a new index, so unless you set it to return a non-nil value it’ll obviously be not-defined whenever you call t[index] = v.

I’m not sure what the issue is, but try this
EDIT: oh well someone answered it for you

function DataMetatable.new(name, save)
	if type(name) ~= "string" then return end
	local self = {}
	setmetatable(self, DataMetatable)
	self.Name = name
	-- stuff

I have no idea if this would work or not, but give it a try ¯_(ツ)_/¯

1 Like

That will behave identically. setmetatable returns the table it set the metatable of.

3 Likes

it didn’t work (30 characters)

so what do I return in the __newindex?

Return whatever value you need to, I can’t think of what you want.

Or you could just try removing the metamethod and running the desired code separately if you don’t know what to return.