📖 古龙精灵 API 参考手册

面向游戏脚本开发者的完整 API 参考文档。涵盖触控模拟、图像识别、OCR 文字识别、YOLO 目标检测、设备控制、网络请求等全部功能。

🚀 概览与快速入门

什么是古龙精灵?

古龙精灵是一个面向游戏脚本开发者的全栈自动化平台。开发者使用 Lua 编写脚本,通过 PC 开发工具调试,最终打包为 APK 部署到 Android 设备上运行。平台提供丰富的 API 用于触控模拟、图像识别、OCR 文字识别、YOLO 目标检测等。

脚本基本结构

每个脚本是一个 Lua 文件,必须包含 main() 函数作为入口点。脚本引擎在加载文件后会自动调用 main()

Lua - 脚本基本结构
-- ============================================================
-- 古龙精灵脚本模板
-- ============================================================

-- 加载子模块
dofile("settings_fields.lua")   -- 设置字段定义
dofile("server_api.lua")        -- 服务器通信模块

-- 全局配置
GAMENAME = "我的游戏脚本"
ACCOUNT_ID = "user_001"

-- 主函数(脚本引擎自动调用)
function main()
    log("脚本开始运行")
    
    -- 获取用户设置
    local auto_fight = get_setting("auto_fight", true)
    
    -- 主循环
    while true do
        if auto_fight then
            tap(500, 800)       -- 点击攻击按钮
            sleep(2000)             -- 等待2秒
        end
        sleep(1000)
    end
end

main()

开发流程

  1. 在 PC 开发工具中编写 Lua 脚本
  2. 使用工具 → 抓取窗口获取坐标、颜色、图片等数据
  3. 在开发工具中连接 Android 设备进行调试
  4. 通过开发者面板上传脚本包
  5. 打包 APK 分发给用户

🎨 UI 控件参考(用户设置面板)

脚本可以在 SCRIPT_SETTINGS_FIELDS 中定义设置字段,这些字段会显示在用户控制面板的"脚本设置"选项卡中。所有控件定义使用 Lua table 格式。

控件结构层级

设置字段支持三层嵌套结构:fold(折叠面板)tab_container(选项卡容器)控件字段

Lua - 完整结构示例
SCRIPT_SETTINGS_FIELDS = {
    {
        key = "section_1",
        label = "战斗设置",
        type = "fold",              -- 折叠面板
        default = true,
        icon = "⚔️",
        fields = {
            {
                type = "tab_container",  -- 选项卡容器
                tabs = {
                    {
                        label = "基础",
                        icon = "❤️",
                        fields = {
                            {key = "auto_fight", label = "自动打怪", type = "bool", default = true, icon = "⚔️"},
                            -- ... 更多控件
                        }
                    },
                }
            }
        },
    },
}

1. ☑️ 布尔开关 (bool)

用于开启/关闭某个功能。必填属性:key, label, type, default。可选属性:icon, description。

属性类型必填说明
keystring唯一标识,脚本中用此 key 读取值
labelstring显示名称
type"bool"控件类型
defaultboolean默认值:true 或 false
iconstring图标(HTML实体编码)
descriptionstring提示文字
示例:基础开关 / 带副标题开关 / 默认关闭开关 / 通知开关 / 调试模式开关
-- 基础开关(默认开启)
{key = "auto_fight", label = "自动打怪", type = "bool", default = true, icon = "⚔️", description = "是否开启自动打怪功能"},

-- 带副标题开关
{key = "auto_pickup", label = "自动拾取", type = "bool", default = true, icon = "📦", description = "是否自动拾取掉落物品"},

-- 默认关闭开关
{key = "auto_sell", label = "自动出售装备", type = "bool", default = false, icon = "💰", description = "是否自动出售背包中的装备"},

-- 通知开关
{key = "enable_notify", label = "启用通知", type = "bool", default = true, icon = "🔔", description = "是否启用任务通知提醒"},

-- 调试模式开关
{key = "debug_mode", label = "调试模式", type = "bool", default = false, icon = "🐛", description = "开启后显示调试信息"},

2. 🔢 数字输入 (number)

用于输入数值。必填属性:key, label, type, default, min, max。可选:step, unit, icon, description。

属性类型必填说明
keystring唯一标识
labelstring显示名称
type"number"控件类型
defaultnumber默认值
minnumber最小值
maxnumber最大值
stepnumber步进值,默认1
unitstring单位(秒、%、分钟等)
iconstring图标
descriptionstring提示文字
示例:基础数字 / 百分比数字 / 时长数字 / 次数数字 / 浮点数
-- 基础数字(带单位)
{key = "fight_interval", label = "打怪间隔", type = "number", default = 5, min = 1, max = 60, step = 1, unit = "秒", icon = "⏱️"},

-- 百分比数字
{key = "hp_threshold", label = "回血阈值", type = "number", default = 30, min = 10, max = 90, step = 5, unit = "%", icon = "❤️"},

-- 时长数字(分钟)
{key = "max_duration", label = "最大时长", type = "number", default = 120, min = 30, max = 1440, step = 10, unit = "分钟"},

-- 次数数字
{key = "max_attempts", label = "最大尝试次数", type = "number", default = 3, min = 1, max = 99, step = 1, unit = "次"},

-- 浮点数(带小数)
{key = "move_speed", label = "移动速度", type = "number", default = 1.5, min = 0.5, max = 5.0, step = 0.1, unit = "倍"},

3. 📝 文本输入 (text)

用于输入文本。必填属性:key, label, type, default。可选:placeholder, password, multiline, icon, description。

属性类型必填说明
keystring唯一标识
labelstring显示名称
type"text"控件类型
defaultstring默认值
placeholderstring占位提示文字
passwordboolean是否为密码输入框
multilineboolean是否多行文本
iconstring图标
descriptionstring提示文字
示例:基础文本 / 密码输入 / 多行文本 / 过滤关键词
-- 基础文本(带占位符)
{key = "target_monster", label = "目标怪物", type = "text", default = "银月贤者", icon = "🎯", placeholder = "输入怪物名称", description = "要自动攻击的怪物名称"},

-- 密码输入
{key = "account_password", label = "账号密码", type = "text", default = "", icon = "🔑", placeholder = "输入密码", password = true, description = "登录密码"},

-- 多行文本
{key = "custom_notice", label = "自定义公告", type = "text", default = "", icon = "📋", multiline = true, placeholder = "输入公告内容..."},

-- 过滤关键词
{key = "filter_keywords", label = "过滤关键词", type = "text", default = "", icon = "🔍", placeholder = "关键词用逗号分隔"},

4. 📋 下拉选择 (select)

用于从预设选项中选择。必填属性:key, label, type, default, options。

属性类型必填说明
keystring唯一标识
labelstring显示名称
type"select"控件类型
defaultstring默认值(对应 option 的 value)
optionstable选项列表:{{value="x", label="显示名"}, ...}
iconstring图标
descriptionstring提示文字
示例:基础下拉 / 地图选择 / 职业选择 / 分辨率选择
-- 基础下拉选择
{key = "difficulty", label = "难度选择", type = "select", default = "normal", icon = "🎮",
 options = {{value = "easy", label = "简单"},{value = "normal", label = "普通"},{value = "hard", label = "困难"},{value = "hell", label = "地狱"}},
 description = "选择打怪难度等级"},

-- 地图选择
{key = "target_map", label = "目标地图", type = "select", default = "map1", icon = "🗺️",
 options = {{value = "map1", label = "新手村"},{value = "map2", label = "幽暗森林"},{value = "map3", label = "冰封雪域"},{value = "map4", label = "火焰山"}}},

-- 职业选择
{key = "class_type", label = "职业选择", type = "select", default = "warrior",
 options = {{value = "warrior", label = "战士"},{value = "mage", label = "法师"},{value = "archer", label = "弓箭手"},{value = "assassin", label = "刺客"}}},

