I'm trying to understand how metatables work and this is my first time trying to use pcall .

local tabl = {pig=15,foo=25}
local mt = {
	__index = function(self, key)
		error(key.." doesn't exist in this table")
	end,
	__newindex = function(self,key,value)
		error("You can't make a new value for this table")
	end
}
setmetatable(tabl,mt)

local success, message = pcall(print(tabl.piggy))
if success then print(message) end

I'm not really sure why the last 2 lines don't work, instead it actually errors and stops the script. Im either using pcall wrong or it just doesn't work for errors inside metamethods? It was based on this:

function BadPrint()
    ppppprint("Hi Mom!") -- This will error.
end
 
success, message = pcall(BadPrint)
if success then
    -- Stuff
else 
    print("An error occurred: "..message)
end

EDIT: I just realised that i was checking if it's succesfull. (genius) I changed that but it still does the same thing since it never actually gets to check..

4 comments

0

:)

0

):

0

You need to call a function when using a pcall.

0

isn't print() a function? and the __index function happens aswell.