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

How can I make my Metatable square given numbers?

I made this Metatable and used the __pow Metamethod, but my numbers aren't being squared. How can I make my Metatable square given numbers? Any and all help is appreciated.

local metatable = {
__pow = function(t)
	local squares = {}
	for key, value in pairs(t) do
		squares[key] = value
	end
	return squares
end	
}

table2 = setmetatable({2,3,4}, metatable)
print(table.concat(table2, "; "))

2 comments

0

put it in a code block so we can read it better.

0

Edited to fix formatting

1 answer

✓ Accepted answer

There are two issues in your code.

The first is that the __pow metamethod is only called when you use the exponentation operator (^) on the table. Since you're not doing this, the function is never called.

Secondly, even if the function was called, it doesn't do anything to change the numbers.

The complete code is here:

local metatable = { 
	__pow = function(t, power) -- Notice the extra argument, 'power'. This is the second value.
		local squares = {} 
		for key, value in pairs(t) do 
			squares[key] = value^power -- We set the number to value^power here.
		end 
		return squares 
	end 
}

table2 = setmetatable({2,3,4}, metatable)
print(table.concat(table2^2, "; ")) -- We also use the power operator to call the __pow metamethod.

Hopefully this does what you are trying to achieve.

(Also, as the comment says, you should put your code in a code block next time)

1 comment

0

Thanks mate!

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