I have a pretty mind-bending setup right now. I have a regular function that returns a table with functions in it under keys "string" and "number":
function defGeneric()
local function funcNumber(a)
return 2*a^2
end
local function funcString(a)
return a.." - test"
end
local returnTable={}
returnTable["number"]=funcNumber
returnTable["string"]=funcString
return returnTable
end
And that works fine. But what I want to do now is make the table that this function returns callable. To illustrate, let's say we have v=defGeneric()
. Specifically:
- If
v
is called with a stringstr
, return the result ofv["string"](str)
- If
v
is called with a numbern
, return the result ofv["number"](n)
This is obviously a job for metatables, so I can (in my function) add the code to set a metatable:
local metaTable = {
__call = function (...) -- "call" event handler
return
end
}
setmetatable(returnTable,metaTable)
But I don't know what I would put after that return statement. I don't think I can reference returnTable, because this table will be called like so:
v=defGeneric()
v("test")
And I need to reference v
's "string" function (there certainly could be multiple defGeneric() tables in one program).
I think the answer here might be some self
trick but I can't wrap my head around how. How do I reference a metatable's table from the metatable?
__call = function(t,x) return t[type(x)](x) end
- Egor Skriptunoff