ошибка при использовании цикла if

KPOLLI

Новичок
Автор темы
23
0
Версия SA-MP
  1. Любая
На основе скрипта с таймером обновления армора хотел сделать примерно тоже самое для щита, чтобы:
- отображалось "Invul" (в идеале цветом) пока активен 3 секунды гм
- отображалось "Inv: (секунды)" до перезарядки (6 сек)

Изменил цикл таймера на 9 сек. При добавлении блока if все ломается и выдает ошибку cannot resume non-suspended coroutine stack traceback
по моему плану когда запускается таймер я вижу надпись инвул, затем проходит 3 секунды и начинается кд и я вижу время до его конца, но луа видит это как-то иначе
луа:
if secondsarmor > 6 then
local text = 'Inv: ' .. secondsarmor
else
local text = 'Invul '
end

Если удалить цикл if то все работает и пишет "Inv: (секунды)"
2:
sampev = require 'samp.events'
script_properties("work-in-pause")
local startTimearmor = 0
local playerName = nil
local playerID = nil
local maxArmorValues = {}
local lastArmor = 0
local renderBoxEnabled = true
local armorCheckEnabled = true

function json(filePath)
    local class, filePath = {}, getWorkingDirectory()..'/config/'..(filePath:find('(.+).json') and filePath or filePath..'.json')
    if not doesDirectoryExist(getWorkingDirectory()..'/config') then createDirectory(getWorkingDirectory()..'/config') end
    function class:save(tbl)
        if tbl then
            local F = io.open(filePath, 'w')
            F:write(encodeJson(tbl) or {})
            F:close()
            return true, 'ok'
        end
        return false, 'table = nil'
    end
    function class:load(defaultTable)
        if not doesFileExist(filePath) then class:save(defaultTable or {}) end
        local F = io.open(filePath, 'r+')
        local TABLE = decodeJson(F:read() or {})
        F:close()
        for def_k, def_v in next, defaultTable do if TABLE[def_k] == nil then TABLE[def_k] = def_v end end
        return TABLE
    end
    return class
end

boolSetPosition = false
path = "renderText1.json"
local settings = json(path):load({
    x = 500,
    y = 500,
    renderBoxEnabled = true,
    armorCheckEnabled = true
})

renderBoxEnabled = settings.renderBoxEnabled
armorCheckEnabled = settings.armorCheckEnabled

function sampev.onServerMessage(color, text)
        if text:find('неуязвимость на 3') or text:find('неуязвимость на 3') then
            startTimearmor = os.clock() + 8.993
     
    end
end



local font = renderCreateFont('Segoe UI', 13, 5)

function main()
    while not isSampAvailable() do wait(0) end

 

    sampRegisterChatCommand('setposs', function()
        boolSetPosition = true
        showCursor(true, true)
        sampAddChatMessage("{AFEEEE}[ KULTARM ] {ffffff}Нажмите {CD5C5C}ЛКМ{ffffff}, чтобы сохранить позицию", -1)
    end)

    startTimearmor = os.clock() + 8.993

    while true do
        wait(0)
        if boolSetPosition then
            local mouseX, mouseY = getCursorPos()
            settings.x, settings.y = mouseX, mouseY
            if isKeyJustPressed(1) then
                json(path):save(settings)
                boolSetPosition = false
                showCursor(false)
                sampAddChatMessage("{AFEEEE}[ KULTARM ] {ffffff}Позиция сохранена (x = {CD5C5C}" .. settings.x .. "{ffffff}, y = {CD5C5C}".. settings.y.."{ffffff})", -1)
                print("Позиция сохранена: x = " .. settings.x .. ", y = " .. settings.y)
            end
        end

        local timeRemainingarmor = startTimearmor - os.clock()
        if timeRemainingarmor > 0 then
            local secondsarmor = math.floor(timeRemainingarmor)

         
            local text = 'Inv: ' .. secondsarmor
         

            local height = renderGetFontDrawHeight(font)
            local textWidth = renderGetFontDrawTextLength(font, text)

            local boxWidth = textWidth + 10
            local boxHeight = height + 10

            local textX = settings.x + (boxWidth - textWidth) / 2
            local textY = settings.y + (boxHeight - height) / 2

            if renderBoxEnabled then
                renderDrawBox(settings.x, settings.y, boxWidth, boxHeight, 0xaa000000)
            end

            renderFontDrawText(font, text, textX, textY, 0xFFFFFFFF)
       
        else

        end
    end
end
 
Последнее редактирование:
Решение
if это не цикл, это раз. два, ты объявляешь переменную локально внутри блока if, снаружи её тупо не будет видно. сделай так
хуяк:
local text = ""
if secondsarmor > 6 then
 text = 'Inv: ' .. secondsarmor
else
 text = 'Invul '
end

БеzликиЙ

Автор темы
Проверенный
1,310
821
if это не цикл, это раз. два, ты объявляешь переменную локально внутри блока if, снаружи её тупо не будет видно. сделай так
хуяк:
local text = ""
if secondsarmor > 6 then
 text = 'Inv: ' .. secondsarmor
else
 text = 'Invul '
end
 
  • Нравится
Реакции: KPOLLI