▸ AutoLua Help · 1.0.0 · 2026-06-17
AutoLua Basics What is AutoLua Project Structure Quick Start Feature Overview Import Packages/Classes/Modules Layout Table Lifecycle Callbacks Event Callbacks Lua Language Reference
ScriptApi Automation What is ScriptApi
Input Method InputText(text) RestoreIME()
App Management RunApp(pkg [, activity]) KillApp(pkg) FindApp(pkg) EnumApp(pkg)
Image & Color SetScreenScale(w, h [, scale]) ResetScreenScale() KeepCapture() ReleaseCapture() SnapShot(path) Capture(x1, y1, x2, y2, path [, deg]) GetColor(x, y [, type]) GetColorNum(x1, y1, x2, y2, color, sim) CmpColor(x, y, color, sim) CmpColorEx(cmd, sim) FindColor(x1, y1, x2, y2, color, dir, sim) FindMultiColor(x1, y1, x2, y2, main, offsets, dir, sim)
Touch KeyDown(key) / KeyUp(key) KeyPress(key) Tap(x, y) Swipe(x1, y1, x2, y2 [, ms]) Touch(x, y [, ms]) TouchDown(x, y [, id]) / TouchUp([id]) / TouchMove(x, y [, id, ms])
Helper Functions Delay(ms) IsLandScape() MoveWindow(x, y) Install2Global()
Built-in Functions Built-in Functions概述
Async Task(func, ..., callback) Thread(src, ...) Timer(f, delay, period, ...)
Layout & Views LoadLayout(t [, root])
Script Control StartScript(path [, arg]) StopScript()
Debug Log(...) DumpObj(o) PrintLuaStack([tag])
String Split(text, delimiter) Trim(s)
Number Round(n)
Table DeepCopy(t [, n])
File FileExist(path) FileRead(path) FileWrite(path, str)
System ShowToast(msg) TracePrint(...)
Utility import(name)
Accessibility Service Accessibility Service概述
Service Status IsConnected()
Gestures Click(x, y) LongClick(x, y) Press(x, y, delay) Swipe(x1, y1, x2, y2, ms) GestureSwipe(path, ms)
Find & Interact FindNode(name) FindAndClick(name) FindAndSetText(name, text)
Global Actions PerformBack() PerformHome() PerformRecents() PerformNotifications()
Utility Install2Global()

AutoLua Basics

What is AutoLua

AutoLua is a lightweight Android scripting tool based on LuaJava. Call Java/Android APIs directly from Lua — no compilation required.

Common use cases:

  • UI Automation: simulate taps, swipes, and text input via Accessibility Service
  • Image & Color scripts: screenshot comparison, find image/color, multi-touch
  • Tool development: build UIs with layout tables, call any Android API

Project Structure

Default project structure:

  • init.lua initialization script, runs first on app launch
  • layout.aly UI layout file
  • main.lua main program entry
  • script.lua script entry
  • .alp compressed project file for import/export

Quick Start

Create a Demo project in the app to get started. Example — a button with click handler:

import("android.widget.*")
layout = {
	LinearLayout,
	orientation = "vertical",
	{ Button, text = "点击", id = "btn" },
}
activity.setContentView(loadlayout(layout))
btn.onClick = function(v)
	print("clicked")
end

Feature Overview

Main areas:

  • Home: new project, run script, settings
  • Project List: search, import/export (.alp)
  • Settings: run mode (Normal/Root), permissions (Accessibility/Overlay), auto-start, check updates, help & feedback, about
  • Log Viewer: Settings → View Logs, filter by Lua tag and keyword search
  • Auto Update: checks on startup

Import Packages/Classes/Modules

import() is the core mechanism: wildcard .* imports entire packages (lazy), class name imports a single class, inner classes use $ separator. Return value can be assigned to variables; also supports loading Lua modules.

import("android.widget.*") -- import entire package
import("android.widget.Button") -- import single class
import("android.view.View$OnClickListener") -- inner class

local Btn = import("android.widget.Button") -- assign to variable

Layout Table

loadlayout(t [, root]) parses a layout table into a view tree. id values are auto-injected into the root table (default _G), accessible as global variables.

layout = {
	LinearLayout,
	orientation = "vertical",
	{
		TextView,
		id = "tv",
		text = "Hello",
		textSize = "18sp",
	},
}
activity.setContentView(loadlayout(layout))
print(tv.getText()) -- id auto-injected, no declaration needed

Lifecycle Callbacks

Define these global functions; the app calls them automatically at the corresponding lifecycle stage:

function onCreate() -- app created
	print("onCreate")
end

function onStart() -- app visible
	print("onStart")
end

function onResume() -- app enters foreground
	print("onResume")
end

function onPause() -- app enters background
	print("onPause")
end

function onStop() -- app invisible
	print("onStop")
end

function onDestroy() -- app destroyed
	print("onDestroy")
end

Event Callbacks

Widget events are bound via Lua function assignment, with getter/setter shorthand.

btn.onClick = function(v)
	print(v)
end

btn.onLongClick = function(v)
	return true -- return true = handled
