Like2D Logo Like2D
← Back to Docs

Modules

Like2D provides module-based APIs using table prefixes: net.*, json.*, tilemap.*, and particle.*.

Networking (net.*)

Built-in TCP + UDP networking library for multiplayer games, chat systems, lobbies, and real-time sync. Uses native OS sockets with a background I/O thread. All events are delivered via callbacks: onNetConnect, onNetMessage, onNetDisconnect.

net.createServer(port)

Starts a TCP server listening on the given port. Incoming connections trigger onNetConnect(peerId, ip, port).

net.createServer(8080)

net.connect(host, port)

Connects to a remote TCP server as a client. Returns a peer ID for sending data.

local server = net.connect("127.0.0.1", 8080)

net.send(peerId, data)

Sends a string message to a specific TCP peer.

net.sendAll(data)

Broadcasts a string message to all connected TCP peers.

net.createUDP(port)

Binds a UDP socket on the given port for receiving datagrams.

net.sendUDP(ip, port, data)

Sends a UDP datagram to the specified address. No connection needed.

net.close()

Closes all TCP and UDP connections and stops the network thread.

net.getPeerCount()

Returns the number of currently connected TCP peers.

net.getPeerIP(peerId)

Returns the IP address of a connected TCP peer.

net.sendToAllExcept(excludePeerId, data)

Sends a message to all connected peers EXCEPT one.

net.disconnect(peerId, reason?)

Forcefully disconnects a peer with an optional reason string.

net.broadcastUDP(port, data)

Sends a UDP broadcast to all machines on the local network. Used for LAN game discovery.

net.httpGet(url)

Performs a synchronous HTTP GET request. Returns a table with status, body, and error fields.

local resp = net.httpGet("http://api.example.com/leaderboard")
if resp.status == 200 then
    local data = json.decode(resp.body)
    for i, entry in ipairs(data) do
        print(entry.name .. ": " .. entry.score)
    end
end

net.httpPost(url, body, contentType?)

Performs a synchronous HTTP POST request. contentType defaults to "application/json".

net.setPeerData(peerId, key, value) / net.getPeerData(peerId, key)

Store and retrieve custom metadata for connected peers.

net.getStats()

Returns a table with network statistics: {bytesSent, bytesReceived, packetsSent, packetsRecv, peerCount, uptime}.

net.setKeepalive(interval, timeout)

Configures automatic disconnection of idle peers.

Network Callbacks

function onNetConnect(peerId, ip, port)
    print("Peer " .. peerId .. " connected from " .. ip)
end

function onNetMessage(peerId, data, ip, port)
    print("Message from " .. ip .. ": " .. data)
end

function onNetDisconnect(peerId, reason)
    print("Peer " .. peerId .. " disconnected: " .. reason)
end

JSON Module (json.*)

json.load(filename)

Loads JSON file, returns table and error.

local data, err = json.load("settings.json")

json.save(filename, table)

Saves table to JSON file.

local ok, err = json.save("save.json", {score = 100})

json.encode(table)

Converts table to JSON string.

json.decode(string)

Parses JSON string into table.

TileMap (tilemap.*)

Built-in tilemap system for rendering 2D tile-based levels. Uses a tileset image and a grid of tile IDs.

tilemap.create(tileset, tileW, tileH, cols, rows)

Creates a new tilemap table with an empty grid. The tileset image must be loaded first with loadImage().

loadImage("tileset.png")
local map = tilemap.create("tileset.png", 32, 32, 20, 15)

tilemap.draw(map, x, y, alpha?)

Renders the entire tilemap at the given screen position. One call draws all tiles.

tilemap.setTile(map, row, col, tileId)

Sets a tile at the given grid position. Tile ID 0 means empty (not drawn).

tilemap.getTile(map, row, col)

Returns the tile ID at the given grid position.

tilemap.fill(map, row, col, w, h, tileId)

Fills a rectangular area of the map with a single tile ID.

tilemap.fill(map, 10, 0, 10, 5, 2)

TileMap Example

local map

function onInit()
    setWindowSize(640, 480)
    loadImage("tileset.png")
    map = tilemap.create("tileset.png", 32, 32, 20, 15)
    tilemap.fill(map, 0, 0, 20, 15, 0)  -- Fill with grass
    -- Add wall border
    for col = 0, 19 do
        tilemap.setTile(map, 0, col, 1)
        tilemap.setTile(map, 14, col, 1)
    end
end

function onDraw()
    clearScreen(0, 0, 0)
    tilemap.draw(map, 0, 0)
end

Particle System (particle.*)

High-performance C++ particle effects for explosions, fire, smoke, rain, snow, and more. Supports thousands of particles at 60fps.

particle.create(config)

Creates a new particle system and returns an integer ID.

Config Table Fields:

Built-in Presets: "explosion", "fire", "smoke", "rain", "snow", "magic", "sparkle", "confetti"

particle.update(id, dt)

Updates the particle simulation. Call once per frame in onUpdate().

particle.draw(id)

Renders all alive particles. Call once per frame in onDraw().

particle.destroy(id)

Removes a particle system and frees its memory.

particle.burst(id, count)

Instantly spawns count particles at the emitter position.

particle.setPosition(id, x, y)

Moves the emitter to a new position.

particle.setEmitting(id, bool)

Start or stop particle emission.

particle.setRate(id, rate)

Changes the emission rate at runtime.

particle.getCount(id)

Returns the number of currently alive particles.

particle.clearAll()

Destroys all active particle systems.

particle.setGravity(id, gravity)

Changes the gravity of a particle system at runtime.

particle.setWind(id, x, y)

Applies a constant wind force to all particles.

particle.setBounce(id, enabled, bounceY, damping)

Toggles ground bounce for particles.

particle.setLifetime(id, lifetime)

Changes the lifetime for newly spawned particles.

particle.getConfig(id)

Returns a table with the current configuration.

particle.registerPreset(name, configFn)

Register a custom preset that can be used with preset = "name".

particle.registerPreset("neon_burst", function(config)
    return {
        rate = 0, oneShot = true,
        speedMin = 80, speedMax = 250,
        spread = 360, lifetime = 1.2, gravity = 0, drag = 3,
        startColor = {0, 255, 200, 255},
        endColor = {0, 100, 255, 0},
        additive = true, shape = "circle",
        maxParticles = 400
    }
end)

local neon = particle.create({ x = 400, y = 300, preset = "neon_burst" })
particle.burst(neon, 300)

Particle Example

local fire, rain

function onInit()
    fire = particle.create({ x = 400, y = 300, preset = "fire" })
    rain = particle.create({ x = 400, y = -10, preset = "rain" })
end

function onUpdate(dt)
    particle.update(fire, dt)
    particle.update(rain, dt)
end

function onDraw()
    clearScreen(20, 20, 30)
    particle.draw(fire)
    particle.draw(rain)
end