What does the _call metamethod do, and how can I use it in scripts?

I’ve finally decided to learn about metatables and metamethods in lua, and so far with every metamethod I’ve been able to use it accordingly, but _call is different. Not only do I not know what it can be used for, but I don’t actually know how to fire the metamethod. The documentation says, “Fires when the table is called like a function, … is the arguments that were passed.”

Can someone explain this to me?
Here’s what I’ve tried so far:

local mytable = {5,10,15,20}
local mymt = {
	__index = function(table, index)
		print('['..tostring(table)..']No data at index '..tostring(index)..", but was called anyways. Defaulting to 0.")
		return 0
	end,
	__call = function(table, args)
		return args
	end
}

(edit) Even though it might not be useful, I still find it pretty cool nonetheless.

1 Like

It would be fired if you called the table, which means mymt()

What it means is that you call the table like a function. When you do, __call metamethod is invoked and then you can decide what to do when it is invoked.

local myTable = {}

setmetatable(myTable, {
   __call = function(t, ...) print("Called table, passed args: " .. (...) )  end
})

myTable("yes") --> Called table, passed args: yes
7 Likes

Ah, thank you. I must’ve been setting it wrong.