-
Notifications
You must be signed in to change notification settings - Fork 8
Networking
Networking with computers is made as easy as possible; all communication is done through channels, which are all identified by their own names. Computers are identified by their hostnames, and you can effectively communicate between scripts and computers using these channels (since version 1.8-alpha
).
First off, here's some functions we can use to get information about our own computer:
-
hostname()
returns the hostname of the current computer -
owner()
returns the UUID (as a string) of the owner
We need to create a channel so that other programs and computers can write data to it:
channel = registerChannel("mychannel")
In this case, we named our channel mychannel
. The registerChannel
function returns a channel object, which we can use several functions with:
-
channel:poll()
will poll the data from the channel, reading one of the messages that is in the channel. This function will returnnil
if there is no data to read. -
channel:read()
will read data, just likechannel:poll()
does, but instead of returningnil
when there is no data, it will wait until there is data to read. -
channel:destroy()
will destroy the channel, freeing the channel name to be used again.
note: creating channels with a channel name that is already in use for the current computer will return nil
.
Reading a message would be done like so:
msg = channel:read()
print("message recieved: \"" .. msg .. "\"")
If we wanted to find another computer, we would use the following code:
computer = findComputer("hostname")
Where "hostname"
is the hostname of the computer we're looking for. This findComputer
function will return nil
if the computer can't be found.
The returned computer also has an owner()
and hostname()
function, but it also has a message(string, string)
function. Let's look at it:
computer:message("mychannel", "Hey Joe!")
This is all it takes to send a message to another computer!
heads up: computers can anonymously write to channels that you register, and can impersonate other computers or confuse applications when working with netcode in Lua. If you have a complex application that uses a lot of networking, consider implementing a system to eliminate this issue (be creative!).