-- 分辨率选择
{key = "resolution", label = "分辨率", type = "select", default = "720p",
 options = {{value = "720p", label = "720x1280"},{value = "1080p", label = "1080x1920"},{value = "2k", label = "1440x2560"}}},
⚠️ 重要提示:中文 key 必须使用方括号语法
如果 key包含中文字符(例如 "difficulty_选择采集物品"),在入口文件中必须使用方括号语法 settings["key"] 来获取值,不能使用点号语法 settings.key
示例:包含中文的 key 用方括号读取
-- ===== 📋 select(下拉选择)=====
-- 读取用户选择的值,用于条件判断
local difficulty_选择采集物品 = settings["difficulty_选择采集物品"] or "wp_流寇"

-- 控件定义
{key = "difficulty_选择采集物品", label = "采集物品", type = "select", default = "normal", icon = "🎮",
 options = {{value = "wp_流寇", label = "流寇"},{value = "wp_煤矿", label = "煤矿"},{value = "wp_铁矿", label = "铁矿"},{value = "wp_伐木场", label = "伐木场"}},
 description = "选择采集物品"},

-- ✅ 正确:使用方括号语法
local val = settings["difficulty_选择采集物品"]
-- ❌ 错误:不能使用点号语法(key含中文时)
-- local val = settings.difficulty_选择采集物品  -- 这会报错!

5. 📦 折叠面板 (fold)

用于将一组控件折叠/展开。必填属性:key, label, type, default, fields。fields 内部可以嵌套 tab_container,tab_container 的 tabs 里才是真正的控件。

属性类型必填说明
keystring唯一标识
labelstring显示名称
type"fold"控件类型
defaultboolean是否默认展开
iconstring图标
descriptionstring提示文字
fieldstable内部控件列表(通常含 tab_container)
fold 完整示例
{
    key = "fight_settings",
    label = "战斗设置",
    type = "fold",
    default = true,
    icon = "⚔️",
    description = "战斗相关设置(可折叠)",
    fields = {
        {
            type = "tab_container",
            tabs = {
                {
                    label = "基础",
                    icon = "⚔️",
                    fields = {
                        {key = "auto_fight", label = "自动打怪", type = "bool", default = true, icon = "⚔️"},
                        {key = "fight_interval", label = "打怪间隔", type = "number", default = 5, min = 1, max = 60, step = 1, unit = "秒"},
                    }
                },
                {
                    label = "高级",
                    icon = "⚙️",
                    fields = {
                        {key = "debug_mode", label = "调试模式", type = "bool", default = false, icon = "🐛"},
                    }
                },
            }
        }
    },
},

6. 📑 选项卡容器 (tab_container)

在折叠面板内部创建多个选项卡,每个选项卡包含一组控件。通常在 fold 的 fields 内部使用。

属性类型必填说明
type"tab_container"固定值
tabstable选项卡列表,每个 tab 有 label, icon, fields

7. 🎨 颜色选择 (color)

示例
-- 颜色选择器
{key = "theme_color", label = "主题颜色", type = "color", default = "#FF5722", icon = "🎨", description = "选择界面主题颜色"},

-- 文字颜色
{key = "text_color", label = "文字颜色", type = "color", default = "#FFFFFF", icon = "✏️"},

📋 入口文件使用示例(完整)

以下示例展示如何在脚本入口文件 main() 中读取所有类型控件的值,并据其控制脚本逻辑。覆盖:bool、number、text、select、date、time、slider、file、multi_select、tag 等全部控件类型。这是实际项目中最核心的模式。

Lua - 入口文件完整示例(全部控件读取 + 使用)
-- ============================================================
-- 第一步:加载设置字段定义文件
-- ============================================================
dofile("settings_fields.lua")

-- ============================================================
-- 第二步:main() 入口函数 - 获取并读取所有控件值
-- ============================================================
function main()
    log("==================================================")
    log("  古龙精灵 - 使用示例")

    -- ===== 获取用户设置 =====
    local settings = get_user_settings()

    -- ===== ☑️ bool(布尔开关)=====
    -- 中文key必须用方括号 settings["key"]
    local auto_fight = false
    if settings["auto_fight_自动打怪"] ~= nil then
        auto_fight = settings["auto_fight_自动打怪"]
    end
    -- 英文key可用点号语法
    local auto_pickup = settings.auto_pickup
    if auto_pickup == nil then auto_pickup = true end

    -- ===== 🔢 number(数字输入)=====
    -- 读取并在脚本中使用,单位由控件定义决定(秒、%、分钟等)
    local fight_interval = settings["fight_interval"] or 5           -- 控件单位:秒
    local hp_threshold = settings.hp_threshold or 30                      -- 控件单位:%
    local max_duration = settings.max_duration or 120                    -- 控件单位:分钟
    local move_speed = settings.move_speed or 1.5                      -- 控件单位:倍(浮点数)
    log("  📊 打怪间隔=" .. fight_interval .. "秒, 回血<" .. hp_threshold .. "%, 最长" .. max_duration .. "分钟, 移速x" .. move_speed)

    -- ===== 📝 text(文本输入)=====
    -- 读取用户输入的文本,常用于匹配目标名称、过滤关键词等
    local target_monster = settings.target_monster or "银月贤者"
    local filter_keywords = settings.filter_keywords or ""
    log("  📝 目标怪物=" .. target_monster .. ", 过滤词=" .. filter_keywords)

    -- ===== 📋 select(下拉选择)=====
    -- 读取用户选择的值,用于条件判断
    local difficulty = settings.difficulty or "normal"
    local target_map = settings.target_map or "map1"
    if difficulty == "hell" then
        log("  ⚠️ 地狱难度已开启!")
    end

    -- ===== 📅 date(日期选择)=====
    local start_date = settings.start_date or "2025-01-01"
    -- 可用于判断当天是否在设定日期之后才执行
    local y, m, d = get_current_time()
    local today = string.format("%d-%02d-%02d", y, m, d)
    if today > start_date then
        log("  📅 日期已到达,开始执行...")
    end

    -- ===== ⏰ time(时间选择)=====
    local start_time = settings.start_time or "08:00"
    -- 解析时间字符串用于判断当前是否在指定时间之后
    local start_hour = tonumber(start_time:sub(1, 2)) or 8
    if h >= start_hour then
        log("  ⏰ 已过" .. start_time .. ",开始执行任务")
    end

    -- ===== 🎚️ slider(滑块)=====
    local volume = settings.volume or 80
    -- 将滑块值(0-100)映射到实际逻辑(如点击速度比例)
    local click_speed = 1.0 + (volume / 100) * 2.0  -- 映射为 1.0~3.0 倍速
    log("  🎚️ 音量=" .. volume .. ", 点击倍速=" .. click_speed)

    -- ===== 📁 file(文件选择)=====
    local script_file = settings.script_file or ""
    if script_file ~= "" then
        log("  📁 用户指定脚本文件: " .. script_file)
        -- 可以 dofile(script_file) 加载用户指定的脚本
    end

    -- ===== ☑️ multi_select(多选列表)=====
    -- 多选列表返回的是 table(数组),包含所有选中的 value
    local target_maps = settings.target_maps or {}
    if #target_maps > 0 then
        log("  🗺️ 多选地图: " .. table.concat(target_maps, ", "))
        -- 遍历每个选中的地图执行逻辑
        for i, map_name in ipairs(target_maps) do
            log("    正在处理地图: " .. map_name)
            -- 跳转到对应地图、执行对应逻辑...
        end
    else
        log("  🗺️ 未选择地图,使用默认地图")
    end

    -- ===== 🏷️ tag(分组标签)=====
    -- 分组标签返回的是 table(数组),包含所有选中的标签 value
    local item_filter = settings.item_filter or {}
    local filter_equip = false
    local filter_potion = false
    for i, tag in ipairs(item_filter) do
        if tag == "equip" then filter_equip = true end
        if tag == "potion" then filter_potion = true end
    end
    log("  🏷️ 物品过滤: 装备=" .. tostring(filter_equip) .. ", 药水=" .. tostring(filter_potion))

    -- ===== 🎨 color(颜色选择)=====
    local theme_color = settings.theme_color or "#FF5722"
    log("  🎨 主题颜色: " .. theme_color)

    -- ===== 主循环:根据控件值控制脚本逻辑 =====
    while true do
        if auto_fight then
            log("⚔️ 自动打怪开始!目标: " .. target_monster .. ", 难度: " .. difficulty)
            -- 调用对应的打怪子程序
        else
            log("⚔️ 自动打怪已关闭")
            log("  [提示] 请在用户控制面板中开启自动打怪")
        end
        sleep(fight_interval * 1000)
    end
