Skip to content

Instantly share code, notes, and snippets.

@nonchip
Last active April 7, 2016 10:52
Show Gist options
  • Save nonchip/4067612ea56ba85969238798078b3c57 to your computer and use it in GitHub Desktop.
Save nonchip/4067612ea56ba85969238798078b3c57 to your computer and use it in GitHub Desktop.
kinda IPC like wrapping system for moonscript classes. might come in handy for nmoonlib
class IPC
dispatch: (name,...)=> -- call this on incoming calls
--print "dispatching: ",name,...
rawget(@@.__base, name) @, ...
call: (name, ...)=>
--print "calling: ",name,...
error "IPC.call: overload this to do outgoing calls"
client: (...)=>
old_mt=getmetatable @
b=@@.__base
inst=@
new_mt={
__index: (key)=>
if v = rawget inst, key
return v
if v = type(old_mt.__index) == "table" and old_mt.__index[key]
return v
if v = type(old_mt.__index) == "function" and old_mt.__index inst, key
return v
if b["get_"..key]
return b.call inst, "get_"..key
if b["call_"..key]
return (...) -> b.call inst, "call_"..key, ...
return b[key]
__newindex: (key,value)=>
if b["set_"..key]
return b.call inst, "set_"..key, value
if v = b["setnew"] and b.call inst, "setnew", key, value
return v
if type(old_mt.__newindex) == "function"
return old_mt.__newindex inst, key, value
return rawset inst, key, value
}
return setmetatable {__clientargs:{...}}, new_mt
class DummyIPC extends IPC
call: (name, ...)=>
-- you could instead send some network message here, that's received by a server then calling `instance\dispatch` on their side
print "DummyIPC.call:", name, ...
ret={@dispatch name, ...}
print "DummyIPC.call returned:", unpack ret
unpack ret
class Test extends DummyIPC
get_a: => @b
set_a: (v)=> @b=v
call_say: => print "yep."
new: ()=>
@b=5
it=Test!
print "value: ", it.b
ic=it\client!
print "get: ", ic.a
print "set"
ic.a=3
print "get: ", ic.a
print "call:"
ic.say!
print "direct:", ic\call "get_a"
print "fake: ", ic\dispatch "get_a"
print "value: ", it.b
expected_result=[[
value: 5
DummyIPC.call: get_a
DummyIPC.call returned: 5
get: 5
set
DummyIPC.call: set_a 3
DummyIPC.call returned:
DummyIPC.call: get_a
DummyIPC.call returned: 3
get: 3
call:
DummyIPC.call: call_say
yep.
DummyIPC.call returned:
DummyIPC.call: get_a
DummyIPC.call returned: 3
direct: 3
fake: 3
value: 3
]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment