Lua
Online Lua Compiler
Your script runs with the standard Lua 5.4 interpreter and its standard library. Output isn’t buffered, so io.write() prompts show before io.read() waits for your input.
Try it aboveHow Lua runs here
- Versions
- Lua 5.4
- Run
lua5.4 main.lua- Limits per run
- 256 MB memory, 15 s of CPU time on half a core, 2 MB of output
- Time
- Up to 10 minutes a run (30 on a paid plan); waits 2 minutes for input (5 on a paid plan)
- Sandbox
- Each run gets its own Linux sandbox with no network access. Text files your program writes next to your code open as new tabs.
A Lua script that reads input
This main.lua reads numbers with io.read("n"), then sorts and summarizes a table:
io.write("How many numbers? ") local n = io.read("n") local nums = {} for i = 1, n do io.write("Number ", i, ": ") nums[i] = io.read("n") end table.sort(nums) local sum = 0 for _, x in ipairs(nums) do sum = sum + x end print("Sorted: " .. table.concat(nums, " ")) print(string.format("Sum: %d, average: %.2f", sum, sum / n)) print("Largest: " .. math.max(table.unpack(nums)))
$ lua5.4 main.lua How many numbers? 4 Number 1: 12 Number 2: 7 Number 3: 30 Number 4: 5 Sorted: 5 7 12 30 Sum: 54, average: 13.50 Largest: 30
Reading input in Lua
- io.read("l") (or plain io.read()) reads a line; io.read("n") reads a number and returns nil if the input isn’t one.
- io.read("n") leaves the line break behind, so a following io.read("l") returns an empty string. Read the leftover line once, or read lines and convert them with tonumber().
- io.read("a") and io.lines() run until the end of input, which this terminal never sends. Read a count first, or stop on an empty line.
What isn’t available here
- LuaRocks and C modules: no luasocket, lfs or cjson. Plain Lua modules work: put utils.lua next to main.lua and load it with require("utils").
- Game APIs. LÖVE (love.graphics), Roblox (game, workspace) and Pico-8 functions don’t exist in plain Lua, and the playground can’t open a window.
Errors you’ll see
- “attempt to perform arithmetic on a nil value (local 'total')” The variable was never given a value, or io.read("n") didn’t find a number.
- “attempt to concatenate a nil value (local 'name')” .. met nil. Use tostring(x), or give a default: name or "".
- “attempt to call a nil value (global 'prnt')” A misspelled function name. Globals are nil until assigned, so typos show up only when the line runs.
Questions
Which Lua version does this use?
Lua 5.4, run with lua5.4 main.lua. It has integers as well as floats: 7 // 2 is 3, and 10 / 2 is 5.0.
How do I read input in Lua?
io.read("n") for a number or io.read("l") for a line. Type the input in the terminal while the script runs.
Can I run LÖVE or Roblox code?
No. Their functions belong to those engines. Plain Lua with the standard library runs here.