What is expression 2 programming language? give me a comprehensive example
- User
What is expression 2 programming language? give me a comprehensive example
- Assistant
What Expression 2 actually is
Expression 2 (often written “E2”) is the scripting language used by the Expression Chip in the Wiremod add‑on for Garry’s Mod.
Think of it as a tiny, C‑like, event‑driven language that runs inside an in‑game micro‑controller:• Compiled just‑in‑time to very fast bytecode.
• Sandboxed so you can’t crash the server.
• Provides direct access to Wiremod I/O pins, the physics engine, entities, sounds, holograms, HUD screens, etc.
• Ideal for automation (doors, turrets, elevators), math/logic (A‑Star pathfinding, PID controllers), or purely cosmetic stuff (dynamic holograms, HUDs).Key language characteristics
Data types: number, string, vector, angle, entity, array, table Scopes: functions + global @persist storage that survives re‑compiles Events: first(), tick(), player(), chat(), input(), sound(), etc. I/O: @inputs, @outputs, @outputs, @entity for chip’s owner, @trigger Libraries: holo, egp, string, math, table, http, wirelink …
A comprehensive, annotated example
Below we’ll build a “Smart Door with Keypad & Access Log” to show most core concepts.
Scenario
• One physical keypad (Wiremod Keypad) provides the code entry (0‑9, Clear, Accept).
• A single prop door (or prop that slides/rotates) will open only when the correct PIN is entered.
• Incorrect attempts are logged and broadcast to the owner.
• Owner can change the PIN by looking at the chip and typing “/setpin 1234” in chat.
• An EGP screen on a monitor shows real‑time door status.Hardware hookup
[Keypad] -> [Expression2] -> [Door] -> world [Monitor] <-> (wirelink) [Expression2]Complete E2 file
@name SmartDoor_v1 @inputs Keypad:wirelink Door:entity @outputs DoorState:string @persist CorrectPIN:string Buffer:string Failed:int @persist Screen:wirelink @trigger # ^ we’ll manually select which inputs trigger – see 'runOn...' ############################################################### # INITIALISATION ############################################################### if (first()) { # Default PIN CorrectPIN = "1234" Buffer = "" # what user has typed so far Failed = 0 # Immediately subscribe to events we care about runOnTick(1) # on every server tick runOnChat(1) # listen to chat for /setpin # Find EGP screen once at startup Screen = findByClass("gmod_wire_egp_emitter"):first() if (Screen) { # Simple label definitions Screen:egpClear() Screen:egpText(1, "SMART DOOR", vec2(128,20)) Screen:egpText(2, "Status:", vec2(20,50)) Screen:egpText(3, "CLOSED", vec2(100,50)) Screen:egpText(4, "Attempts:", vec2(20,70)) Screen:egpText(5, "0", vec2(100,70)) } } ############################################################### # TICK EVENT – poll keypad each frame ############################################################### if (tickClk()) { ### 1) Read keys pressed this tick # Keypad outputs: 1..9, 0, Accept (=), Clear (C) for (k = 0, 9) { if (Keypad[k, number]) { appendBuffer(k) } } if (Keypad["Clr", number]) { Buffer = "" } if (Keypad["Ent", number]) { checkPIN() } ### 2) Update Door state string for outside world DoorState = Door:isDoorOpen() ? "OPEN" : "CLOSED" ### 3) Refresh screen text if (Screen) { Screen:egpTextBox(3, DoorState) Screen:egpTextBox(5, Failed:string()) } } ############################################################### # CHAT COMMAND – owner can change the pin ############################################################### if (chatClk(owner())) { msg = owner():lastSaid():lower() if (msg:find("/setpin")) { new = msg:explode(" "):last() if (new:length() >= 3 & new:length() <= 6 & new:isnumber()) { CorrectPIN = new owner():soundPlay(1, 0, "buttons/button17.wav") hint(owner(), "PIN updated to " + new) } else { hint(owner(), "Invalid PIN (3‑6 digits only).") } } } ############################################################### # HELPER FUNCTIONS ############################################################### function void appendBuffer(num) { if (Buffer:length() < 6) { Buffer = Buffer + num } # max 6 digits owner():soundPlay(2, 0, "buttons/button15.wav") } function void checkPIN() { if (Buffer == CorrectPIN) { openDoor() } else { Failed += 1 owner():soundPlay(3, 0, "buttons/button10.wav") hint(owner(), "Wrong PIN! (" + Buffer + ")") } Buffer = "" # reset entry } function void openDoor() { if (!Door:isValid()) { return } Door:propDoorToggle() owner():soundPlay(4, 0, "doors/door_latch3.wav") hint(owner(), "Door toggled successfully.") }What you just saw in action
- Direct Pin Mapping
Keypad:wirelinkexposes each button as a number output we poll every tick. - Events
first(),tickClk(),chatClk(player)are implicit event functions. - runOn…
Lets you enable/disable event callbacks at run‑time, saving performance. - Persistent Variables (@persist)
Survive chip rewires and automatic restarts (so the PIN isn’t forgotten). - Wirelink & EGP
Shows how to talk to other chips (Keypad, Screen) over a virtual bus. - Entity API
Door:propDoorToggle()calls a built‑in helper for most Source Engine doors. - Sound & UI Feedback
Small QoL touches viasoundPlay()and HUDhint().
Tiny cheat‑sheet for new E2 authors
Snippet Purpose runOnTick(1)Enable tickClk()each server frame@persist A B CSave variables across reloads findByClass("<class>")Returns array of entities of that class entity():pos(), :ang()World‑space position / orientation holoCreate(idx, pos, ang)Spawn a hologram (#Wiremod’s 3D sprite) egpText(id,str,pos)Draw 2D text on EGP screen owner(), lastSaid()Reference to player who spawned chip table, arrayComposite data containers httpRequest(url, ...)Yes, you can call web APIs² ²HTTP calls are often disabled on public servers for security.
Where to learn more
• Workshop: “Wiremod” (includes Expression2)
• Wiki: https://github.com/wiremod/wire/wiki/Expression-2
• Discord: discord.gg/wiremod (tons of example contraptions)
• YouTube Tutorials: “Pawl the Pixel” / “Crix” seriesHappy wiring, and remember: fancier logic ≠ heavier physics 😉
- Direct Pin Mapping
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.