CC: Tweaked · Explained · Beginner

Lua for CC: Tweaked Explained: Variables, Functions & The os.pullEvent Loop

Writing your own scripts in CC: Tweaked unlocks total control over your Minecraft world, allowing you to automate everything from simple redstone doors to complex Turtle mining arrays. This guide breaks down the essentials of the Lua language—specifically variables, functions, and the critical event-pulling loop—so you can build reliable programs that never freeze or crash.

What you need

  • Computer or Advanced Computer
  • Redstone Dust
  • Lever or Button
  • Redstone Lamp (optional, for testing output)

Step by step

  1. 1Set Up Your Hardware and Create a Script

    Place your Computer or Advanced Computer down in the world. Put a Lever directly on its left side and a Redstone Lamp on its right side to act as our input and output. Right-click the computer to open the CraftOS terminal, type 'edit learn.lua', and press Enter to open the built-in text editor.

    Tip: Advanced Computers allow you to use a color display and click inside the text editor with your mouse, making coding much faster.

  2. 2Store Data with Local Variables

    At the very top of your blank file, type 'local inputSide = "left"' and on the next line type 'local outputSide = "right"'. A variable is simply a named box that holds information—in this case, strings of text representing the sides of the computer. Using variables at the top of your script means if you ever move your Lever to the back, you only have to change the word in one place rather than hunting through hundreds of lines of code.

    Tip: Always put the word 'local' in front of a new variable; this keeps the data restricted to your current program so it doesn't accidentally interfere with other scripts.

  3. 3Bundle Actions into a Function

    Skip a line and type 'local function updateLamp()' then press Enter. Inside this block, we will check our input and toggle our output by typing 'if rs.getInput(inputSide) then rs.setOutput(outputSide, true) else rs.setOutput(outputSide, false) end'. Finally, close the function by typing 'end' on a new line. A function is a reusable recipe of instructions that sits dormant until you explicitly tell the computer to run it.

    Tip: Indent your code inside functions and 'if' statements using the Tab key or spaces so you can easily see where each block begins and ends.

  4. 4Build an Infinite Loop

    Below your function, start a continuous cycle by typing 'while true do' and pressing Enter. This tells the computer to repeat everything inside the loop forever until the computer is turned off or the program is manually terminated. On the next line, call the function you just made by typing 'updateLamp()', which executes your redstone check.

    Tip: Never save and run a 'while true do' loop without adding a pause or event check inside it, or your program will instantly freeze and crash.

  5. 5Yield the Script with os.pullEvent

    Still inside your 'while' loop, directly underneath 'updateLamp()', type 'local event = os.pullEvent("redstone")'. On the final line below that, type 'end' to close your 'while' loop. The os.pullEvent command is the most important part of the script: it tells the computer to go to sleep and stop using server power until a redstone change actually happens in the world.

    Tip: If you leave the parentheses empty like 'os.pullEvent()', the loop will wake up for any event, including key presses, mouse clicks, or timer ticks.

  6. 6Save and Run Your Event-Driven Program

    Press the Control key (Ctrl) on your keyboard to open the bottom menu, ensure 'Save' is highlighted, and press Enter. Press Control again, select 'Exit', and press Enter to return to the terminal. Type 'learn' and press Enter to start your program, then exit the computer screen and flip the Lever on the left side to watch the Redstone Lamp on the right respond instantly.

    Tip: To stop an infinite loop program and get back to the normal command line, hold down Ctrl + T for two seconds until it says 'Terminated'.

How it works

To understand why CC: Tweaked scripts require specific structures, you have to understand how the mod shares processing power with Minecraft. Every computer and Turtle in your world actually runs inside a single thread alongside the main game. Because they share this brain, only one computer can actively run code at any given microsecond. To make it look like dozens of computers are running at once, the mod uses Lua coroutines to rapidly switch between them.

However, a computer will only hand control over to the next computer when its script 'yields' (pauses). If you write a 'while true do' loop that constantly checks a redstone signal without pausing, that single computer hogs the entire system thread. To protect your Minecraft world from lagging to a halt, CC: Tweaked runs a strict watchdog timer. If a script runs for several seconds without yielding, the watchdog forcibly kills the program and throws the infamous 'Too long without yielding' error.

This is the true purpose of os.pullEvent(). Under the hood, everything that happens to a computer—a player pressing a key, a redstone wire changing state, a modem receiving a message, or a timer finishing—is placed into an event queue. When your code hits os.pullEvent(), it tells the mod: 'I am going to yield my turn now; do not wake me up until a new event arrives in my queue.' Even functions like sleep(1) or turtle.forward() work this way internally: they start a timer or a movement action, call os.pullEvent() to yield the script, and wait for the game to send back a completion event.

Common mistakes

  • Running an unyielded loop: Writing a 'while true do' loop that only checks variables or redstone states without calling os.pullEvent() or sleep() inside every single path of the loop. This will always crash your script with a 'Too long without yielding' error.
  • Using sleep() instead of filtering events: Using 'sleep(1)' to check for redstone changes once per second makes your contraptions feel sluggish and wastes processing ticks. Using 'os.pullEvent("redstone")' uses zero power while idle and reacts the exact tick the signal changes.
  • Mismatched 'end' keywords: Every 'function', 'if', 'while', and 'for' statement in Lua must be closed with its own 'end' keyword. If the terminal says 'eof expected' or '<eof>', you either have one too many or one too few 'end' statements.
  • Confusing assignment with comparison: In Lua, a single equals sign (=) puts data into a variable, while a double equals sign (==) checks if two things are the same. Writing 'if event = "redstone" then' will cause a syntax error; it must be 'if event == "redstone" then'.

FAQ

How do I capture extra details from an event, like which key was pressed?

os.pullEvent() actually returns multiple values depending on the event type. You can catch them by listing multiple variables separated by commas, such as: 'local event, key = os.pullEvent("key")'. You can check the built-in 'help events' command in the terminal to see what extra data each event provides.

Why don't I need os.pullEvent() when writing a basic Turtle mining script?

Physical Turtle actions like 'turtle.dig()' and 'turtle.forward()' take time in the real game world to complete, so they automatically call os.pullEvent() behind the scenes while waiting for the movement or block-breaking animation to finish. You only need to manually yield if your Turtle enters a loop where it isn't moving or digging, such as waiting for an inventory to fill up.

How do I make my script start automatically when the world loads or the chunk reloads?

Rename your script to 'startup.lua' using the command 'mv learn.lua startup.lua' in the terminal. Any file named startup in the root folder will automatically execute the moment the computer turns on or its chunk loads.

How can I wait for two different types of events at the same time?

Call 'local event, param1, param2 = os.pullEvent()' with nothing inside the parentheses so it catches every event. Then, use an 'if' and 'elseif' statement right after it to check what the 'event' variable equals (for example, 'if event == "redstone" then' followed by 'elseif event == "char" then').

By combining local variables, reusable functions, and an os.pullEvent loop, you can write clean, responsive CC: Tweaked programs that automate your base without ever crashing or lagging the server.

More CC: Tweaked guides

CC: Tweaked · Getting startedCC: Tweaked Getting Started Guide: First Computer, CraftOS & PastebinCC: Tweaked brings fully programmable computers into your Minecraft world, allowing you to automate almost any task using the Lua programming language. In this guide, you will learn how to craft your first computer, navigate the CraftOS terminal, write a simple script, and download community-made programs straight into your game. Mastering these foundational skills is the essential first step before moving on to autonomous mining turtles and complex base networks.Beginner7 steps
CC: Tweaked · PowerTurtle Fuel & Progression Guide: From Basic Turtles to Infinite Lava RefuelingTurtles in CC: Tweaked are powerful mobile robots, but they cannot move a single block without fuel. In this guide, you will learn how the internal Turtle fuel economy operates, how to upgrade from basic gray models to high-capacity Advanced Turtles, and how to program a self-sustaining Nether lava refueling loop.Beginner7 steps
CC: Tweaked · AutomationHow to Automate Strip Mining & Quarries with Mining TurtlesManual mining is one of the most time-consuming tasks in survival Minecraft, often taking hours away from complex base building and automation. With CC: Tweaked, you can deploy programmable Mining Turtles to carve out massive quarries and strip mines completely hands-free. This guide will walk you through crafting a Mining Turtle, setting up an automated fueling and chest-dumping station, and running both built-in and custom Lua mining scripts.Intermediate8 steps
CC: Tweaked · ExplainedPeripherals & Wired Networks Explained: Wrapping, Modems & Networking CablesIn CC: Tweaked, a standalone Computer can only do so much on its own; its real power comes from controlling external blocks known as peripherals. This guide will teach you how to connect your Computer to adjacent and distant machines—like Monitors, Speakers, and Chests—using Wired Modems, Networking Cables, and the Lua peripheral API. Mastering wired networks allows you to manage an entire base's inventory and automation from one central terminal.Intermediate8 steps
CC: Tweaked · Setup guideHow to Build a CC: Tweaked Storage Network & Auto-Crafting SystemIn this advanced guide, you will build a centralized item storage network and an on-demand auto-crafting system using CC: Tweaked's Wired Modems, Advanced Computers, and Crafty Turtles. By leveraging the native inventory peripheral methods in Lua, you can create a zero-RF digital storage solution that rivals dedicated logistics mods while giving you total programmable control over every item slot.Advanced8 steps
CC: Tweaked · Setup guideHow to Build an Interactive Touchscreen Monitor Dashboard for Base ControlIn this guide, you will build a dynamic touchscreen dashboard using CC: Tweaked to monitor your base's energy and fluid storage while toggling generators with a single tap. Centralizing your base controls onto an interactive graphical screen eliminates messy redstone wiring and prevents catastrophic power outages by giving you real-time data at a glance.Intermediate7 steps