简体   繁体   中英

lua serialize array for UDP

I am trying to send a couple of pieces of data over udp via a lua script client to a node.js server.

A string var containing a string is passed to a function. Inside the function an array is being created to add 2 more strings which are id's defined outside of the function to be used on the receiving end to identify the destination of the msg.

I have confirmed that all 3 variables are defined inside the function. I then create the array bossMsg and try to send it via sendto(). I believe this is where the error occurs because I need to serialize the the array, but reading the information I am still unclear on how to do this. Isn't there a simple way to serialize the data so it can be sent via sendto()?

Thanks in advance for any help.

PandaBoss.sendBossMessage = function(msg)

    bossMsg = {msg, g_ID, c_ID}
    socket.try(PandaBoss.UDPSendSocket:sendto(bossMsg, ip, port))

end

sendto sends a datagram to the specified IP address and port number. Datagram is a string with the datagram contents.

So you have to serialize bossMsg to a string. The simplest way is to serialize it to JSON. Something like this:

-- https://github.com/rxi/json.lua
json = require "json"

PandaBoss.sendBossMessage = function(msg)

    bossMsg = {msg, g_ID, c_ID}
    socket.try(PandaBoss.UDPSendSocket:sendto(json.encode(bossMsg), ip, port))

end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM