[Можно закрывать] Вопрос по поводу скрипта lua

mr.qldu

Известный
Автор темы
46
0
Версия MoonLoader
Другое
Lua:
require "lib.moonloader"
require "lib.sampfuncs"
local vkeys = require "lib.vkeys"
-- Registration of command.
local CMD
local min_price = 50
local max_price = 150
local count_client = 0
function main()
    while not isSampfuncsLoaded() or not isSampLoaded() do return end
    while not isSampAvailable() do wait(100) end
    CMD = sampRegisterChatCommand
    register_commands()
    
    while true do
    wait(0)
        register_events_keys()
    end
end
function register_commands()
    CMD('welcome', welcome_function)
    CMD('bye', bye_function)
    CMD('minprice', setminprice)
    CMD('maxprice', setmaxprice)
end
function register_events_keys()
    -- check_for_repair_action(vkeys.VK_MBUTTON)
    -- check_button(vkeys.VK_SHIFT, vkeys.VK_Z)
    create_key_event(vkeys.VK_SHIFT, vkeys.VK_MBUTTON, check_for_repair_action)
end
function check_button(key1, key2)
    lua_thread.create(function()
        if isKeyDown(key1) and isKeyJustPressed(key2) then
            while isKeyDown(key1) and isKeyJustPressed(key2) do wait(10) end
            show_message("Нажата клавиша шифт.")
        end
    end)
end

function welcome_function()
    lua_thread.create(function()
            sampSendChat("Доброго времени суток.")
            wait(1000)
            sampSendChat("Вам необходима услуга ремонта автомобиля?")
        end
    )
end
function repair_function(id)
    if id ~= nil then
        lua_thread.create(function()
            sampSendChat("/do В автомобиле установлен бортовой компьютер.")
            wait(2000)
            sampSendChat("/todo Включая бортовой компьютер*сейчас посмотрим.")
            wait(2000)
            sampSendChat("/me осмотрел автомобиль и ввёл данные в бортовой компьютер.")
            wait(2000)
            sampSendChat("/me отправил данные диагностики для оценки работы.")
            wait(5000)
            sampSendChat("/do В бортовом компьютере отобразились данные.")
            wait(2000)
            sampSendChat("/me достал ручку и чековую книжу, затем выписал чек.")

            local current_price = math.random(min_price, max_price)
            
            count_client = count_client + 1
            show_message(string.format("Обслуживается %d-й клиент.", count_client))
            if (count_client % 5 == 0) then
                wait(2000)
                sampSendChat("Мои поздравления! Вы принимаете участие в акции \"Каждому пятому ремонт за 1$\"!")
                current_price = 1
            end
            wait(2000)
            sampSendChat(string.format("/todo Передавая чек в открытое окно*стоимость услуг составит %d$.", current_price))
            wait(2000)
            sampSendChat(string.format("/repair %d %d", id, current_price))
        end)
    else
        print("[error] //repair no ID.")
    end
end
function bye_function()
    lua_thread.create(function()
            sampSendChat("Хорошей дороги!")
        end
    )
end
function setminprice(num)
    if is_number(num) then
        min_price = num
        show_message(string.format("Установлена минимально возможная цена ремонта: %d$.", min_price))
    else
        show_message(string.format("Введённое значение не является целочисленным: \"%s\".", num))
    end
end
function setmaxprice(num)
    if is_number(num) then
        max_price = num
        show_message(string.format("Установлена максимально возможная цена ремонта: %d$.", max_price))
    else
        show_message(string.format("Введённое значение не является целочисленным: \"%s\".", num))
    end
end
function check_for_repair_action()
    lua_thread.create(function()
        if (sampIsDialogActive()) then
            return
        end
        sampShowDialog(6406, "Ввод ID игрока", "Введите ID игрока и нажмите \"ОК\".", "ОК", "Отмена", DIALOG_STYLE_INPUT)
        while sampIsDialogActive(6406) do wait(100) end
        local result, button, _, input = sampHasDialogRespond(6406)
        if not result or button ~= 1 then
            show_message("Операция отменена.")
            return
        end
        if not is_number(input) then
            show_message("Введите целочисленное значение.")
            return
        end
        if (tonumber(input) < 0 or tonumber(input) > 999) then
            show_message("Число в недопустимом диапазоне.")
            return
        end
        repair_function(input)
    end)
end
function show_message(text) 
    sampAddChatMessage(string.format("{03C03C}[Mechanic Helper]: {05F04B}%s", text), 0x03C03C)
end
function is_number(str) 
    return (not (str == nil or str == "")) and (type(tonumber(str)) == 'number')
end
function create_key_event(key1, key2, func)
    lua_thread.create(function()
        if isKeyDown(key1) and isKeyJustPressed(key2) then
            while isKeyDown(key1) and isKeyJustPressed(key2) do wait(10) end
            show_message("test")
            func()
        end
    end)
end

