Basically I need a hacky solution so that when I do
object:Foo()
it will run the Foo function but if I do
print(object.Foo)
or
object.Foo += 1
then it understands that I’m looking for a variable and not the function Foo.
Is that possible?
Basically I need a hacky solution so that when I do
object:Foo()
it will run the Foo function but if I do
print(object.Foo)
or
object.Foo += 1
then it understands that I’m looking for a variable and not the function Foo.
Is that possible?
There is the __call metamethod that you could use to get close to what you’re asking but I don’t see how you would get all of what you’re asking with that.
It does beg the question why you want to do this in the first place as it seems a little unnecessary.
Call is only used when you do
object() not when you do object:Foo()
Don’t question my methods.
Just make object.Foo
a metatable and add the behavior you want, and make foo
a local function to make the metatable structure less of a mess(so on __call
it runs the local foo
function and returns it).
I need the reverse. All the functions are part of the metatable and all variables part of object.
EDIT: Actually scrap that, there’s functions in object too. But no variables in metatable atleast (if that helps)
To elaborate further on what I said:
local function createAttribute(func, value)
local attributeMt = {
__call = func
}
return setmetatable({
Value=value
}, attributeMt)
end
local testTable = {}
testTable.Foo = createAttribute(
function()
print("Called Foo")
end,
25
)
print(testTable:Foo()) -- >>> Called Foo
print(testTable.Foo.Value)-- >>> 25
I think this is the closest that you can get. The issue being that testTable.Foo
will refer the the encapsulated table that enables testTable:Foo()
to work.
Thanks for the code! But I think in this case it would just be easier to have a new table in testTable called Values.
and do
print(testTable.Values.Foo) instead.
It’s actually possible if the variable is a table!
BaseClass.__call = function(child, object, ...)
local meta = getmetatable(object)
meta[child.Name](object, ...)
end
So basically I have
If you try to do object:Open() then it will run the __call function on object.Open (the table variable), which will redirect your request to the function instead.
Doesn’t work for variables other than table, but hey atleast it’s something!
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.