end

Getter/setter shorthand: btn.text = "hello" is equivalent to btn.setText("hello")

Lua Language Reference

ScriptApi Automation

What is ScriptApi

Requires root permission

ScriptApi is a built-in automation module that wraps touch, image/color, key, and input method operations. Global simulation via root — no dependency on Accessibility Service. Complements the Accessibility Service approach.

Import via require("ScriptApi"), or call Install2Global() to inject into the global namespace.

InputText(text)

Switch to AutoLua IME and input text. First call auto-selects as default IME.

InputText("hello")

RestoreIME()

Restore system default IME.

RunApp(pkg [, activity])

Launch the specified app. If activity is omitted, auto-resolves the launch Activity.

RunApp("com.android.settings")

KillApp(pkg)

Force-stop the specified app.

FindApp(pkg)

Check app install and run status.

Return Value

ReturnDescription
-1Not installed
0Installed, not running
1Installed and running
2Running status unknown

EnumApp(pkg)

Enumerate matching package names, space-separated. Supports fuzzy matching; empty string enumerates all installed apps.

Return Value

  • Space-separated package name string (empty if none)

Example

local pkgs = EnumApp("com.tencent")

SetScreenScale(w, h [, scale])

Set the development reference resolution. All subsequent coordinates are auto-scaled to screen ratio.

SetScreenScale(1080, 1920)

ResetScreenScale()

Disable screen scaling, restore actual coordinates.

KeepCapture()

Keep screenshot state; subsequent captures reuse system cache. Pair with ReleaseCapture() to avoid repeated screenshots.

ReleaseCapture()

Release screenshot hold.

SnapShot(path)

Capture full screen and save to file.

SnapShot("/sdcard/screen.png")

Capture(x1, y1, x2, y2, path [, deg])

Capture a rectangular region and save. Pass 0 for screen edge; deg is clockwise rotation count (0-3).

Capture(0, 0, 500, 300, "/sdcard/crop.png")

GetColor(x, y [, type])

Get the pixel color at the specified coordinates.

Parameters

ParameterTypeRequiredDescription
xnumberX coordinate
ynumberY coordinate
typenumber0=hex (default) 1=decimal
local hex = GetColor(100, 200)

GetColorNum(x1, y1, x2, y2, color, sim)

Count pixels matching the specified color within the region. Pass 0 for boundaries.

Return Value

  • 匹配像素数量

CmpColor(x, y, color, sim)

Single-point color compare. Check if the color at coordinates matches. Similarity 0-1 (1 = exact match).

Return Value

  • true match, false no match

Example

CmpColor(100, 200, "0xFF0000", 0.9)

CmpColorEx(cmd, sim)

Multi-point color compare. Check multiple coordinates at once. Format: "x|y|color,...".

Return Value

  • true all match, false any mismatch

Example

CmpColorEx("100|200|0xFF0000,300|400|0x00FF00", 0.9)

FindColor(x1, y1, x2, y2, color, dir, sim)

Find a color within a region. Pass 0 for boundaries; dir=0 = left-to-right, top-to-bottom.

Return Value

ReturnDescription
ret≥0 found, <0 not found
x, yMatch point coordinates

Example

local ret, x, y = FindColor(0, 0, 0, 0, "0xFF0000", 0, 0.9)
if ret >= 0 then
	Tap(x, y)
end

FindMultiColor(x1, y1, x2, y2, main, offsets, dir, sim)

Multi-point color find. Locate the main color first, then verify each offset point. Pass 0 for boundaries.

Parameters

ParameterTypeDescription
x1,y1,x2,y2numberSearch region (0=boundary)
mainstringMain color
offsetsstringOffset string offX|offY|color
dirnumberSearch direction (0/1/2)
simnumberSimilarity 0-1

Return Value

  • x ≥ 0 found, x < 0 not found

Example

FindMultiColor(0, 0, 0, 0, "0xFF0000", "10|0|0x00FF00,-10|0|0x0000FF", 0, 0.9)

KeyDown(key) / KeyUp(key)

Key press / release.

KeyPress(key)

Full key press (down + up).

KeyPress("BACK")
KeyPress("HOME")

Tap(x, y)

Tap at coordinates.

Tap(500, 300)

Swipe(x1, y1, x2, y2 [, ms])

Swipe from start to end. ms defaults to -1 (auto speed).

Swipe(100, 500, 900, 500, 500)

Touch(x, y [, ms])

Hold at coordinates. ms defaults to -1 (hold indefinitely).

Touch(500, 300, 2000)

TouchDown(x, y [, id]) / TouchUp([id]) / TouchMove(x, y [, id, ms])

Multi-touch. id defaults to 0, used to distinguish fingers.

TouchDown(300, 400, 0)
TouchMove(600, 400, 0, 200)
TouchUp(0)

Delay(ms)

Delay in milliseconds. Thread sleeps in Java state to avoid ANR.

Delay(1000)

IsLandScape()

Check screen orientation.

Return Value

  • Landscape returns true, portrait returns false

MoveWindow(x, y)

Move the script floating window to coordinates.