end

main()

8. 📅 其他控件

日期选择 (date)、时间选择 (time)、滑块 (slider)、文件选择 (file)、多选列表 (multi_select)、分组标签 (tag)

其他控件示例
-- 日期选择
{key = "start_date", label = "开始日期", type = "date", default = "2025-01-01", icon = "📅"},

-- 时间选择
{key = "start_time", label = "开始时间", type = "time", default = "08:00", icon = "⏰"},

-- 滑块
{key = "volume", label = "音量调节", type = "slider", default = 80, min = 0, max = 100, step = 1, icon = "🔊"},

-- 文件选择
{key = "script_file", label = "脚本文件", type = "file", default = "", icon = "📄", placeholder = "选择脚本文件..."},

-- 多选列表
{key = "target_maps", label = "目标地图(多选)", type = "multi_select", default = {}, icon = "🗺️",
 options = {{value = "map1", label = "新手村"},{value = "map2", label = "幽暗森林"},{value = "map3", label = "冰封雪域"}}},

-- 分组标签
{key = "item_filter", label = "物品过滤", type = "tag", default = {}, icon = "🏷️",
 options = {{value = "equip", label = "装备"},{value = "potion", label = "药水"},{value = "material", label = "材料"}}},

⚙️ 脚本中获取用户设置参数

在脚本中,用户通过控制面板配置的设置可以通过多种方式获取。以下是完整的使用方法:

方法一:全局变量 user_settings

user_settings 是一个全局 table,包含用户在控制面板保存的所有设置。

Lua - 使用 user_settings
while true do
    if user_settings.auto_fight then
        log("自动打怪已开启")
        -- 执行打怪逻辑
    end
    sleep((user_settings.fight_interval or 5) * 1000)
end

方法二:get_setting() 函数

安全地获取单个设置项的值,如果键不存在则返回默认值。

Lua - 使用 get_setting
local auto_fight = get_setting("auto_fight", true)        -- 获取布尔值,默认 true
local fight_interval = get_setting("fight_interval", 5) -- 获取数字,默认 5
local target = get_setting("target_monster", "银月贤者") -- 获取文本
local difficulty = get_setting("difficulty", "normal") -- 获取下拉选择

if auto_fight then
    log("自动打怪已开启,间隔: " .. fight_interval .. "秒")
end

方法三:set_setting() 函数

在脚本中动态修改用户配置项的值。

Lua - 使用 set_setting
set_setting("auto_fight", false)       -- 关闭自动打怪
set_setting("fight_interval", 10)   -- 修改打怪间隔为10秒
set_setting("target_monster", "boss") -- 切换目标怪物

方法四:从 settings 字典读取(节点模式)

在节点模式下,通过服务器 API 获取用户设置后使用。这是实际项目(梦幻逍遥脚本)中使用的方式:

Lua - 从服务器获取设置后使用
-- 获取设置
local settings = get_user_settings()

-- 读取配置项(中文 key 必须用方括号)
local auto_fight_自动饱食度 = false
if settings["auto_fight_自动饱食度"] ~= nil then
    auto_fight_自动饱食度 = settings["auto_fight_自动饱食度"]
end

auto_fight_自动打怪 = false
auto_fight_自动打怪 = settings["auto_fight_自动打怪"]

-- 控制主循环
if auto_fight_自动打怪 then
    log("⚔️ 自动打怪开始!")
    -- 执行打怪逻辑
else
    log("⚔️ 自动打怪已关闭")
end

-- ⚠️ 重要:包含中文的 key 必须使用方括号语法 settings["key"]
-- 不能用 settings.key 点号语法

扁平化设置字段

当设置字段包含 fold 和 tab_container 嵌套结构时,使用 flatten_settings_fields() 函数提取所有字段的默认值:

Lua - 扁平化与默认值
function flatten_settings_fields(fields)
    local result = {}
    for _, field in ipairs(fields) do
        if field.type == "tab_container" then
            for _, tab in ipairs(field.tabs or {}) do
                for _, f in ipairs(tab.fields or {}) do
                    table.insert(result, f)
                end
            end
        elseif field.type == "fold" then
            for _, f in ipairs(field.fields or {}) do
                if f.type == "tab_container" then
                    for _, tab in ipairs(f.tabs or {}) do
                        for _, tf in ipairs(tab.fields or {}) do
                            table.insert(result, tf)
                        end
                    end
                else
                    table.insert(result, f)
                end
            end
        else
            table.insert(result, field)
        end
    end
    return result
end

-- 获取所有默认设置
function get_default_settings()
    local settings = {}
    local flat = flatten_settings_fields(SCRIPT_SETTINGS_FIELDS)
    for _, field in ipairs(flat) do
        settings[field.key] = field.default
    end
    return settings
end

🖱️ 触控方法 19个API

tap点击
点击坐标为x,y的点(推荐使用)
📥 参数:
x (number): 当前屏幕横坐标 y (number): 当前屏幕纵坐标
📤 返回值:boolean - true表示成功
示例
-- 点击坐标
tap(100, 100)

-- 配合找图使用
local result = find_image("images/button.png")
if result and result.success then
    tap(result.x, result.y)
end
longTap长点击
长点击坐标为x,y的点(按住约500ms后抬起)
📥 参数:
x (number): 当前屏幕横坐标 y (number): 当前屏幕纵坐标
示例
longTap(100, 100)
tapRandom随机点击
模拟真人随机点击(防检测)。方式1 矩形范围:tapRandom(x, y, x1, y1);方式2 半径范围:tapRandom(x, y, r)。随机坐标复用 tap() 逻辑执行点击(自动分辨率适配)
📥 参数:
矩形范围: x, y, x1, y1 (number) / 半径范围: x, y, r (number)
📤 返回值:
boolean: true 表示执行成功
示例
-- 方式1:矩形范围内随机点击
tapRandom(100, 200, 300, 400)

-- 方式2:圆形半径内随机点击
tapRandom(500, 800, 50)
swipe划动
模拟从一点滑动到另外一点(所有模式可用,推荐用于滑动操作)
📥 参数:
x1 (number): 起点x / y1 (number): 起点y / x2 (number): 终点x / y2 (number): 终点y / time (number, 可选): 耗时(毫秒),默认300
示例
-- 从左滑到右
swipe(200, 200, 800, 200, 500)

-- 向上滑动翻页
swipe(540, 800, 540, 200, 300)
touchDown / touchMove / touchUp手指按下/移动/弹起
底层触摸控制,用于复杂手势(推荐使用 swipe 替代)
📥 参数:
id (number): 手指索引0-4 / x,y (number): 坐标
示例
-- 从下往上滑动
touchDown(1, 297, 327)
for i = 1, 300 do
    touchMove(1, 297, 327 - i)
end
touchUp(1)
touchMoveEx模拟滑动增强版
带时间控制的滑动(增强版)
📥 参数:
id (number): 手指索引 / x,y (number): 目标坐标 / time (number): 滑动耗时(毫秒)
示例
touchDown(1, 100, 100)
sleep(50)
touchMoveEx(1, 300, 300, 800)
touchUp(1)
keyPress / keyDown / keyUp按键
模拟物理按键操作(home/back/recent/power等)
示例
-- 按HOME键
keyPress("home")
-- 按返回键
keyPress("back")

