KISS-multiplayer icon indicating copy to clipboard operation
KISS-multiplayer copied to clipboard

Lua Events

Open vulcan-dev opened this issue 2 years ago • 0 comments

Instead of using sendLua for everything, I've implemented a basic event system so the server & client can both send and receive events from each other.

Here's some example code, if you press the button on the client, it will trigger an event on the server which will then send data back and add some text to the UI.

Server

hooks.register("setData", "setData", function(clientID, data)
    print("setData: " .. data)
    local player = connections[clientID]
    player:triggerEvent("setData", "Hello World")
end)

Client

local M = {}

local imgui = ui_imgui
local message = nil

local function onUpdate()
    if imgui.Begin("KissMP Events") then
        if message then
            imgui.Text(message)
        end
        if imgui.Button("Send Event") then
            network.trigger_event("setData", "Hello World")
        end
    end
end

if network then
    network.register_event("setData", function(data)
        log("D", "eventTest", "setData event called with data: " .. data)
        message = data
    end)
else
    log("E", "eventTest", "network is nil")
end

M.onUpdate = onUpdate

return M

Note: I had issues with KissMP mounting the test mod so just manually enable it and reload it (via "extensions.reload(modName)" )once you get in the server.

vulcan-dev avatar Feb 03 '23 16:02 vulcan-dev