Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Moonscript

Learn Moonscript - 10 Code Examples & CST Typing Practice Test

MoonScript is a high-level, dynamic programming language that compiles to Lua. It provides syntactic sugar, cleaner syntax, and modern language features like classes, comprehensions, and pattern matching, while maintaining full compatibility with Lua runtime.

View all 10 Moonscript code examples →
MoonScript Counter and Theme ToggleMoonScript Random Number GeneratorMoonScript Todo ListMoonScript StopwatchMoonScript Temperature ConverterMoonScript Dice RollerMoonScript Countdown TimerMoonScript Name GreetingMoonScript Prime CheckerMoonScript Shopping Cart

Learn MOONSCRIPT with Real Code Examples

Updated Nov 21, 2025

Explain

MoonScript lets developers write Lua programs with less boilerplate and a more expressive syntax.

It preserves Lua’s performance and interoperability while adding modern features for readability and maintainability.

Widely used in game development, scripting, and projects where Lua is popular (e.g., Love2D, Roblox).

Core Features

Compile-time conversion to Lua

Modern syntax with indentation-based blocks

Anonymous functions and closures

Table literals and comprehensions

Pattern matching for tables

Basic Concepts Overview

Variables and tables

Functions and anonymous functions

Classes and inheritance

List comprehensions

Destructuring assignments

Project Structure

src/ - MoonScript source files

build/ - compiled Lua output

tests/ - unit tests

libs/ - external Lua dependencies

docs/ - project documentation

Building Workflow

Write `.moon` source files

Compile using `moonc`

Run generated Lua code with Lua interpreter

Debug using Lua runtime or print statements

Integrate with Lua modules or external libraries

Difficulty Use Cases

Beginner: basic scripts with variables and functions

Intermediate: table comprehensions and loops

Advanced: class hierarchies and inheritance

Expert: large-scale projects with Lua interop

Enterprise: embedding in complex Lua-based applications

Comparisons

Higher-level than Lua syntax

More readable than Lua for complex scripts

Compiles to Lua like TypeScript to JavaScript

Less mature tooling than Lua

Better for scripting and rapid prototyping

Versioning Timeline

2012 - Initial release

2013 - Community growth and tooling

2015 - Stable compiler with standard library

2018 - Integration with game engines popularized

2025 - Actively maintained with Lua 5.4 support

Glossary

Table: Lua’s main data structure

Class: MoonScript object abstraction

Comprehension: concise loop-based expression

Destructuring: assign multiple values at once

Function: callable block of code

Installation Setup

Install Lua runtime (5.1+ recommended)

Install MoonScript via LuaRocks (`luarocks install moonscript`)

Verify installation with `moonc --version`

Use MoonScript compiler (`moonc`) to compile .moon files to Lua

Optional IDE plugins for syntax highlighting

Environment Setup

Install Lua runtime

Install MoonScript via LuaRocks

Set PATH for `moonc` CLI

Optional IDE/editor MoonScript plugin

Test compilation and execution

Config Files

moonc.lua configuration

.moon files as source

Compiled Lua output in build/

Project-specific Lua modules

Documentation and notes

Cli Commands

moonc file.moon - compile to Lua

moonc --watch src/ - auto-compile changes

lua file.lua - run compiled Lua

luarocks install moonscript - install MoonScript

moonc --version - check compiler version

Internationalization

UTF-8 support

Works with global Lua modules

Compatible with multi-language strings

No locale restrictions

Community examples worldwide

Accessibility

Cross-platform via Lua runtime

Open-source and MIT licensed

Lightweight compiler

Readable syntax for beginners

Works in text editors and IDEs

Ui Styling

Terminal output via `print`

Text-based logging

Integration with game engine rendering

No native GUI in MoonScript

Visual output handled by Lua host

State Management

Tables for mutable state

Class instances for object state

Local and global variables

Function closures

Interop with Lua state when needed

Data Management

Table creation and manipulation

List and table comprehensions

Class properties and methods

Interfacing with Lua modules

Serialization via Lua tables

Architecture

MoonScript source code

MoonScript compiler

Generated Lua code

Lua runtime execution

Optional integration with Lua libraries

Rendering Model

Parse MoonScript source

Convert to Lua syntax

Generate `.lua` files

Run via Lua interpreter

Optional runtime checks

Architectural Patterns

Source-to-source compilation

Class-based abstractions

Table and function composition

Indentation-driven code blocks

Hybrid Lua/MoonScript codebases

Real World Architectures

Love2D games

Roblox scripts

Embedded Lua scripting

Rapid prototyping of Lua applications

Lua-based plugin ecosystems

Design Principles

Readable, concise syntax

Compile-to-Lua transparency

Maintain Lua compatibility

Enable modern programming constructs

Lightweight and fast compilation

Scalability Guide

Modularize code into classes and modules

Use comprehensions to reduce boilerplate

Separate logic from Lua host code

Optimize table usage for performance

Automate compilation in CI/CD

Migration Guide

Move Lua scripts to MoonScript for readability

Refactor repetitive Lua code to MoonScript comprehensions

Integrate MoonScript with Lua-based projects

Compile MoonScript before deployment

Maintain Lua interop for mixed environments

Performance Notes

MoonScript adds no runtime overhead

Compiled Lua is as fast as hand-written Lua

Performance depends on Lua version/runtime

Use LuaJIT for high-performance execution

Avoid unnecessary table allocations in performance-critical code

Security Notes

MoonScript inherits Lua’s security considerations

Sanitize inputs if running untrusted scripts

Avoid dynamic code execution unless necessary

Validate Lua modules before use

Use proper sandboxing in embedded environments

Monitoring Analytics

Log performance in Lua runtime

Measure table allocations

Debug compiled Lua output

Use print or logging modules

Monitor memory for large scripts

Code Quality

Use consistent indentation

Comment modules and functions

Prefer classes for reusable code

Leverage comprehensions for clarity

Keep Lua interop minimal and explicit

Practical Examples

Defining a class with methods

List comprehension for table filtering

Pattern matching on tables

Creating modules with MoonScript

Embedding MoonScript in Love2D game

Troubleshooting

Check generated Lua code for syntax issues

Ensure correct Lua version is used

Watch indentation carefully (MoonScript is indentation-sensitive)

Use verbose compilation mode for debugging

Test MoonScript functions with small Lua scripts

Testing Guide

Unit test compiled Lua output

Validate MoonScript syntax using compiler

Check function behavior in Lua runtime

Test class hierarchies and inheritance

Verify table comprehensions and destructuring

Deployment Options

Distribute compiled Lua code

Embed MoonScript in Lua applications

Use in game engines (Love2D, Roblox)

Automate compilation in CI/CD

Package as Lua modules

Tools Ecosystem

MoonScript compiler (`moonc`)

Lua runtime (Lua 5.1+)

LuaRocks for dependency management

IDE/editor plugins for MoonScript

Love2D and Roblox engines

Integrations

Lua modules and libraries

Game engines like Love2D

Embedded Lua scripting in apps

CI pipelines for compiling MoonScript

Testing frameworks for Lua/MoonScript

Productivity Tips

Write small functions for clarity

Compile frequently to catch syntax errors

Use comprehensions instead of loops

Integrate with Lua testing frameworks

Leverage IDE snippets and syntax highlighting

Challenges

Compile and debug complex MoonScript code

Integrate with Lua libraries

Use comprehensions effectively

Write reusable classes and modules

Embed MoonScript in game projects

Learning Path

Learn Lua basics

Study MoonScript syntax and constructs

Practice compiling and running `.moon` files

Use classes, comprehensions, and destructuring

Integrate with Lua projects or game engines

Skill Improvement Plan

Week 1: Variables, functions, tables

Week 2: Loops, comprehensions, conditionals

Week 3: Classes and inheritance

Week 4: Lua interoperability

Week 5: Building small projects/games

Interview Questions

What is MoonScript and how does it relate to Lua?

How do you define a class in MoonScript?

Explain comprehensions in MoonScript.

How do you compile MoonScript to Lua?

What are the main benefits of MoonScript over plain Lua?

Cheat Sheet

x = 10 - variable assignment

-> - function shorthand

class Name ... - class definition

[v*2 for v in values] - table comprehension

require 'module' - load Lua module

Books

Programming in MoonScript

Mastering Lua and MoonScript

Game Scripting with MoonScript

Lua for Developers

Lua Patterns and Best Practices

Tutorials

MoonScript basics

Classes and inheritance

Table comprehensions

Lua interoperability

Building small games with MoonScript

Official Docs

MoonScript official repository

MoonScript compiler documentation

MoonScript syntax guide

Community Links

MoonScript GitHub

Love2D community forums

LuaRocks community

Stack Overflow MoonScript questions

Game dev and scripting forums

Community Support

MoonScript GitHub repository

Love2D forums

LuaRocks community

Lua and game development communities

Stack Overflow MoonScript questions

Monetization

Game development with Love2D

Custom scripting plugins

Educational programming tutorials

Embedded Lua applications

Freelance MoonScript development

Future Roadmap

Better IDE/editor support

Enhanced integration with Lua 5.4+ features

Expanded community libraries

Performance optimizations in compiler

Improved tooling for game development

When Not To Use

Pure Lua projects without MoonScript syntax preference

Large-scale enterprise applications without Lua expertise

Environments with strict Lua version constraints

When IDE/editor support is critical

Projects requiring immediate Lua code modification by others

Final Summary

MoonScript modernizes Lua syntax without sacrificing performance.

Ideal for scripting, rapid prototyping, and game development.

Compiles to Lua, ensuring full compatibility.

Lightweight, expressive, and developer-friendly.

Faq

Is MoonScript free?

Yes - open-source and MIT licensed.

Can MoonScript run anywhere Lua runs?

Yes, it compiles to standard Lua code.

Is MoonScript faster than Lua?

No, runtime speed is the same; it’s syntax sugar.

Can I mix Lua and MoonScript?

Yes, MoonScript can call Lua and vice versa.

Code Sample Descriptions

1

MoonScript Counter and Theme Toggle

count = 0
isDark = false

updateUI = ->
    print "Counter: #{count}"
    print "Theme: #{if isDark then 'Dark' else 'Light'}"

increment = ->
    count += 1
    updateUI!

decrement = ->
    count -= 1
    updateUI!

reset = ->
    count = 0
    updateUI!

toggleTheme = ->
    isDark = not isDark
    updateUI!

# Simulate actions
updateUI!
increment!
increment!
toggleTheme!
decrement!
reset!

Demonstrates a simple counter with theme toggling using MoonScript variables and functions.

Let’s Try →
2

MoonScript Random Number Generator

generate = ->
    num = math.random 1, 100
    parity = if num % 2 == 0 then 'Even' else 'Odd'
    print "Number: #{num}, #{parity}"

# Simulate actions
generate!
generate!
generate!

Generates a random number and shows if it is odd or even.

Let’s Try →
3

MoonScript Todo List

todos = {}

updateUI = ->
    print "Todo List:"
    for i, task in ipairs todos
        print "#{i}. #{task}"
    print "----------------"

addTask = (task) ->
    table.insert todos, task
    updateUI!

removeTask = (index) ->
    table.remove todos, index
    updateUI!

# Simulate actions
addTask 'Buy milk'
addTask 'Write MoonScript code'
removeTask 1

Maintains a simple todo list with add and remove functions.

Let’s Try →
4

MoonScript Stopwatch

time = 0
running = false

updateUI = ->
    print "Stopwatch: #{time} seconds"

start = ->
    running = true
    print 'Stopwatch started'

stop = ->
    running = false
    print 'Stopwatch stopped'

reset = ->
    time = 0
    updateUI!

# Simulate actions
updateUI!
start!
time += 5
updateUI!
stop!
reset!

Simulates a stopwatch with start, stop, and reset functionality.

Let’s Try →
5

MoonScript Temperature Converter

celsiusToF = (c) -> (c * 9 / 5) + 32
fToCelsius = (f) -> (f - 32) * 5 / 9

updateUI = (temp, scale) ->
    if scale == 'C'
        print "#{temp}°C = #{celsiusToF temp}°F"
    else
        print "#{temp}°F = #{fToCelsius temp}°C"

# Simulate actions
updateUI 25, 'C'
updateUI 77, 'F'

Converts Celsius to Fahrenheit and vice versa.

Let’s Try →
6

MoonScript Dice Roller

rollDice = ->
    result = math.random 1, 6
    print "Rolled: #{result}"

# Simulate actions
rollDice!
rollDice!
rollDice!

Rolls a dice and prints the result.

Let’s Try →
7

MoonScript Countdown Timer

count = 5

updateUI = ->
    print "Countdown: #{count}"

startCountdown = ->
    while count > 0
        updateUI!
        count -= 1
    updateUI!
    print 'Done!'

# Simulate actions
startCountdown!

Counts down from a number to zero.

Let’s Try →
8

MoonScript Name Greeting

greet = (name) ->
    print "Hello, #{name}! Welcome!"

# Simulate actions
greet 'Saurav'
greet 'Alice'
greet 'Bob'

Greets the user with their name.

Let’s Try →
9

MoonScript Prime Checker

isPrime = (n) ->
    return false if n < 2
    for i in [2..math.floor(math.sqrt n)]
        return false if n % i == 0
    true

checkNumber = (num) ->
    print "#{num} is #{if isPrime num then 'Prime' else 'Not Prime'}"

# Simulate actions
checkNumber 7
checkNumber 10
checkNumber 13

Checks if a number is prime.

Let’s Try →
10

MoonScript Shopping Cart

cart = {}
total = 0

updateUI = ->
    print "Cart Items:"
    for item, price in pairs cart
        print "#{item}: $#{price}"
    print "Total: $#{total}"
    print '----------------'

addItem = (item, price) ->
    cart[item] = price
    total += price
    updateUI!

removeItem = (item) ->
    if cart[item]
        total -= cart[item]
        cart[item] = nil
    updateUI!

# Simulate actions
addItem 'Apple', 2
addItem 'Banana', 3
removeItem 'Apple'

Simulates adding and removing items in a shopping cart with total cost.

Let’s Try →

Frequently Asked Questions about Moonscript

What is Moonscript?

MoonScript is a high-level, dynamic programming language that compiles to Lua. It provides syntactic sugar, cleaner syntax, and modern language features like classes, comprehensions, and pattern matching, while maintaining full compatibility with Lua runtime.

What are the primary use cases for Moonscript?

Scripting for games (Love2D, Roblox). Writing concise Lua programs. Rapid prototyping in Lua environments. Embedding in applications with Lua runtime. Creating libraries compatible with Lua

What are the strengths of Moonscript?

Improves code readability over Lua. Maintains full Lua compatibility. Supports modern programming patterns. Lightweight with zero runtime overhead. Ideal for rapid prototyping

What are the limitations of Moonscript?

Dependent on Lua runtime. Smaller community than Lua itself. Debugging maps to generated Lua code. Limited IDE/editor support. Less suitable for large enterprise codebases without Lua experience

How can I practice Moonscript typing speed?

CodeSpeedTest offers 10+ real Moonscript code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.