Note that this question is about pure Lua. I do not have access to any module or the C side. Additionally, I can not use the IO, the OS or the debug library.
What I’m trying to make is a function that receives, as parameters:
- a number that is an ammount of second
- a callable value
By ‘a callable value’, I mean a value that can be called. This can be:
- a function
- a table with a metatable that allows calling (through a
__callmetamethod)
Here’s an example of a callable table:
local t = {}
setmetatable(t, {
__call = function() print("Hi.") end
})
print(type(t)) --> table
t() --> Hi.
Here’s the function:
function delay(seconds, func)
-- The second parameter is called 'func', but it can be anything that is callable.
coroutine.wrap(function()
wait(seconds) -- This function is defined elsewhere. It waits the ammount of time, in seconds, that it is told to.
func() -- Calls the function/table.
end)()
end
But I have a problem. I want the function to throw an error if the parameter ‘func’ is not callable.
I can check if it is a function. But what if it is a table with a metatable that allows calling?
If the metatable of the table is not protected by a __metatable field, then, I can check the metatable to know if it is callable, but, otherwise, how would I do it?
Note that I have also thought about trying to call the ‘func’ parameter with pcall, to check if it is callable, but to do that, I need to call it prematurely.
Basically, here’s the problem: I need to know if a function/table is callable, but without trying to call it.
In general, if the metatable does not want you to be able to get it (by defining
__metatableto being something special), then you’re not going to get it. Not from Lua.However, if you want to cheat, you can always use
debug.getmetatable, which will return the metatable associated with that object.You don’t have to prematurely call anything with
pcall. Observe: