Skip to content

Writing Scripts

Berke edited this page Jun 23, 2026 · 2 revisions

Lua Script Examples

This page contains practical Lua script examples using the engine scripting API.

All scripts support the following lifecycle functions:

Start()
Update(deltaTime)

1. Basic Lifecycle Example

This example demonstrates when Start and Update are called.

function Start()
    -- Called once when the script is initialized
    Debug.Print("start gets called in the first frame")
end

function Update(deltaTime)
    -- Called every frame
    Debug.Print("update gets called every frame")
end

2. WASD Movement (Rigidbody)

This example moves an entity using keyboard input and a Rigidbody component.

-- Movement speed (public variable exposed via "Public")
Public.speed = 5.0

function Start()
    Debug.Print("Player movement script started")
end

function Update(deltaTime)
    local rb = Owner.rigidbody
    if not rb then return end

    local velocity = Vector3(0, 0, 0)

    -- WASD input controls movement direction
    if Input.GetKey("W") then
        velocity = velocity + Vector3(0, 0, -1)
    end

    if Input.GetKey("S") then
        velocity = velocity + Vector3(0, 0, 1)
    end

    if Input.GetKey("A") then
        velocity = velocity + Vector3(-1, 0, 0)
    end

    if Input.GetKey("D") then
        velocity = velocity + Vector3(1, 0, 0)
    end

    -- Normalize direction so diagonal movement isn't faster
    if velocity:length() > 0 then
        velocity = velocity:normalized()
    end

    -- Apply movement using physics
    rb.velocity = Vector3(
        velocity.x * Public.speed,
        rb.velocity.y,
        velocity.z * Public.speed
    )
end

3. Health / Damage System

This example shows a simple damage system using a public variable.

-- Public variable shared across scripts / inspector
Public.health = 100

function Start()
    Debug.Print("Health system initialized")
end

function Update(deltaTime)
    if Public.health <= 0 then
        Debug.Print("Entity died")
    end
end

-- Custom function callable from other scripts
function TakeDamage(amount)
    Public.health = Public.health - amount

    Debug.Print("Took damage:", amount, "Current HP:", Public.health)

    if Public.health <= 0 then
        Debug.Print("Dead")
    end
end

Notes

  • Public is a shared global table between scripts
  • Owner refers to the entity this script is attached to
  • Update(deltaTime) receives frame time from GameTime::deltaTime
  • Components are accessed safely (may be nil)

Clone this wiki locally