Install2Global()

Inject all ScriptApi functions into the global namespace — no Script. prefix needed afterwards.

local Script = require("ScriptApi")
Script.Install2Global()
Tap(500, 300) -- call directly

Built-in Functions

Built-in Functions概述

Core module, auto-loaded — no manual require needed

Provides async tasks, timers, layout building, string processing, file I/O, debug output and more. All functions are auto-injected into the global namespace — call directly from scripts.

Task(func, ..., callback)

Execute heavy work in a thread pool, callback result on main thread. Supports arguments (boolean/number/string/Java objects). If first arg is a number, it is treated as delay in ms.

Task(function(a, b)
	return a + b
end, 1, 2, print) -- print receives result 3

Task(1000, function()
	print("after 1 second delay")
end)

Thread(src, ...)

Create an independent Lua thread with its own global environment. Cannot directly access external variables; interact with the main thread via call(t, fn) / set(t, k, v).

t = Thread("myscript", arg1, arg2)
call(t, "doWork", data)
set(t, "config", { timeout = 30 })

Timer(f, delay, period, ...)

Periodic timer. delay = initial delay, period = interval in ms. Set t.enabled = false to pause, t.stop() to stop. If f has a run() method, it is called repeatedly.

t = Timer(function()
	print("every second")
end, 0, 1000)
-- t.enabled = false  -- pause
-- t.stop()              -- stop

LoadLayout(t [, root])

Parse layout table into view tree. id injected into root (default _G). Supports .aly layout files.

Parameters

ParameterTypeRequiredDescription
ttable/stringLayout table or .aly filename
roottableid→view mapping table, default _G
layout = { LinearLayout, { TextView, id = "tv", text = "Hi" } }
activity.setContentView(loadlayout(layout))
print(tv.getText())

StartScript(path [, arg])

Floating window only controls scripts launched this way Launch a new script. arg is a string; if arg points to an existing file path, it is auto-read as JSON config.

StartScript("test")
StartScript("test", "hello")
StartScript("test", "/sdcard/config.json") -- auto-detected as JSON

StopScript()

Stop the currently running script.

Log(...)

Output to Logcat with tag "lua". Arguments are auto-joined with spaces. adb logcat -s lua

log("x=", x, "y=", y)

DumpObj(o)

Serialize a Lua object to a readable string. Supports nested tables and circular reference detection.

Return Value

  • Formatted string

Example

print(DumpObj({ a = 1, b = { 2, 3 } }))

PrintLuaStack([tag])

Print the current Lua call stack to Logcat for debugging call paths.

Split(text, delimiter)

Split a string by delimiter, returns an array.

local parts = Split("a,b,c", ",") -- {"a", "b", "c"}

Trim(s)

Remove leading and trailing whitespace.

Trim(" hello ") -- "hello"

Round(n)

Round to nearest integer.

Round(3.6) -- 4

DeepCopy(t [, n])

Deep copy a table. n = max recursion depth (default 3). Handles circular references.

FileExist(path)

Check if file exists, returns boolean.

FileRead(path)

Read entire file contents. Returns nil on failure.

FileWrite(path, str)

Write string to file, overwriting existing content.

ShowToast(msg)

Show an Android Toast message.

ShowToast("Done")

TracePrint(...)

Output to Logcat with arguments joined; includes current filename and line number. adb logcat -s lua

TracePrint("x=", x, "y=", y)

import(name)

Import a Java class/package or Lua module. Wildcard imports are lazy; class name auto-takes the last segment as variable name. See AutoLua Basics → Import Packages/Classes/Modules.

Example

import("android.widget.*")
import("android.widget.Button")

Accessibility Service

Accessibility Service概述

Accessibility function module imported via local AS = require("AccessibilityApi"). Provides node search, gestures, global keys etc. Requires Accessibility Service to be enabled.

IsConnected()

Check if the Accessibility Service is connected.

if AS.IsConnected() then
	AS.Click(500, 300)
end

Click(x, y)

Tap at coordinates.

AS.Click(500, 300)

LongClick(x, y)

Long-press at coordinates.

AS.LongClick(500, 300)

Press(x, y, delay)

Press at coordinates, release after delay ms.

AS.Press(500, 300, 2000)

Swipe(x1, y1, x2, y2, ms)

Swipe from start to end.

AS.Swipe(100, 500, 900, 500, 500)

GestureSwipe(path, ms)

Gesture swipe along a Path.

FindNode(name)

Check if a node exists, returns boolean.

local ok = AS.FindNode("确定")

FindAndClick(name)

Find by text and click. name is a string.

AS.FindAndClick("确定")

FindAndSetText(name, text)

Find an input field by text and set its text.

AS.FindAndSetText("搜索", "关键词")

PerformBack()

Global back key.

PerformHome()

Global Home key.

PerformRecents()

Global Recents key.

PerformNotifications()

Open notification shade.

Install2Global()

Inject all Accessibility Service functions into the global namespace — no AS. prefix needed afterwards.

local AS = require("AccessibilityApi")
AS.Install2Global()
Click(500, 300) -- call directly