-- 按下并弹起
keyDown("home")
sleep(100)
keyUp("home")
inputText模拟输入文字
模拟输入文字(安卓端古龙精灵/古龙代码箱均支持)。底层执行系统 input text 命令,适合普通系统输入框:先点击输入框聚焦并等待输入法弹出再调用。仅适合英文/数字/常见符号;中文、空格、换行请改用 imeLib.setText。
📥 参数:
text (string): 要输入的文本内容
📤 返回值:
boolean: true 表示命令执行成功,false 表示失败(自绘UI输入框可能收不到文字)
示例
-- 常规输入(聊天框 / 账号 / 密码框)
tap(300, 800)  -- 先点击输入框唤起输入法
sleep(800)
inputText("hello123")

-- 中文/空格请用输入法通道
imeLib.setText("你好 world")
imeLib.setText / imeLib.lock / imeLib.unlock / imeLib.deleteChar / imeLib.finishInput / imeLib.keyEvent输入法系列
输入法输入系列(推荐首选)。imeLib.lock() 锁定 App 内置「古龙输入法」后,setText 直接 commitText 到当前输入框,不弹系统键盘且支持中文(root 自动切换;无 root 需先在系统设置启用一次古龙输入法);imeLib.unlock() 恢复原输入法。未锁定时会依次尝试:无障碍 ACTION_SET_TEXT → root input text → ADB_INPUT_TEXT 广播 → input text 兜底。deleteChar 删除一个字符,finishInput 回车确认,keyEvent 发送按键。
示例
-- 推荐:锁定古龙输入法(不弹键盘,支持中文)
setStopCallBack(function(error)
    imeLib.unlock()
end)
imeLib.lock()
imeLib.setText("公会副本马上开始")
imeLib.finishInput()   -- 回车/发送
imeLib.unlock()        -- 手动解锁(脚本停止时也会自动解锁)

-- 账号 + 密码登录框
tap(acc_x, acc_y)
imeLib.setText("player123")
tap(pwd_x, pwd_y)
imeLib.setText("p@ss w0rd")  -- 含空格/符号也可输入

-- 删除一个字符
imeLib.deleteChar()
setStopCallBack设置停止回调
注册脚本停止回调:脚本停止(含手动停止)时调用,常用于 imeLib.unlock() 等收尾清理。回调参数为错误信息,正常停止时为空字符串。
示例
setStopCallBack(function(error)
    imeLib.unlock()
end)
setOnTouchListener获取用户触摸屏幕坐标
设置触摸监听,获取用户在屏幕上的触摸坐标(仅在root/激活模式下有效)
示例
function onTouchEvent(x, y)
    log("触摸坐标: " .. x .. ", " .. y)
end
setOnTouchListener(onTouchEvent)
sleep(1000000)

🔍 图像识别 12个API

screenshot截图
截取当前设备屏幕
示例
-- 保存截图到文件
screenshot("output/screen.png")

-- 截图到内存(用于找图)
local img = screenshot()
local result = find_image("images/target.png")
find_image找图
在屏幕截图中查找指定模板图片的位置
📥 参数:
template_path (string): 模板图片路径 / threshold (number, 可选): 匹配阈值0.0~1.0,默认0.8
📤 返回值:table - {success, x, y, center_x, center_y, confidence}
示例
local result = find_image("images/button.png")
if result and result.success then
    tap(result.x, result.y)
    log(string.format("置信度: %.2f", result.confidence))
end
wait_image等待图片
等待指定图片在屏幕上出现(带超时机制)
示例
-- 等待图片出现(最多等10秒)
local result = wait_image("images/loading_done.png")
if result then
    tap(result.x, result.y)
end

-- 等待30秒超时
local result = wait_image("images/login_success.png", 30)
if not result then
    log("登录超时!")
end
exists判断存在
判断指定图片是否在屏幕上存在
示例
if exists("images/button.png") then
    log("按钮存在")
    tap(100, 200)
end
get_color获取颜色
获取屏幕指定坐标点的颜色值(返回16进制颜色字符串)
📤 返回值:string - 如 "ff0000"(红色)
示例
-- 获取坐标颜色并解析RGB
local color = get_color(500, 300)
local r, g, b = tonumber("0x"..color:sub(1,2)), tonumber("0x"..color:sub(3,4)), tonumber("0x"..color:sub(5,6))
log(r..","..g..","..b)

