Lua#
This guide describes how to install the Lua client, and the features it provides. The Client API Reference describes each function and class.
Installing the Library#
The library can be found on LuaRocks or downloaded from GitHub. It runs on Lua 5.1 to 5.4 and LuaJIT.
To install it and its dependencies using luarocks:
luarocks install krpc
Connecting to the Server#
The game must be running with the server started. The Server Plugin in the getting started guide shows how to install and start it.
The client connects over TCP/IP or over a local socket. Each server in the server window uses one protocol, and accepts connections over that protocol only. Pick the protocol when you add the server, and connect with the matching function.
Note
A server with “Auto-accept new clients” turned off answers only once the player approves the
connection in game. The connection fails after 5 seconds by default. Pass false as the
handshake_timeout to wait indefinitely for the player.
Over TCP/IP#
Select “Protobuf over TCP/IP” as the server’s protocol. connect() connects to it, and
returns a Connection. You make every call through this object. The following connects
to a server with the default settings, address 127.0.0.1 and port 50000, and prints its version:
local krpc = require 'krpc'
local conn = krpc.connect()
print(conn.krpc.get_status().version)
connect() also takes a name for the connection, and the address and port of the server.
These match the address and port shown in the server window. The name appears in the server window
in the game:
local krpc = require 'krpc'
local conn = krpc.connect('My Example Program', '192.168.1.10', 1000)
print(conn.krpc.get_status().version)
TCP/IP works over a network, so your program can run on a different machine from the game.
Over a Local Socket#
Select “Protobuf over local socket” as the server’s protocol. connect_local() connects
to it, and returns a Connection as connect() does. The following connects
to a server with the default settings, at the default socket path for your platform, and prints its
version:
local krpc = require 'krpc'
local conn = krpc.connect_local('My Example Program')
print(conn.krpc.get_status().version)
connect_local() also takes a path, for a server with another socket path. The path
matches the one shown in the server window.
A local socket works only on the machine running the game. It has lower overhead than TCP/IP, so it is faster.
Note
A local socket needs luasocket’s socket.unix module, which luasocket builds on Linux and
macOS. On Windows, connect with connect() instead.
Closing the Connection#
close() closes a connection:
local krpc = require 'krpc'
local conn = krpc.connect('My Example Program')
print(conn.krpc.get_status().version)
conn:close()
A connection you do not close stays open until the garbage collector collects it, or your program exits.
Calling Remote Procedures#
The server provides procedures for your program to call, grouped into services.
The following gets the active vessel from active_vessel, an object
of type Vessel. It sets the vessel’s name, then prints its altitude:
local krpc = require 'krpc'
local conn = krpc.connect()
local vessel = conn.space_center.active_vessel
vessel.name = 'My Vessel'
local flight_info = vessel:flight()
print(flight_info.mean_altitude)
Each service is a field of the connection, such as conn.space_center for the SpaceCenter
service. A property is a field, as in vessel.name. Call a method of an object with :, as
in vessel:flight(), and a procedure of a service with ., as in
conn.krpc.get_status().
Handling Errors#
A procedure that fails on the server raises a Lua error in your program. The following catches the
error from loading a save that does not exist, using pcall:
local krpc = require 'krpc'
local conn = krpc.connect()
local ok, err = pcall(conn.space_center.load, 'missing')
if not ok then
print('Failed to load the save: ' .. err)
end
The error is an object, which tostring and .. turn into its message. Its class says what
failed, and krpc.RemoteError:class_of(err) matches every error of the client’s own:
A procedure that fails on the server raises a
krpc.ServerError. Itsserviceandnamefields name the server’s exception, such asKRPCandArgumentException.A failed connection attempt raises a
krpc.ConnectionError. When the server refuses the connection, itsstatusfield names the status it gave, such asDENIED. When the server ends the connection, itsreasonfield names the reason, such asSERVER_STOPPED.A call made once the connection has closed or failed raises a
krpc.ConnectionError.A value that fails to decode raises a
krpc.EncodingError.An argument the client rejects raises a string.
Values#
Procedures take and return Lua values, such as number, string and Penlight’s List,
Set and Map. A null is nil, or Types.none as described below. The services also
define their own types:
A class is a remote object, described below.
A structure is a value with a field for each field of the structure.
An enumeration value is a value of the enumeration, such as
conn.space_center.MapFilterType.debris.
Flags Enumerations#
A flags enumeration, such as MapFilterType, holds any combination of its
values. You combine values with union, and test for one with contains:
local krpc = require 'krpc'
local conn = krpc.connect()
local MapFilterType = conn.space_center.MapFilterType
-- Show only probes and ships in map mode
conn.space_center.map_filter =
MapFilterType.probes:union(MapFilterType.ships)
-- Check whether map mode shows debris
local filter = conn.space_center.map_filter
print(filter:contains(MapFilterType.debris))
-- Show debris as well
conn.space_center.map_filter = filter:union(MapFilterType.debris)
intersection and difference give the other combinations of two values.
Null Values#
A procedure that can return null returns nil. The following prints the name of the target
vessel, if there is one, then clears the target:
local krpc = require 'krpc'
local conn = krpc.connect()
local space_center = conn.space_center
-- The target vessel is nil when nothing is targeted
local target = space_center.target_vessel
if target then
print(target.name)
end
-- Assigning nil clears the target
space_center.target_vessel = nil
A nil argument leaves the argument out, and the parameter takes its default. The arguments
after it are still passed. The following launches a vessel with the default crew, and passes
false for the parameter after it:
local krpc = require 'krpc'
local conn = krpc.connect()
-- Launch with the default crew, without recovering the vessel on the pad
conn.space_center.launch_vessel('VAB', 'My Rocket', 'LaunchPad', nil, false)
At a parameter with no default, a nil argument is null if the parameter can be null. Otherwise
it raises an error.
A Lua table cannot hold nil, so a null in a list, tuple, dictionary or structure is
Types.none:
local Types = require 'krpc.types'
local values = {1, Types.none, 3}
print(values[2] == Types.none)
Pass Types.none as an argument for a null at a parameter whose default
is not null.
Remote Objects#
Many procedures return an object identifying something in the game, such as a vessel or a part. The object holds no copy of the game’s state. It is just a reference to it. Each call through it reads the game as it is now:
local krpc = require 'krpc'
local socket = require 'socket'
local conn = krpc.connect()
local vessel = conn.space_center.active_vessel
local flight_info = vessel:flight()
-- Each read gets the current altitude from the game
print(flight_info.mean_altitude)
socket.sleep(1)
print(flight_info.mean_altitude)
-- Two objects for the same vessel are equal
print(vessel == conn.space_center.active_vessel)
Two objects for the same thing in the game compare equal with ==. Objects are also ordered
with <, so a list of them can be sorted.
Once the thing an object identifies is destroyed, such as a part that explodes, each call through
it raises an error naming KRPC.ObjectDestroyedException.
An object for a vessel or a part keeps working when you load a save, quickload or revert, and then reads the loaded game. Other objects depend on what they identify. A maneuver node, for example, is destroyed by a load.
A vessel far from the active vessel is unloaded, and the game keeps no parts for it. The vessel
itself reads normally, but a call on one of its parts raises an error naming
KRPC.ObjectNotLoadedException. The part works again once the vessel comes back into range.
See also
Object Lifetime describes how each kind of object behaves in more detail.
Calling Methods#
You call a method on an object of its class, with a colon. A static method needs no object, and you call it on the class itself with a dot. Reach the class through the connection’s service:
local krpc = require 'krpc'
local conn = krpc.connect()
local vessel = conn.space_center.active_vessel
local frame = vessel.orbit.body.reference_frame
local Orbit = conn.space_center.Orbit
-- Call a method on an object
print(vessel:position(frame))
-- Call a static method on the class
print(Orbit.reference_plane_direction(frame))
The call runs on the connection the class is reached through. Called through an object, a static method runs on the object’s connection.
Server Side Functions#
A server side function runs inside the game. You build it in your program with the expression API, and the client sends it to the server, which runs it there. The following reads the vessel’s altitude and speed together:
local krpc = require 'krpc'
local conn = krpc.connect()
local vessel = conn.space_center.active_vessel
local flight = vessel:flight(vessel.orbit.body.reference_frame)
-- Get the remote procedure calls as messages, so they can be passed to the
-- server
local mean_altitude_call = conn:get_call(flight.get_mean_altitude, flight)
local speed_call = conn:get_call(flight.get_speed, flight)
-- Build a function that reads the altitude and the speed
local Expression = conn.krpc.Expression
local expr = Expression.create_tuple({
Expression.call(mean_altitude_call),
Expression.call(speed_call)
})
-- Run the function once, so both values come from the same physics tick
local value = conn:run(expr)
print(string.format('Altitude: %.1f m, speed: %.1f m/s',
value[1], value[2]))
get_call() returns the call a procedure makes, as a message for
call() to embed in the function. A property is read through its getter,
such as flight.get_speed, with the object as the first argument.
get_call_template() names a procedure through its class, with no object or
arguments, for call_with_arguments() to supply each argument, as in
Functions and Collections. The Expression API in the
server side functions guide describes how to build functions.
Running a Function#
run() runs a function once, and returns its value. The server runs the whole
function within one physics tick, so every value it reads comes from the same moment in the game.
In the example, the altitude and the speed are consistent with each other, which two separate calls
cannot guarantee.
A function takes arguments through its parameters. The following compiles a function ahead of its first run, then passes it an argument:
local krpc = require 'krpc'
local conn = krpc.connect()
local Expression = conn.krpc.Expression
-- Build a function that doubles its parameter
local x = Expression.parameter('x', conn.krpc.Type.double())
local func = conn:compile(Expression.lambda(
{x}, Expression.multiply(x, Expression.constant_double(2))))
print('Result: ' .. conn:run(func, 21))
compile() makes the first run as fast as later ones.
Streams and Events#
The Lua client has no streams or events. Read a value by calling its procedure in a loop instead.
Deprecated Members#
A member of a service can be deprecated, when a newer member replaces it. A deprecated member still works, but may be removed in a future release, so move to its replacement.
The API reference marks it as deprecated, and names the replacement. Using it writes a warning naming the replacement to standard error, once per member on a connection.
Service Stubs#
The Lua client has no pre-generated service stubs. When you connect, it builds every service from the service definitions the server sends. The services match the server you connect to, whatever its version, including services added by other mods.
Client API Reference#
-
krpc.connect(
name?:string,
address?:string,
port?:number,
handshake_timeout?:number|false
):krpc.Connection# Connects to a kRPC server, and returns a
Connection.- Parameters:
name – A name for the connection, shown in the server window in the game. Defaults to
''.address – The address of the server, as a host name or an IP address. Defaults to
'127.0.0.1'.port – The port of the server. Defaults to 50000.
handshake_timeout – How many seconds to wait for the server to accept the connection. Defaults to 5.
falsewaits indefinitely, such as for a server that asks the player to approve each connection.
Raises an error if the connection fails or the server refuses it, and for a timeout that is not positive.
-
krpc.connect_local(
name?:string,
path?:string,
handshake_timeout?:number|false
):krpc.Connection# Connects to a kRPC server on the same machine over a local socket, and returns a
Connection. The server must use the local socket protocol.This needs luasocket’s
socket.unixmodule, which luasocket builds on Linux and macOS.- Parameters:
name – A name for the connection, shown in the server window in the game. Defaults to
''.path – The path of the server’s socket, shown in the server window in the game. Defaults to the path the server uses unless it was configured with another.
handshake_timeout – As for
connect().
Raises an error as
connect()does, ifsocket.unixis not available, and if nopathis given and the default path cannot be found.
- class krpc.RemoteError#
The base of every error the client raises of its own, a
pl.classclass.RemoteError:class_of(err)checks whether a value is one.- message#
What failed, followed by the message of the cause, if there is one.
- cause#
The error that caused this one, or
nil.
- class krpc.ConnectionError#
Raised when connecting fails, and by each call once the connection has closed or failed. A subclass of
krpc.RemoteError.- status#
The status the server refused the connection with, such as
'DENIED', ornil.
- reason#
The reason the server gave for ending the connection, such as
'SERVER_STOPPED', ornil.
- class krpc.ServerError#
Raised for an error from the server. A subclass of
krpc.RemoteError.- service#
The service of the server’s exception, such as
'KRPC', ornil.
- name#
The name of the server’s exception, such as
'ArgumentException', ornil.
- class krpc.EncodingError#
Raised for a value that fails to decode. A subclass of
krpc.RemoteError.
-
krpc.get_object_id(obj):
number# The identifier of a remote object on the server, e.g. to pass to
constant_object(). Raises an error if the object isnilorTypes.none.- Parameters:
obj – The remote object.
- class krpc.Connection#
A connection to the server, with a field for each of the server’s services. Obtain one by calling
connect()orconnect_local().- close()#
Closes the connection. Closing a connection that is already closed does nothing.
-
get_call(procedure:
function, ...):table# The call a procedure of a service or a class makes with the given arguments, as a
KRPC.ProcedureCallmessage forcall(). A property is read through its getter,get_<name>, and set through its setter,set_<name>, each with the object or the service as the first argument.Raises an error if a service’s property is not given the service.
-
get_call_template(procedure:
function):table# The call template of a procedure of a service or a class, a
KRPC.ProcedureCallmessage that names the procedure and carries no arguments, forcall_with_arguments()to supply each one. The procedure is reached through its class or service, such asconn.space_center.Engine.get_has_fuel. The procedure itself, passed where a call is expected, is converted to its call template.
-
compile(func:
KRPC.Expression):KRPC.Expression# Compiles a server side function on the server, so that its first run is as fast as later ones, and returns the function.
-
run(func:
KRPC.Expression, ...):any# Runs a server side function within a single physics tick, and returns its value. The arguments are passed to the function’s parameters, with
nilorTypes.nonefor a null. Returnsnilfor a function with no value, and for a null value.Raises an error if the number of arguments differs from the number of parameters, or an argument does not match its parameter.
- krpc.Types.none#
The value that stands for null in a list, tuple, dictionary or structure, where
nilcannot go, and in an argument whose default is not null. Load it withlocal Types = require 'krpc.types', and test for it with==.
Numeric Limits#
The krpc.limits module names the extremes of the numeric types kRPC carries over the wire.
A service can declare one of these limits as a parameter’s default value, and it is then
documented as the constant here.
The minimum of an unsigned type is 0, so it has no constant.
From Lua 5.3 on, a 64-bit value is an exact integer. Lua has no unsigned integer type. A
uint64 above \(2^{63} - 1\) wraps to a negative integer, so
UINT64_MAX is -1. math.ult compares two such values.
Note
In Lua 5.1, 5.2 and LuaJIT every number is a double, which holds an integer exactly up to
\(2^{53}\). SINT64_MAX and UINT64_MAX round up
to \(2^{63}\) and \(2^{64}\). A 64-bit value from the server arrives as the nearest
double.
- krpc.limits.DOUBLE_MAX#
- krpc.limits.DOUBLE_LOWEST#
The largest and most negative finite 64-bit float.
- krpc.limits.SINT32_MAX#
- krpc.limits.SINT32_MIN#
The largest and most negative 32-bit signed integer.
- krpc.limits.SINT64_MAX#
- krpc.limits.SINT64_MIN#
The largest and most negative 64-bit signed integer.
- krpc.limits.UINT32_MAX#
The largest 32-bit unsigned integer.
- krpc.limits.UINT64_MAX#
The largest 64-bit unsigned integer.
Service API Reference#
Server