diff --git a/ew_api_example/module.lua b/ew_api_example/module.lua index d21f6647..0cc0d1b7 100644 --- a/ew_api_example/module.lua +++ b/ew_api_example/module.lua @@ -1,8 +1,24 @@ +local ew_api = dofile_once("mods/quant.ew/files/api/ew_api.lua") + +-- Needs a unique, but preferably short identifier. +local rpc = ew_api.new_rpc_namespace("api_example") + +-- Make the next rpc be delivered reliably. +-- This means that it will be called exactly once (unless a disconnection happens), and will be ordered the same way. +-- E. g. if you call rpc.rpc1(), rpc.rpc1(), rpc.rpc2() that are reliable, they will get called in the same order on other clients. +rpc.opts_reliable() +-- This rpc will also get called locally. +rpc.opts_everywhere() +function rpc.send_hi() + GamePrint("Hi from "..ew_api.rpc_player_data().name) +end + local module = {} function module.on_world_update() if GameGetFrameNum() % 60 == 0 then GamePrint("Hi from api example!") + rpc.send_hi() end end diff --git a/quant.ew/files/api/ew_api.lua b/quant.ew/files/api/ew_api.lua new file mode 100644 index 00000000..67698c41 --- /dev/null +++ b/quant.ew/files/api/ew_api.lua @@ -0,0 +1,11 @@ +local ew_api = {} + +-- Creates an rpc namespace. See ew_api_example for how to use it. +ew_api.new_rpc_namespace = net.new_rpc_namespace_with_id + +-- In rpc, returns player_data of a peer who called that rpc. +function ew_api.rpc_player_data() + return ctx.rpc_player_data +end + +return ew_api \ No newline at end of file diff --git a/quant.ew/files/core/net.lua b/quant.ew/files/core/net.lua index ab0baa43..83a7fd18 100644 --- a/quant.ew/files/core/net.lua +++ b/quant.ew/files/core/net.lua @@ -67,6 +67,11 @@ local rpc_meta = { __newindex = function (t, k, v) table.insert(rpc_inner.rpcs, v) local index = #rpc_inner.rpcs + if t._ew_id ~= nil then + index = t._ew_id..t._ew_index + t._ew_index = t._ew_index + 1 + print("Created API rpc: "..index) + end local reliable = rpc_inner.opts.reliable == true local everywhere = rpc_inner.opts.everywhere == true rawset(t, k, function(...) @@ -97,6 +102,14 @@ function net.new_rpc_namespace() return ret end +function net.new_rpc_namespace_with_id(id) + local ret = {} + ret._ew_id = id + ret._ew_index = 0 + setmetatable(ret, rpc_meta) + return ret +end + function net.init() local ready = false local addr = os.getenv("NP_NOITA_ADDR") or "127.0.0.1:21251"