Discord
Steam
/
Garry's Mod
/
Developers
/
Entity instanc..
Login/Join
Event Log
Entity instanced sub-metatables
0 replies, posted
Search
In This Thread
How might one make a metatable for something like the entity metatable that automatically creates its own instances? Sample Code: [lua] local testClass = {} function testClass.MyFunc(t,x,y,z) print( "MyFunc() Call:",t,x,y,z ) end local testMeta = {} function testMeta.__index(t,k,...) print("Meta Index:",t,k,...) return testClass[k] end function testMeta.__call(t,...) print("Meta Call:",t,...) end local ENTITY = FindMetaTable("Entity") ENTITY.Test = setmetatable({},testMeta) -- Test Entities -- ents.Create() or player:GetEyeTrace().Entity local e1 = testEnt1 local e2 = testEnt2 print( "e1:", e1.Test, "\ne2:", e2.Test ) -- e1: table 0x00ff -- e2: table 0x00ff e1:Test("cats") -- Meta Call: -- table 0x00ff -- Entity( e1 ) -- "cats" -- e2:Test("dogs") -- Meta Call: -- table 0x00ff -- Entity( e2 ) -- "dogs" -- e1.Test:MyFunc("cats") -- Meta Index: -- table 0xffff -- "MyFunc" -- -- MyFunc() Call: -- table 0x01ff -- "cats" -- nil -- nil -- e2.Test:MyFunc("dogs") -- Meta Index: -- table 0xffff -- "MyFunc" -- -- MyFunc() Call: -- table 0x01ff -- "dogs" -- nil -- nil -- e1.Test.x = "cheese" print( e2.Test.x ) -- "cheese" [/lua] The desired outcome is as follows; [lua] local ENTITY = FindMetaTable("Entity") ENTITY.Test = ??? print( "e1:", e1.Test, "\ne2:", e2.Test ) -- e1: table 0x01ff -- e2: table 0x02ff e1:Test("cats") -- Meta Call: -- table 0x01ff -- Entity( e1 ) -- "cats" -- e2:Test("dogs") -- Meta Call: -- table 0x02ff -- Entity( e2 ) -- "dogs" -- e1.Test:MyFunc("cats") -- MyFunc() Call: -- table 0x01ff -- "cats" -- nil -- nil -- e2.Test:MyFunc("dogs") -- MyFunc() Call: -- table 0x02ff -- "dogs" -- nil -- nil -- e1.Test.x = "cheese" print( "e1:", e1.Test.x, "\ne2:", e2.Test.x ) -- e1: "cheese" -- e2: nil [/lua] This is my current solution: [lua] function testMeta.__call(t,x,...) if( !x ) then return t end print( "Meta Call:",t,x,... ) end local function newTestClass(e) e._Test = setmetatable({},testMeta) return e._Test end local ENTITY = FindMetaTable("Entity") ENTITY.Test = function(e,...) return (e._Test or newTestClass(e))(...) end [/lua] However it results in this outcome which is a little different to what i'm aiming for. [lua] local ENTITY = FindMetaTable("Entity") ENTITY.Test = ??? print( "e1:", e1.Test, "\ne2:", e2.Test ) -- e1: function 0x00ff -- e2: function 0x00ff e1:Test("cats") -- Meta Call: -- table 0x01ff -- Entity( e1 ) -- "cats" -- e2:Test("dogs") -- Meta Call: -- table 0x02ff -- Entity( e2 ) -- "dogs" -- e1:Test():MyFunc("cats") -- MyFunc() Call: -- table 0x01ff -- "cats" -- nil -- nil -- e2:Test():MyFunc("dogs") -- MyFunc() Call: -- table 0x02ff -- "dogs" -- nil -- nil -- e1:Test().x = "cheese" print( "e1:", e1:Test().x, "\ne2:", e2:Test()x ) -- e1: "cheese" -- e2: nil [/lua] Any suggestions or ideas?
Sorry, you need to
Log In
to post a reply to this thread.