-- 判断颜色
if r > 200 then log("该点偏红") end
find_color找色
在屏幕上查找所有匹配指定颜色的像素点
示例
-- 查找所有红色像素
local points = find_color({255, 0, 0}, 20)
log("找到 " .. #points .. " 个红色像素点")
findMultiColor多点取色
在屏幕上查找与指定多点颜色匹配的位置(最常用的取色函数)
📥 参数:
x1,y1,x2,y2 (number): 搜索区域 / base_color (string): 基准点颜色 "RRGGBB" / offset_str (string): 偏移点 "dx|dy|RRGGBB|..." / direction (number, 可选): 方向0-4 / sim_threshold (number, 可选): 相似度0.0~1.0
示例
local result = findMultiColor(0, 0, 1080, 1920, "ff0000", "10|0|00ff00|20|0|0000ff", 0, 0.9)
if result then
    tap(result[1], result[2])
end
findMultiColorTargets多目标多点取色
一次截图查找多个多点配色,找到任意一个即返回(相比逐个调用 findMultiColor 快约3倍)
📥 参数:
x1,y1,x2,y2 (number): 搜索区域 / MultiColorTargets (table): {{base_color, offset_str}, ...} / direction (number, 可选): 方向0-4 / sim_threshold (number, 可选): 相似度0.0~1.0
📤 返回值:
table: 第一个匹配的 {x, y} 坐标,全不匹配返回 nil
示例
local MultiColorTargets = {
    {"845635", "-9|8|d7c189|-77|-3|7a4829"},
    {"efe3d3", "36|-18|e3c288|-10|6|efe1d3"},
}
local result = findMultiColorTargets(0, 0, 1080, 1920, MultiColorTargets, 0, 0.9)
if result then tap(result[1], result[2]) end
findMultiColorStr带文字标识的多点取色
一次截图查找多个多点配色,每个配色带文字标识;找到任意一个即返回(适合多状态识别,标识方便调试)
📥 参数:
x1,y1,x2,y2 (number): 搜索区域 / MultiColorStr (table): {{"文字", base_color, offset_str}, ...} / direction (number, 可选): 方向0-4 / sim_threshold (number, 可选): 相似度0.0~1.0
📤 返回值:
table: 第一个匹配的 {x, y} 坐标,全不匹配返回 nil
示例
local MultiColorStr = {
    {"系统", "e7c548", "2|15|f2a91a|-25|-3|dac04f"},
    {"返回", "ff0000", "10|0|00ff00|20|0|0000ff"},
}
local result = findMultiColorStr(0, 0, 1080, 1920, MultiColorStr, 0, 0.9)
if result then tap(result[1], result[2]) end
getMultiColorStr获取多点标记
识别范围内所有匹配的多点标记,返回所有匹配到的文字标识(用 | 分隔,同名只返回一次),适合判断界面存在哪些元素
📥 参数:
x1,y1,x2,y2 (number): 搜索区域 / MultiColorStr (table): {{"文字", base_color, offset_str}, ...} / direction (number, 可选): 方向0-4 / sim_threshold (number, 可选): 相似度0.0~1.0
📤 返回值:
table: {success=true/false, text="标记1|标记2|..."}
示例
local MultiColorStr = {
    {"天兵", "e7c548", "2|15|f2a91a|-25|-3|dac04f"},
    {"亢金龙", "efe3d3", "36|-18|e3c288|-10|6|efe1d3"},
}
local r = getMultiColorStr(0, 0, 1080, 1920, MultiColorStr, 0, 0.9)
if r and r.success then log("当前界面元素: " .. r.text) end
cmpColorEx / findMultiColorAll / findColor更多图色函数
cmpColorEx: 比较多点颜色(返回匹配索引)/ findMultiColorAll: 查找所有匹配位置 / findColor: 查找任意匹配颜色
示例
-- 比较多点颜色
local ret = cmpColorEx("ff0000", "10|0|00ff00|20|0|0000ff", 0, 0.9)
if ret ~= -1 then log("颜色匹配成功") end

-- 查找所有匹配位置
local results = findMultiColorAll(0, 0, 1080, 1920, "ff0000", "10|0|00ff00|20|0|0000ff")
for i, pos in ipairs(results) do
    tap(pos[1], pos[2])
end
getColorNum获取区域颜色数量
统计指定区域内与目标颜色匹配的像素点个数,适合判断按钮/文字的“亮/灰”“多/少”等状态
📥 参数:
x1,y1,x2,y2 (number): 搜索区域 / color (string): 颜色 "RRGGBB",多个用 "|" 分隔,支持偏色 "RRGGBB-偏色" / sim (number): 相似度 0~1,默认0.9
📤 返回值:
number: 区域内匹配的像素点数量
示例
local number = getColorNum(10, 50, 600, 600, "e91e1e", 0.8)
print(number)

-- 判断按钮状态:区域内红色像素多 → 按钮点亮
local redNum = getColorNum(100, 200, 300, 250, "e91e1e", 0.9)
if redNum > 200 then
    tap(200, 225)
end

-- 多颜色 + 偏色
local num = getColorNum(0, 0, 500, 300, "ff0000|00ff00-202020", 0.85)

📝 OCR文字识别 4个API

使用本地ONNX模型进行文字识别,无需联网。

ocr_recognize_localOCR本地文字识别
识别指定区域的文字
📥 参数:
lang (string): 'ch'(中英文)/ region (table): {x1, y1, x2, y2}
📤 返回值:table - {success, text, error}
示例
local text = ocr_recognize_local("ch", { 987, 332, 1121, 368 })
if text.success then
    log("识别结果: " .. text.text)
    if text.text == "开始挑战" then
        tap(1050, 350)
    end
end
ocr_find_text_localOCR本地查找文字
在指定区域查找目标文字并返回位置(推荐用于定位后点击)
📤 返回值:table - {found, x, y, w, h, text, confidence}
示例
local pos = ocr_find_text_local("开始", nil, {987, 332, 1121, 368})
if pos and pos.found then
    -- 点击文字中心
    tap(pos.x + pos.w / 2, pos.y + pos.h / 2)
end
ocr_recognize_detail_localOCR本地文字识别详情
识别区域中所有文字块,返回每个文字块的位置和内容
示例
local detail = ocr_recognize_detail_local("ch", {800, 300, 1200, 500})
if detail.success then
    for i, item in ipairs(detail.results) do
        if string.find(item.text, "开始挑战") then
            tap(item.x + item.w / 2, item.y + item.h / 2)
            break
        end
    end
end
ocr_find_text_all_localOCR本地查找所有匹配文字
查找所有匹配目标文字的位置,适合多个相同文字的场景
示例
local result = ocr_find_text_all_local("确认", nil, {100, 200, 600, 400})
if result.found then
    -- 从下往上点击所有匹配项
    for i = result.count, 1, -1 do
        local item = result.results[i]
        tap(item.x + item.w / 2, item.y + item.h / 2)
        sleep(500)
    end
end

🤖 YOLO目标检测 6个API

yolo_detectYOLO目标检测
YOLO v11目标检测 - 检测屏幕上的物体
📥 参数:
conf_threshold (number, 可选): 置信度阈值,默认0.25 / iou_threshold (number, 可选): IoU阈值默认0.45
示例
local result = yolo_detect()
if result.success then
    log("检测到 " .. result.count .. " 个物体")
    for i, det in ipairs(result.detections) do
        log(string.format("%s: %.2f, (%d,%d)", det.class_name, det.confidence, det.center_x, det.center_y))
    end
    -- 点击第一个检测到的物体
    if result.count > 0 then
        tap(result.detections[1].center_x, result.detections[1].center_y)
    end
end
yolo_load_custom_model加载自定义YOLO模型
加载自定义训练的NCNN格式YOLO模型(.param + .bin)
示例
-- 加载自定义模型
local result = yolo_load_custom_model("resources/models/yolov11_npc.param")
if result.success then
    log("类别: " .. table.concat(result.class_names, ", "))
    -- 执行检测
    local det = yolo_detect(0.35)
end
yolo_detect_file / yolo_detect_and_draw / yolo_load_model / yolo_get_available_models
yolo_detect_file: 从图片文件检测 / yolo_detect_and_draw: 检测并绘制边界框 / yolo_load_model: 切换内置模型 / yolo_get_available_models: 获取模型列表
示例
-- 从文件检测
local result = yolo_detect_file("screenshot.png")

-- 检测并绘制
local result = yolo_detect_and_draw()

-- 加载内置模型
yolo_load_model("yolo11n")  -- Nano最快
yolo_load_model("yolo11s")  -- Small

-- 查看可用模型
local models = yolo_get_available_models()
for i, m in ipairs(models) do
    log(m.name .. ": " .. (m.exists and "✅" or "⬇️"))
end

🔧 工具函数 55个API

sleep等待
等待指定毫秒数
示例
sleep(2000)   -- 等待2秒
sleep(500)    -- 等待0.5秒
random_sleep随机等待
随机等待一段时间(模拟人类操作,避免被检测)
示例
random_sleep(1000, 3000)   -- 随机等待1~3秒
tap(500, 300)
random_sleep(300, 800)   -- 模拟人类点击间隔
tap(500, 400)
log输出日志
输出日志信息到控制台
示例
log("脚本开始执行")
log(string.format("坐标: (%d, %d)", x, y))
user_settings / get_setting / set_setting用户设置
获取/设置用户在控制面板中配置的参数(详见上方"脚本参数获取"章节)
示例
-- 全局变量
if user_settings.auto_fight then ... end

-- 安全获取
local val = get_setting("key", defaultValue)

-- 动态修改
set_setting("key", newValue)
http_get / http_postHTTP请求
发送HTTP GET/POST请求(支持JSON和表单数据)
示例
local resp = http_get("http://api.example.com/data")
local data = json_parse(resp)

local resp = http_post("http://api.example.com/login", nil, {username = "admin", password = "123456"})
open_url打开网址
在默认浏览器中打开URL
示例
open_url("http://www.baidu.com")
write_file写入文件
写入内容到文件(目录不存在时自动创建)。相对路径以「古龙精灵」App 内置 scripts 目录为基准(示例统一使用相对路径):如 write_file("data.txt", ...) 实际写入 App 内置 scripts 目录下的 data.txt;古龙代码箱为当前工程目录、PC 调试为脚本运行目录,写法一致。无写入权限的绝对路径(如 /sdcard/Download)在设备已 root 时会自动通过 su 回退写入
📥 参数:
path (string): 文件路径(推荐相对路径,基于 App 内置 scripts 目录) / content (string): 文件内容
📤 返回值:
boolean: true 表示写入成功,false 表示失败
示例
-- 以古龙精灵为例:相对路径 = App 内置 scripts 目录
local ok = write_file("result.txt", "执行完成")
log("写入结果: " .. tostring(ok))

-- 写入JSON配置
local data = {time = os.time(), status = "ok"}
write_file("data.json", json_stringify(data))

-- ===== 绝对路径示例(雷电模拟器)=====
-- /sdcard 等价于 /storage/emulated/0
local ok2 = write_file("/sdcard/Download/gulong/data.txt", "Hello World")
log(read_file("/storage/emulated/0/Download/gulong/data.txt"))

-- 雷电共享目录(Windows 对应:文档\LDPlayer\Pictures)
write_file("/mnt/shared/Pictures/gulong_test.txt", "Hello LDPlayer")
call_python调用Python
调用Python文件中的函数(Lua→Python跨语言调用)
示例
local result = call_python("scripts/my_module.py", "process_data", "input.txt")
get_account_info获取账号信息
获取当前登录的账号信息(节点模式下使用)
示例
local account = get_account_info()
if account then log("账号: " .. account.account_id) end
get_device_info获取设备信息
获取当前连接的设备信息
示例
local info = get_device_info()
if info then log("设备: " .. info.device_name) end

更多工具函数(简要列表)

函数名说明示例
get_clipboard获取剪贴板内容local text = get_clipboard()
set_clipboard设置剪贴板内容set_clipboard("文本")
get_battery_level获取电池电量百分比local b = get_battery_level()
get_network_type获取网络类型local n = get_network_type()
is_screen_on检查屏幕是否亮起if not is_screen_on() then ...
wake_screen唤醒设备屏幕wake_screen()
get_volume / set_volume获取/设置媒体音量set_volume(15)
get_notifications获取通知列表local n = get_notifications()
clear_notifications清除通知栏clear_notifications()
get_location获取GPS定位local loc = get_location()
get_contacts获取联系人local c = get_contacts()
get_sms_list获取短信列表local s = get_sms_list(10)
send_sms发送短信send_sms("号", "内容")
make_call拨打电话make_call("10086")
get_sim_info获取SIM卡信息local s = get_sim_info()
get_wifi_list获取WiFi列表local w = get_wifi_list()
connect_wifi连接WiFiconnect_wifi("名", "密码")
get_bluetooth_devices获取蓝牙设备local b = get_bluetooth_devices()
get_file_list获取文件列表local f = get_file_list("/sdcard/")
download_file下载文件到设备download_file(url, path)
upload_file上传文件到服务器upload_file(path, url)
delete_file删除文件delete_file("/sdcard/temp.txt")
create_dir创建目录create_dir("/sdcard/app")
file_exists检查文件是否存在(相对路径=App 内置 scripts 目录)if file_exists("config.json") then ...
read_file_content读取文件内容(已实现,与read_file等价;相对路径=App 内置 scripts 目录)local c = read_file_content("config.json")
write_file_content写入文件内容(已实现,与write_file等价;相对路径=App 内置 scripts 目录)write_file_content("data.txt", "内容")
get_sdcard_path获取SD卡路径get_sdcard_path()
get_internal_storage_path获取内部存储路径get_internal_storage_path()
get_app_data_path获取应用数据目录路径get_app_data_path()
get_cache_path获取应用缓存目录路径get_cache_path()
get_download_path获取下载目录路径get_download_path()
get_pictures_path获取图片目录路径get_pictures_path()
get_music_path获取音乐目录路径get_music_path()
get_movies_path获取视频目录路径get_movies_path()
get_dcim_path获取相机照片目录路径get_dcim_path()
get_documents_path获取文档目录路径get_documents_path()
get_ringtone_path获取铃声目录路径get_ringtone_path()
get_alarms_path获取闹钟音频目录路径get_alarms_path()
get_notifications_path获取通知音频目录路径get_notifications_path()
get_podcasts_path获取播客目录路径get_podcasts_path()

💡 read_file_content / write_file_content 已在安卓端(古龙精灵、古龙代码箱)与 PC 调试引擎中实现:成功时分别返回 string / true,文件不存在或失败返回 nil / false。示例统一使用相对路径,在「古龙精灵」中即以 App 内置 scripts 目录为基准(如 data.txt → App 内置 scripts 目录/data.txt),便于脚本打包发布。绝对路径同样支持;若路径无权限(如共享存储 /sdcard/Download),设备已 root 时会自动通过 su 回退读写。
🔎 绝对路径示例(雷电模拟器)write_file_content("/sdcard/Download/gulong/data.txt", "Hello")read_file_content("/storage/emulated/0/Download/gulong/data.txt")(/sdcard 等价 /storage/emulated/0);雷电共享目录:/mnt/shared/Pictures(对应 Windows「文档\LDPlayer\Pictures」,电脑端可直接查看)。

📱 设备方法 14个API

show_message显示消息
在设备屏幕上显示提示消息(APK模式可用)。支持 top / center / bottom 预设位置,也支持按坐标显示:show_message(msg, x, y[, duration]),(x,y) 为消息框中心,按脚本设计分辨率自动缩放适配实际屏幕
📥 参数:
message (string): 消息内容 / position (string|number|table, 可选, 默认'top'):预设位置或 x 坐标 / y (number, 可选): 坐标定位的 Y / duration (number, 可选): 显示时长(毫秒),默认3000
📤 返回值:
示例
-- 默认顶部显示
show_message("任务开始执行")

-- 预设位置 + 时长
show_message("任务完成!", "bottom", 5000)

-- 坐标定位:(x,y) 为消息框中心(自动缩放适配分辨率)
show_message("⚠️ 血量不足,请注意!", 600, 300, 3000)

-- 坐标定位(table 写法)
show_message("检测到BOSS", {x = 640, y = 200}, 2000)
toast显示提示
在设备上显示Toast弹窗
示例
toast("操作完成")
runApp / stopApp打开/关闭应用
打开或关闭指定应用(传入包名)
示例
runApp("com.tencent.mm")
stopApp("com.tencent.mm")
frontAppName / appIsFront / appIsRunning
获取/判断前台应用和运行状态
示例
local pkg = frontAppName()
if appIsFront("com.example.game") then
    log("游戏在前台")
end
readPasteboard / writePasteboard读写剪贴板
读取/写入剪贴板内容
示例
writePasteboard("123")
local text = readPasteboard()
rnd生成随机整数
生成指定范围的随机整数(包含端点)
示例
local num = rnd(1, 100)
local x = rnd(100, 500)   -- 随机点击位置
getDisplaySize获取屏幕分辨率
获取设备的屏幕宽度和高度
示例
local w, h = getDisplaySize()
tap(w / 2, h / 2)  -- 点击屏幕中心
setControlBarPosNew设置悬浮窗位置
设置悬浮窗位置(按比例0~1.0)
示例
setControlBarPosNew(0, 0)        -- 左上角
setControlBarPosNew(1.0, 0)      -- 右上角
setControlBarPosNew(0.5, 0.5)    -- 屏幕中心
get_current_time获取当前时间
获取当前年月日时分秒
示例
local y, m, d, h, mi, s = get_current_time()
log(string.format("%d-%02d-%02d %02d:%02d:%02d", y, m, d, h, mi, s))
get_uptime获取开机运行时间
获取系统开机运行时间(毫秒)
示例
local hours = get_uptime() / 3600000

🔐 Root与Shell 2个API

execRoot执行Root命令
以 Root 权限执行命令并返回输出(需设备已 root)。优先使用持久 su 通道(不会重复弹授权)并带超时;无 root 或执行失败返回空字符串。可用于文件管理(ls/cp/mv/rm/mkdir/chmod)、系统操作(reboot / setenforce 0 / mount -o remount,rw /system)、应用管理(pm list packages / pm disable)等。注意:高权限操作需谨慎。
📥 参数:
command (string): 要执行的命令 / timeout (number, 可选): 超时毫秒,默认10000
📤 返回值:
string: 命令输出(含 stderr),无 root 或失败返回空字符串
示例
-- 查看系统信息
local info = execRoot("cat /proc/version")
print("系统版本: " .. info)

-- 获取当前用户
print("当前用户: " .. execRoot("whoami"))

-- 查看进程列表
print(execRoot("ps -A"))

-- 隐藏状态栏(完全沉浸式,* 表示所有应用)
execRoot("settings put global policy_control immersive.full=*")
-- 恢复状态栏显示
execRoot("settings put global policy_control null")
shell执行Shell命令
执行普通 shell 命令(以当前应用 uid,无需 root)并返回输出(stdout+stderr 合并)。适合无需 root 的设置/查询命令,例如隐藏状态栏指定图标(Android 6.0+ icon_blacklist)。
📥 参数:
command (string): 要执行的命令 / timeout (number, 可选): 超时毫秒,默认10000
📤 返回值:
string: 命令输出(含 stderr),失败返回空字符串
示例
-- 查看当前已隐藏的状态栏图标
local hidden = shell("settings get secure icon_blacklist")
print("已隐藏图标: " .. hidden)

-- 隐藏蓝牙与QQ图标(无需root,Android 6.0+)
shell("settings put secure icon_blacklist bluetooth,qq")

-- 查看所有支持隐藏的图标名称
print(shell("cmd statusbar get-status-icons"))

-- 隐藏所有应用的状态栏(如需写权限请改用 execRoot)
shell("settings put global policy_control immersive.status=*")

♿ 无障碍方法 2个API

函数名说明示例
getCaptureMode获取当前截图模式(root / mediaprojection / unknown)local mode = getCaptureMode()
setFindColorDelay设置无障碍模式下找到颜色后的等待延时(毫秒),等待屏幕稳定setFindColorDelay(200)

🖥️ 全分辨率方法 12个API

在 720×1280 下开发,自动适配其他分辨率。末尾参数 >255 为目标分辨率:仅当设备分辨率匹配时才执行且不做缩放;≤255 为容差(部分函数为「容差 + 相似度比例」)。

函数名说明示例
setDesignResolution设置脚本设计分辨率,用于后续坐标/区域缩放适配setDesignResolution(720, 1280)
setAdaptTolerance设置分辨率缩放时的颜色适配容差setAdaptTolerance(20)
setAdaptSimScale设置分辨率缩放时的相似度比例setAdaptSimScale(0.7)
tap点击(支持指定目标分辨率)tap(716, 357, 2000, 1200)
find_color单点/多颜色找色(支持指定分辨率)find_color(100,200,300,250,"ff0000",10)
findMultiColor多点取色(支持指定分辨率)findMultiColor(0,0,1080,1920,"ff0000","10|0|00ff00",0,0.9,2000,1200)
findMultiColorTargets多目标多点取色(支持指定分辨率)findMultiColorTargets(0,0,1080,1920,MultiColorTargets,0,0.9,2000,1200)
findMultiColorStr带文字标识的多点取色(支持指定分辨率)findMultiColorStr(0,0,1080,1920,MultiColorStr,0,0.9,2000,1200)
getMultiColorStr获取多点标记(支持指定分辨率)getMultiColorStr(0,0,1080,1920,MultiColorStr,0,0.9,2000,1200)
findMultiColorAll查找所有匹配位置(支持指定分辨率)findMultiColorAll(0,0,1080,1920,"ff0000","10|0|00ff00",0,0.9,2000,1200)
cmpColorEx比较多点颜色(支持指定分辨率)cmpColorEx("ff0000","10|0|00ff00",0,0.9,2000,1200)
findColor多颜色列表找色(支持指定分辨率)findColor(100,200,300,250,"ff0000|00ff00",0,0.9,2000,1200)

📝 字符串方法 20个API

函数名说明示例
splitStr根据分隔符拆分字符串splitStr("a#b#c", "#") → {"a","b","c"}
string.lower转换为小写string.lower("AbC") → "abc"
string.upper转换为大写string.upper("AbC") → "ABC"
string.find查找子串位置string.find("Hello Lua", "Lua") → 7, 9
string.reverse反转字符串string.reverse("abc") → "cba"
string.format格式化字符串string.format("值=%d", 666)
string.char / string.byteASCII与字符互转string.char(97) → "a" / string.byte("a") → 97
string.len获取字节长度string.len("abc") → 3
string.rep重复字符串n次string.rep("ab",3) → "ababab"
gbkToUtf8GBK 编码字符串转 UTF-8local s = gbkToUtf8(gbkStr)
cleanText清理文本中的空格/换行/特殊字符(OCR 结果清洗常用)local t = cleanText(ocrText)

UTF-8 扩展方法(支持中文)

函数名说明示例
utf8.inStrUTF-8查找子串utf8.inStr(1, "中国人民", "人民")
utf8.inStrRevUTF-8反向查找utf8.inStrRev("中国人民人民", "人民")
utf8.strReverseUTF-8字符串反转utf8.strReverse("中国人民")
utf8.lengthUTF-8字符长度utf8.length("中国人民万岁")
utf8.left从左截取n个字符utf8.left("中国人民", 2)
utf8.right从右截取n个字符utf8.right("中国人民", 2)
utf8.mid中间截取utf8.mid("中国人民", 2, 2)
utf8.strCut移除指定范围字符utf8.strCut("中国人民", 2, 2)

📊 数组方法 7个API

函数名说明示例
# (数组长度)获取数组元素个数local len = #arr
table.concat连接数组元素为字符串table.concat({"a","b"}, ",") → "a,b"
table.insert插入元素table.insert(arr, "x") / table.insert(arr, 1, "x")
table.remove移除元素table.remove(arr, 2) → 移除第2个元素
table.sort数组排序table.sort(nums) / table.sort(nums, function(a,b) return a>b end)
table.unique数组去重local uniq = table.unique(arr)
table.merge合并两个数组/表local all = table.merge(arr1, arr2)

📋 JSON方法 2个API

json_parseJSON解析
解析JSON字符串为Lua table
示例
local data = json_parse('{"name":"test","value":123}')
log("名称: " .. data.name)  -- 输出: test
json_stringifyJSON序列化
将Lua table序列化为JSON字符串
示例
local data = {name = "test", value = 123}
local json_str = json_stringify(data)
log(json_str)  -- 输出: {"name":"test","value":123}

🧵 多线程 14个API

在脚本里开多个线程并行干活:一边等待某个界面出现,一边做别的事。每个线程跑在独立 Java 线程上(真并行),互不阻塞。

⚠️ 注意事项:① 全局变量(_G)是所有线程共享的,多个线程同时改写同一个全局变量可能丢数据,请用 thread_lock() / thread_unlock() 保护临界区;② 停止是协作式的,子线程在调用 sleep / 取色 / 点击等 API 时才响应停止;③ 主脚本结束时所有子线程会自动退出;④ 最多同时 32 个子线程。
thread_start启动线程
启动一个脚本线程执行指定函数,立即返回线程 id;主脚本继续往下执行,实现真并行。可传函数或函数名,并支持传参。
📥 参数:
func (function|string): 要执行的函数或函数名
... (可选): 传给该函数的参数
📤 返回:
number: 线程 id(从 1 开始);参数非法或超过 32 个线程返回 nil
示例
-- 用法1:匿名函数(判断_等待服务器出现 放到子线程里跑)
local tid = thread_start(function()
    while true do
        if 综合调用.判断_服务器() then break end
        sleep(100)
    end
end)

-- 用法2:函数名(字符串),需与函数定义同名
-- 注意:脚本里的中文函数名会被自动转成英文标识符,字符串写法会找不到,
--       中文函数请改用函数引用:thread_start(判断_等待服务器出现)
local tid2 = thread_start("judgeServer")

-- 用法3:带参数 + 取返回值
local tid3 = thread_start(function(name, times)
    for i = 1, times do
        log(name .. " 第" .. i .. "次")
        sleep(100)
    end
    return name .. "完成"
end, "打怪", 3)

----主脚本代码写在这里

-- 主脚本继续做别的事,最后统一等待
thread_wait_all()
log(thread_result(tid3))
thread_wait等待线程
等待指定线程结束;不传参数(或传 nil)等价于等待全部子线程。
📥 参数:
tid (number, 可选): 线程 id,省略或 nil 表示等待全部
timeout (number, 可选): 超时毫秒,省略表示一直等待
📤 返回:
boolean: true=已结束 / false=超时或被打断;线程不存在返回 nil
示例
local tid = thread_start(function() sleep(1000) end)

if thread_wait(tid, 5000) then
    log("线程已结束")
else
    log("等待超时,线程仍在运行")
end

thread_wait()   -- 等待全部子线程
thread_wait_all等待全部线程
等待所有子线程结束(等价于 thread_wait(nil, timeout))。
📥 参数:
timeout (number, 可选): 超时毫秒,省略表示一直等待
📤 返回:
boolean: true=全部已结束 / false=超时
示例
thread_start(function() sleep(500) end)
thread_start(function() sleep(800) end)

if thread_wait_all(10000) then
    log("全部线程结束")
end
thread_stop停止线程
请求停止指定线程(协作式:被停止的线程在调用 sleep / 取色 / 点击等 API 时会尽快退出)。
📥 参数:
tid (number): 线程 id
📤 返回:
boolean: true=已发出停止请求 / false=线程不存在
示例
local tid = thread_start(function()
    while true do sleep(100) end
end)

sleep(500)
thread_stop(tid)          -- 请求停止
thread_wait(tid, 3000)    -- 等它退出
thread_stop_all停止全部线程
请求停止所有子线程(脚本被停止或结束时系统也会自动调用)。
📥 参数:
📤 返回:
number: 被请求停止的线程数量
示例
thread_start(function() while true do sleep(100) end end)
thread_start(function() while true do sleep(100) end end)

local n = thread_stop_all()
log("已停止 " .. n .. " 个线程")
thread_is_running线程是否运行中
判断指定线程是否仍在运行。
📥 参数:
tid (number): 线程 id
📤 返回:
boolean: true=运行中 / false=已结束或不存在
示例
local tid = thread_start(function() sleep(2000) end)
log(tostring(thread_is_running(tid)))  -- true

thread_wait(tid)
log(tostring(thread_is_running(tid)))  -- false
thread_count存活线程数
获取当前存活的子线程数量(主线程不计入)。
📥 参数:
📤 返回:
number: 存活线程数
示例
thread_start(function() sleep(1000) end)
thread_start(function() sleep(1000) end)
log("当前线程数: " .. thread_count())  -- 2

thread_wait_all()
log("当前线程数: " .. thread_count())  -- 0
thread_id当前线程ID
获取当前执行线程的 id(主线程固定为 0,子线程从 1 开始),可在同一函数里区分自己跑在主线程还是子线程。
📥 参数:
📤 返回:
number: 当前线程 id
示例
local tid = thread_start(function()
    log("我在子线程 " .. thread_id())  -- 例如 1
end)

log("我在主线程 " .. thread_id())      -- 0
thread_wait(tid)
thread_list存活线程列表
获取当前所有存活子线程 id 的数组,便于批量等待或批量停止。
📥 参数:
📤 返回:
table: 线程 id 数组
示例
thread_start(function() sleep(500) end)
thread_start(function() sleep(500) end)
sleep(100)

for i, tid in ipairs(thread_list()) do
    log("存活线程: " .. tid)
end
thread_result线程返回值
取线程函数执行后的返回值(支持多返回值;线程还在运行时返回 nil)。
📥 参数:
tid (number): 线程 id
📤 返回:
任意: 线程返回的值(可多个);未结束或不存在返回 nil
示例
local tid = thread_start(function()
    sleep(500)
    return "结果A", 123
end)

thread_wait(tid)
local a, b = thread_result(tid)
log(tostring(a) .. ", " .. tostring(b))  -- 结果A, 123
thread_error线程错误信息
取线程执行时的异常信息(正常结束或被主动停止的线程返回 nil),便于定位子线程报错。
📥 参数:
tid (number): 线程 id
📤 返回:
string: 错误信息;无错误返回 nil
示例
local tid = thread_start(function()
    error("子线程出错了")
end)

thread_wait(tid)
local err = thread_error(tid)
if err then log("线程报错: " .. err) end
thread_lock加锁
获取全局互斥锁(可重入)。多个线程同时修改同一个全局变量时用它对临界区加锁,避免并发写导致数据丢失。必须与 thread_unlock() 成对使用。
📥 参数:
📤 返回:
boolean: true
示例
计数 = 0

local function 累加()
    for i = 1, 1000 do
        thread_lock()        -- 进入临界区
        计数 = 计数 + 1
        thread_unlock()      -- 离开临界区
    end
end

thread_start(累加)
thread_start(累加)
thread_wait_all()
log("计数 = " .. 计数)       -- 2000(不加锁可能少几次)
thread_unlock解锁
释放 thread_lock() 获取的全局互斥锁,避免其它线程一直等待。
📥 参数:
📤 返回:
boolean: true=成功解锁 / false=当前线程未持有锁
示例
thread_lock()
共享变量 = 共享变量 + 1
thread_unlock()
thread_sleep线程休眠
线程休眠(毫秒)。与 sleep 效果一致,仅让当前线程等待,其它线程继续运行;语义上更明确,推荐在子线程里使用。
📥 参数:
ms (number): 休眠毫秒数
📤 返回:
示例
local tid = thread_start(function()
    for i = 1, 3 do
        log("子线程 tick " .. i)
        thread_sleep(300)
    end
end)

log("主线程不受影响,继续执行")
thread_wait(tid)

📄 完整脚本示例

以下是一个完整的游戏挂机脚本示例,演示了触控、找图、取色、OCR、用户设置等核心功能的使用。

Lua - 梦幻逍遥脚本(核心逻辑摘录)
-- ============================================================
-- 梦幻逍遥脚本 - 核心逻辑示例
-- 演示:触控、取色、OCR、用户设置获取
-- ============================================================

-- 加载子模块
dofile("settings_fields.lua")
dofile("server_api.lua")

local 打怪调用 = require("子程序_打怪")
local 综合调用 = require("子程序_综合调用")
local 组队调用 = require("子程序_组队")

-- 判断是否正在战斗中(取色方式)
function 判断_人物停止了()
    -- 取色判断:如果画面中某特征颜色不变,说明人物停在原处
    local colorStr = get_color(451, 585)
    local r, g, b = tonumber("0x"..colorStr:sub(1,2)), tonumber("0x"..colorStr:sub(3,4)), tonumber("0x"..colorStr:sub(5,6))
    
    sleep(900)
    
    local colorStr2 = get_color(451, 585)
    local r1, g1, b1 = tonumber("0x"..colorStr2:sub(1,2)), ...
    
    -- 颜色不变 = 人物已停止
    if r == r1 and g == g1 and b == b1 then
        return true
    end
    return false
end

-- 主函数
function main()
    log("==================================================")
    log("  古龙精灵 - 梦幻逍遥")
    
    -- 获取用户设置
    local settings = get_user_settings()
    
    -- ⚠️ 中文key必须用方括号语法
    local auto_fight_自动饱食度 = settings["auto_fight_自动饱食度"]
    local auto_自动巡山 = settings["auto_自动巡山"]
    local auto_自动除妖 = settings["auto_自动除妖"]
    local auto_fight_自动打怪 = settings["auto_fight_自动打怪"]
    
    -- 主循环
    while true do
        综合调用.操作_关闭异常提示弹出()
        
        if auto_自动除妖 then
            log("⚔️ 自动除妖开始!")
            主程序调用.主程序_除妖()
        end
        
        if auto_自动巡山 then
            log("⭐ 自动巡山开始!")
            主程序调用.主程序_巡山()
        end
        
        if auto_fight_自动打怪 then
            log("⚔️ 自动打怪开始!")
            主程序调用.主程序_除妖()
        end
        
        sleep(1000)
    end
end

main()

抓取工具使用技巧

在 PC 开发工具的工具 → 抓取窗口中:

  • 右键点击画面 → 取色:自动生成 get_color(x, y) 代码
  • 左键框选区域:自动生成 findMultiColor 代码(多点取色)
  • Ctrl+左键自定义取色:手动添加取色点,生成多点取色代码
  • 右键 → ONNX查找文字:自动生成 ocr_find_text_local 代码
  • 左键框选 + OCR模式:自动生成 ocr_recognize_local 代码

代码插入方式

在开发工具的右侧 API参考面板和UI设计面板中,点击任意代码即可自动插入到编辑器复制到剪贴板

🐉 古龙精灵 · 自动化脚本开发平台 © 2026

API参考手册 · 版本 v1.1.0

✅ 已复制到剪贴板