Ошибка из лога:
Код:
[13:49:43.978092] (error)    Mechanic.lua: cannot resume non-suspended coroutine
stack traceback:
    [C]: in function 'create'
    ...mes\Grand Theft Auto San Andreas\moonloader\Mechanic.lua:152: in function 'create_key_event'
    ...mes\Grand Theft Auto San Andreas\moonloader\Mechanic.lua:35: in function 'register_events_keys'
    ...mes\Grand Theft Auto San Andreas\moonloader\Mechanic.lua:20: in function <...mes\Grand Theft Auto San Andreas\moonloader\Mechanic.lua:13>
[13:49:43.978092] (error)    Mechanic.lua: Script died due to an error. (146D4044)

Ошибка возникает не постоянно, через два-три раза после выполнения кода с обработкой клавиш Шифт + Средняя кнопка мыши
Версию мунлоадера не знаю где посмотреть, качал неделю назад его с этого сайта
 
Последнее редактирование:

mr.qldu

Известный
Автор темы
46
0
Переписал немного, теперь варнингов в сампе и ошибок в логе нет.
Lua:
require "lib.moonloader"
require "lib.sampfuncs"
local vkeys = require "lib.vkeys"

-- Registration of command.
local CMD

local min_price = 50
local max_price = 150

local count_client = 0

function main()
    while not isSampfuncsLoaded() or not isSampLoaded() do return end
    while not isSampAvailable() do wait(100) end

    CMD = sampRegisterChatCommand
    register_commands()

    while true do
        wait(0)
        check_keys_events()
    end
end

function register_commands()
    CMD('minprice', setminprice)
    CMD('maxprice', setmaxprice)
end

function setminprice(num)
    if is_number(num) then
        min_price = num
        show_message(string.format("Установлена минимально возможная цена ремонта: %d$.", min_price))
    else
        show_message(string.format("Введённое значение не является целочисленным: \"%s\".", num))
    end
end

function setmaxprice(num)
    if is_number(num) then
        max_price = num
        show_message(string.format("Установлена максимально возможная цена ремонта: %d$.", max_price))
    else
        show_message(string.format("Введённое значение не является целочисленным: \"%s\".", num))
    end
end


function check_keys_events()
    check_keys_event(vkeys.VK_SHIFT, vkeys.VK_MBUTTON, key_event_repair)
end


function check_keys_event(key1, key2, func)
    if isKeyDown(key1) and isKeyJustPressed(key2) then
        while isKeyDown(key1) and isKeyJustPressed(key2) do wait(0) end
        func()
    end
end





function key_event_repair()
    lua_thread.create(function()
        if (sampIsDialogActive()) then
            print("сработала проверка на sampIsDialogActive")
            return
        end
        sampShowDialog(6406, "Ввод ID игрока", "Введите ID игрока и нажмите \"ОК\".", "ОК", "Отмена", DIALOG_STYLE_INPUT)
        while sampIsDialogActive(6406) do wait(100) end
        local result, button, _, input = sampHasDialogRespond(6406)

        if not result or button ~= 1 then
            show_message("Операция отменена.")
            return
        end

        if not is_number(input) then
            show_message("Введите целочисленное значение.")
            return
        end

        if (tonumber(input) < 0 or tonumber(input) > 999) then
            show_message("Число в недопустимом диапазоне.")
            return
        end

        sampSendChat("/do В автомобиле установлен бортовой компьютер.")
        wait(2000)
        sampSendChat("/todo Включая бортовой компьютер*сейчас посмотрим.")
        wait(2000)
        sampSendChat("/me осмотрел автомобиль и ввёл данные в бортовой компьютер.")
        wait(2000)
        sampSendChat("/me отправил данные диагностики для оценки работы.")
        wait(5000)
        sampSendChat("/do В бортовом компьютере отобразились данные.")
        wait(2000)
        sampSendChat("/me достал ручку и чековую книжу, затем выписал чек.")


        local current_price = math.random(min_price, max_price)
        
        count_client = count_client + 1
        show_message(string.format("Обслуживается %d-й клиент.", count_client))

        if (count_client % 5 == 0) then
            wait(2000)
            sampSendChat("Мои поздравления! Вы принимаете участие в акции \"Каждому пятому ремонт за 1$\"!")
            current_price = 1
        end

        wait(2000)
        sampSendChat(string.format("/todo Передавая чек в открытое окно*стоимость услуг составит %d$.", current_price))

        wait(2000)
        sampSendChat(string.format("/repair %d %d", input, current_price))
    end)
end



function show_message(text)
    sampAddChatMessage(string.format("{03C03C}[Mechanic Helper]: {05F04B}%s", text), 0x03C03C)
end

function is_number(str)
    return (not (str == nil or str == "")) and (type(tonumber(str)) == 'number')
end
 

Pakulichev

Software Developer & System Administrator
Друг
1,789
2,133
И неактуально, прекрасный совет!
 
  • Нравится
Реакции: mr.qldu