You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua新手求助:实现单次触发Toggle按钮及async.httpGet使用方法

Lua新手问题解答

1. async.httpGet(port, url) 使用说明

async.httpGet是异步发起HTTP GET请求的函数,核心是利用异步回调处理响应,不会阻塞主线程。基本用法如下:

核心步骤

  • 调用async.httpGet(port, url)发送请求,其中port是用于接收响应的标识端口,url是目标请求地址
  • 通过监听对应事件(通常是http_response)获取返回结果

示例代码

-- 发起GET请求,指定用端口1接收响应
async.httpGet(1, "https://example.com/api/data")

-- 监听响应事件
function onEvent(event, port, response)
    -- 匹配事件类型和指定端口
    if event == "http_response" and port == 1 then
        -- 处理响应内容,比如打印或解析
        print("请求返回内容:", response)
    end
end

注意事项

  • 异步请求不会立即返回结果,必须通过事件回调处理响应
  • 确保运行环境支持async模块及对应的事件监听机制

2. 实现单次触发的Toggle按钮

你的代码当前存在两个问题:一是onDraw嵌套在onTick内部导致语法错误,二是持续按压时每帧都会执行数值增加。要实现单次触发,核心是检测按钮按下的瞬间(上升沿),而非持续按压状态。

修复后的完整代码

base = 1
num = 1
rectX = 1
rectY = 1
rectW = 10
rectH = 10
lastPressed = false -- 记录上一帧的按钮状态

function onTick()
    local isPressed = input.getBool(1)
    local inputX = input.getNumber(3)
    local inputY = input.getNumber(4)
    local inRectangle = false
    local isPressingRectangle = false

    -- 判断鼠标是否在按钮区域内
    if inputX >= rectX and inputY >= rectY and inputX <= rectX + rectW and inputY <= rectY + rectH then
        inRectangle = true
    end

    isPressingRectangle = isPressed and inRectangle
    output.setBool(1, isPressingRectangle)

    -- 单次触发逻辑:仅当从"未按下"变为"按下"时执行数值变化
    if isPressingRectangle and not lastPressed then
        num = num + 1
        -- 限制num在base到base+1之间
        if num > base + 1 then
            num = base
        elseif num < base then
            num = base + 1
        end
    end

    -- 更新上一帧状态
    lastPressed = isPressingRectangle
end

-- 将onDraw移到onTick外部,修复语法错误
function onDraw()
    if isPressingRectangle then
        screen.setColor(0,255,0)
        screen.drawRectF(rectX,rectY,rectW,rectH)
    else
        screen.setColor(255,0,0)
        screen.drawRect(rectX,rectY,rectW,rectH)
    end
    screen.drawText(16,16,inputX)
    screen.drawText(35,16,inputY)
    screen.drawText(54,16,num)
end

关键逻辑说明

  • lastPressed变量用于记录上一帧的按钮状态,每次onTick结束时更新
  • 只有当当前按钮按下(isPressingRectangle为true)且上一帧未按下(lastPressed为false)时,才触发数值增加,确保仅在按下瞬间执行一次
  • 修复了onDraw嵌套的语法错误,同时将局部变量用local声明,避免全局变量污染

内容的提问来源于stack exchange,提问作者Rhys Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 17:05:03