Вопросы по Lua скриптингу

Общая тема для вопросов по разработке скриптов на языке программирования Lua, в частности под MoonLoader.
  • Задавая вопрос, убедитесь, что его нет в списке частых вопросов и что на него ещё не отвечали (воспользуйтесь поиском).
  • Поищите ответ в теме посвященной разработке Lua скриптов в MoonLoader
  • Отвечая, убедитесь, что ваш ответ корректен.
  • Старайтесь как можно точнее выразить мысль, а если проблема связана с кодом, то обязательно прикрепите его к сообщению, используя блок [code=lua]здесь мог бы быть ваш код[/code].
  • Если вопрос связан с MoonLoader-ом первым делом желательно поискать решение на wiki.

Частые вопросы

Как научиться писать скрипты? С чего начать?
Информация - Гайд - Всё о Lua скриптинге для MoonLoader(https://blast.hk/threads/22707/)
Как вывести текст на русском? Вместо русского текста у меня какие-то каракули.
Изменить кодировку файла скрипта на Windows-1251. В Atom: комбинация клавиш Ctrl+Shift+U, в Notepad++: меню Кодировки -> Кодировки -> Кириллица -> Windows-1251.
Как получить транспорт, в котором сидит игрок?
Lua:
local veh = storeCarCharIsInNoSave(PLAYER_PED)
Как получить свой id или id другого игрока?
Lua:
local _, id = sampGetPlayerIdByCharHandle(PLAYER_PED) -- получить свой ид
local _, id = sampGetPlayerIdByCharHandle(ped) -- получить ид другого игрока. ped - это хендл персонажа
Как проверить, что строка содержит какой-то текст?
Lua:
if string.find(str, 'текст', 1, true) then
-- строка str содержит "текст"
end
Как эмулировать нажатие игровой клавиши?
Lua:
local game_keys = require 'game.keys' -- где-нибудь в начале скрипта вне функции main

setGameKeyState(game_keys.player.FIREWEAPON, -1) -- будет сэмулировано нажатие клавиши атаки
Все иды клавиш находятся в файле moonloader/lib/game/keys.lua.
Подробнее о функции setGameKeyState здесь: lua - setgamekeystate | BlastHack — DEV_WIKI(https://www.blast.hk/wiki/lua:setgamekeystate)
Как получить id другого игрока, в которого целюсь я?
Lua:
local valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE) -- получить хендл персонажа, в которого целится игрок
if valid and doesCharExist(ped) then -- если цель есть и персонаж существует
  local result, id = sampGetPlayerIdByCharHandle(ped) -- получить samp-ид игрока по хендлу персонажа
  if result then -- проверить, прошло ли получение ида успешно
    -- здесь любые действия с полученным идом игрока
  end
end
Как зарегистрировать команду чата SAMP?
Lua:
-- До бесконечного цикла/задержки
sampRegisterChatCommand("mycommand", function (param)
     -- param будет содержать весь текст введенный после команды, чтобы разделить его на аргументы используйте string.match()
    sampAddChatMessage("MyCMD", -1)
end)
Крашит игру при вызове sampSendChat. Как это исправить?
Это происходит из-за бага в SAMPFUNCS, когда производится попытка отправки пакета определенными функциями изнутри события исходящих RPC и пакетов. Исправления для этого бага нет, но есть способ не провоцировать его. Вызов sampSendChat изнутри обработчика исходящих RPC/пакетов нужно обернуть в скриптовый поток с нулевой задержкой:
Lua:
function onSendRpc(id)
  -- крашит:
  -- sampSendChat('Send RPC: ' .. id)

  -- норм:
  lua_thread.create(function()
    wait(0)
    sampSendChat('Send RPC: ' .. id)
  end)
end
 
Последнее редактирование:

Narkizo

Участник
37
14
Lua:
addOneOffSound(0, 0, 0, 1137) --on
addOneOffSound(0, 0, 0, 1138) --off
/aimset:
if not doesDirectoryExist('moonloader/config') then createDirectory('moonloader/config') end

local events = require 'lib.samp.events'
local keys = require 'lib.vkeys'

local state = false
local debugMode = false

local settings = {
    max_distance = 85,
    field_of_search = 10,
    show_circle = true,
    through_walls = false,
    key_activation = 0x4A,
    miss_ratio = 30
}

function convertSettingsToString(settings_table)
    local output = ''
    for k, v in pairs(settings_table) do
        output = output .. k .. '=' .. tostring(v) .. ','
    end
    return output:sub(0, -2)
end

function convertStringToSettings(str)
    local output = {}
    for par in str:gmatch('[^,]+') do
        local field, value = par:match('(.+)=(.+)')
        if value == 'true' then value = true
        elseif value == 'false' then value = false
        else value = tonumber(value) end
        output[field] = value
    end
    return output
end

function saveSettings(str)
    local file = io.open('moonloader/config/aim.ini', 'w')
    file:write(str)
    file:close()
end

function loadSettings()
    local file = io.open('moonloader/config/aim.ini', 'r')
    settings = convertStringToSettings(file:read())
    file:close()
end

function debugSay(msg)
    if debugMode then sampAddChatMessage('[SHOT] ' .. msg, -1) end
end

if not doesFileExist('moonloader/config/aim.ini') then saveSettings( convertSettingsToString(settings) ) end
loadSettings()

local cx = representIntAsFloat(readMemory(0xB6EC10, 4, false))
local cy = representIntAsFloat(readMemory(0xB6EC14, 4, false))
local w, h = getScreenResolution()
local xc, yc = w * cy, h * cx

function getpx()
    return ((w / 2) / getCameraFov()) * settings.field_of_search
end

function canPedBeShot(ped)
    local ax, ay, az = convertScreenCoordsToWorld3D(xc, yc, 0) -- getCharCoordinates(1)
    local bx, by, bz = getCharCoordinates(ped)
    return not select(1, processLineOfSight(ax, ay, az, bx, by, bz + 0.7, true, false, false, true, false, true, false, false))
end

function getcond(ped)
    if settings.through_walls or isKeyDown(keys.VK_E) then return true
    else return canPedBeShot(ped) end
end

function getDistanceFromPed(ped)
    local ax, ay, az = getCharCoordinates(1)
    local bx, by, bz = getCharCoordinates(ped)
    return math.sqrt( (ax - bx) ^ 2 + (ay - by) ^ 2 + (az - bz) ^ 2 )
end

function getClosestPlayerFromCrosshair()
    local R1, target = getCharPlayerIsTargeting(0)
    local R2, player = sampGetPlayerIdByCharHandle(target)
    if R2 then return player, target end
    local minDist = getpx()
    local closestId, closestPed = -1, -1
    for i = 0, 999 do
        local res, ped = sampGetCharHandleBySampPlayerId(i)
        if res then
            if getDistanceFromPed(ped) < settings.max_distance then
            local xi, yi = convert3DCoordsToScreen(getCharCoordinates(ped))
            local dist = math.sqrt( (xi - xc) ^ 2 + (yi - yc) ^ 2 )
            if dist < minDist then
                minDist = dist
                closestId, closestPed = i, ped
            end
            end
        end
    end
    return closestId, closestPed
end

function rand() return math.random(-50, 50) / 100 end

function getDamage(weap)
    local damage = {
        [22] = 8.25,
        [23] = 13.2,
        [24] = 46.200000762939,
        [25] = 30,
        [26] = 30,
        [27] = 30,
        [28] = 6.6,
        [29] = 8.25,
        [30] = 9.9,
        [31] = 9.9000005722046,
        [32] = 6.6,
        [33] = 25,
        [38] = 46.2
    }
    return (damage[weap] or 0) + math.random(1e9)/1e15
end

local shotindex = 0

function events.onSendBulletSync(data)
    math.randomseed(os.clock())
    if not state then return end
    local weap = getCurrentCharWeapon(1)
    if not getDamage(weap) then return end
    local id, ped = getClosestPlayerFromCrosshair()
    if id == -1 then return debugSay('В зоне вокруг прицела не было найдено игроков') end
    local vmes =    sampGetPlayerNickname(id) .. ' > ' .. math.floor(getDistanceFromPed(ped)) .. 'm > ' ..
            math.floor(getCharSpeed(1) * 3) .. ' vs ' .. math.floor(getCharSpeed(ped) * 3) .. ' > '
    if data.targetType == 1 then return debugSay(vmes .. 'Попадание без помощи аима') end
    if math.random(1, 100) < settings.miss_ratio and not isKeyDown(keys.VK_E) then return debugSay(vmes .. 'Выстрел отменен (имитация промахов)') end
    if not getcond(ped) then return debugSay(vmes .. 'Выстрел отменен (игрок за текстурами)') end
    debugSay(vmes .. 'OK')
    data.targetType = 1
    local px, py, pz = getCharCoordinates( ped )
    data.targetId = id

    data.target = { x = px + rand(), y = py + rand(), z = pz + rand() }
    data.center = { x = rand(), y = rand(), z = rand() }

    lua_thread.create(function ()
        wait(1)
        sampSendGiveDamage(id, getDamage(weap), weap, 3)
    end)
end

function showmenu()
    local output =    ' \t \n' ..
            'Статус:\t' .. (state and '{00AA00}ON' or '{AA0000}OFF') .. '\n' ..
            'Стрельба сквозь текстуры:\t' .. (settings.through_walls and '{00AA00}ON' or '{AA0000}OFF') .. '\n' ..
            'Радиус поиска:\t{ABCDEF}' .. settings.field_of_search .. '{FFFFFF} градусов\n' ..
            'Показывать радиус поиска:\t' .. (settings.show_circle and '{00AA00}ON' or '{AA0000}OFF') .. '\n' ..
            'Кнопка активации:\t{ABCDEF}' .. keys.id_to_name(settings.key_activation) .. '\n' ..
            'Лимит дистанции:\t{ABCDEF}' .. settings.max_distance .. '{FFFFFF} метров\n' ..
            'Вероятность промаха:\t{ABCDEF}' .. settings.miss_ratio .. '{FFFFFF} %\n' ..
            'Информация о выстрелах:\t' .. (debugMode and '{00AA00}ON' or '{AA0000}OFF') .. '\n' ..
            'Показать справку'
    sampShowDialog(900, '{00CC00}Silent Aim by astynk | Настройки', output, 'Выбрать', 'Закрыть', 5)
    saveSettings( convertSettingsToString(settings) )
end

local faqtext = 'Данный аим имитирует выстрел по ближайшему к прицелу игроку.\n' ..
        'Таким образом, достаточно просто стрелять хотя бы в ту сторону, где находится игрок.\n' ..
        'Открыть меню настроек аима - /aimset\nВключить/выключить аим - J (по умолчанию)\n\n' ..
        'Подробная информация по всем настройкам:\n' ..
        'Стрельба сквозь текстуры - позволяет стрелять в игроков сквозь текстуры. Есть и зажимной вариант (на клавишу "E")\n' ..
        'Радиус поиска - зона вокруг прицела, в пределах которой будет производиться поиск игроков\n' ..
        'Показывать радиус поиска - отображает синий круг вокруг прицела, соответствующий радиусу поиска\n' ..
        'Кнопка активации - настраивает кнопку для быстрого включения/выключения аима\n' ..
        'Лимит дистанции - максимальное расстояние до игрока, в пределах которого работает аим\n' ..
        'Вероятность промахов - Имитация промахов для предотвращения определения аима\n' ..
        'Информация о выстрелах - показывает дистанцию, скорость и другие параметры, также можно командой /aimdebug\n' ..
        'Все настройки сохраняются при перезаходе.\n' ..
        'Стрельбу сквозь текстуры включать на свой страх и риск, можно в крайних случаях использовать зажимной вариант.'
        

function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('aimset', function ()
        showmenu()
    end)
    sampRegisterChatCommand('aimdebug', function ()
        debugMode = not debugMode
    end)
    local PI = 3.14159
    while true do
        wait(0)
            if state and settings.show_circle and isKeyDown(2) and isCharOnFoot(1) and getDamage(getCurrentCharWeapon(1)) then
            local px = getpx()
            local step = px / 1e4
            for i = 0, 6.28, step do
                if
                    i > PI * 1.875 or i < PI * 0.125 or
                    i > PI * 0.875 and i < PI * 1.125 or
                    i > PI * 0.375 and i < PI * 0.625 or
                    i > PI * 1.375 and i < PI * 1.625
                then
                    renderDrawBox(xc + math.cos(i) * px, yc + math.sin(i) * px, 3, 3, 0x55007FFF)
                end
            end
        end

        local res1, but1, list1 = sampHasDialogRespond(900)
        if res1 and but1 == 1 then
            if list1 == 0 then state = not state; showmenu() end
            if list1 == 1 then settings.through_walls = not settings.through_walls; showmenu() end
            if list1 == 2 then sampShowDialog(901, "{00CC00}Введите радиус поиска", '', "ОК", "Закрыть", 1) end
            if list1 == 3 then settings.show_circle = not settings.show_circle; showmenu() end
            if list1 == 4 then sampShowDialog(902, "{00CC00}Введите кнопку активации", '', "ОК", "Закрыть", 1) end
            if list1 == 5 then sampShowDialog(903, "{00CC00}Введите лимит дистанции", '', "ОК", "Закрыть", 1) end
            if list1 == 6 then sampShowDialog(904, "{00CC00}Введите вероятность промаха", '', "ОК", "Закрыть", 1) end
            if list1 == 7 then debugMode = not debugMode; showmenu() end
            if list1 == 8 then sampShowDialog(905, "{00CC00}Silent Aim by astynk | Справка", faqtext, "ОК") end
        end

        local res2, but2, list2, input2 = sampHasDialogRespond(901)
        if res2 and but2 == 1 then
            input2 = tonumber(input2)
            if not input2 or input2 < 0 or input2 > 100 then
                sampAddChatMessage('Введено неверное значение.', 0xAFAFAF)
            else
                settings.field_of_search = input2
            end
            showmenu()
        end
        if res2 and but2 == 0 then showmenu() end

        local res3, but3, list3, input3 = sampHasDialogRespond(902)
        if res3 and but3 == 1 then
            local k = keys.name_to_id(input3)
            if not k then
                sampAddChatMessage('Введено некорректное название клавиши.', 0xAFAFAF)
            else
                settings.key_activation = k
            end
            showmenu()
        end
        if res3 and but3 == 0 then showmenu() end

        local res4, but4, list4, input4 = sampHasDialogRespond(903)
        if res4 and but4 == 1 then
            input4 = tonumber(input4)
            if not input4 or input4 < 0 or input4 > 1000 then
                sampAddChatMessage('Введено неверное значение.', 0xAFAFAF)
            else
                settings.max_distance = input4
            end
            showmenu()
        end
        if res4 and but4 == 0 then showmenu() end

        local res5, but5, list5, input5 = sampHasDialogRespond(904)
        if res5 and but5 == 1 then
            input5 = tonumber(input5)
            if not input5 or input5 < 0 or input5 > 100 then
                sampAddChatMessage('Введено неверное значение.', 0xAFAFAF)
            else
                settings.miss_ratio = input5
            end
            showmenu()
        end
        if res5 and but5 == 0 then showmenu() end


        local res6, but6, list6, input6 = sampHasDialogRespond(905)
        if res6 then
            showmenu()
        end

        [COLOR=rgb(209, 72, 65)]if wasKeyPressed(settings.key_activation) and not (sampIsChatInputActive() or sampIsDialogActive()) then
                state = not state
                print( and 'ВКЛ' or 'ВЫКЛ')[/COLOR]
        end
    end
end
Подскажи, пожалуйста, чайнику, как поставить чтобы при активации был один звук, а при выключении другой. Я пытался пытался, но ничего не вышло :D
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,778
11,223
/aimset:
if not doesDirectoryExist('moonloader/config') then createDirectory('moonloader/config') end

local events = require 'lib.samp.events'
local keys = require 'lib.vkeys'

local state = false
local debugMode = false

local settings = {
    max_distance = 85,
    field_of_search = 10,
    show_circle = true,
    through_walls = false,
    key_activation = 0x4A,
    miss_ratio = 30
}

function convertSettingsToString(settings_table)
    local output = ''
    for k, v in pairs(settings_table) do
        output = output .. k .. '=' .. tostring(v) .. ','
    end
    return output:sub(0, -2)
end

function convertStringToSettings(str)
    local output = {}
    for par in str:gmatch('[^,]+') do
        local field, value = par:match('(.+)=(.+)')
        if value == 'true' then value = true
        elseif value == 'false' then value = false
        else value = tonumber(value) end
        output[field] = value
    end
    return output
end

function saveSettings(str)
    local file = io.open('moonloader/config/aim.ini', 'w')
    file:write(str)
    file:close()
end

function loadSettings()
    local file = io.open('moonloader/config/aim.ini', 'r')
    settings = convertStringToSettings(file:read())
    file:close()
end

function debugSay(msg)
    if debugMode then sampAddChatMessage('[SHOT] ' .. msg, -1) end
end

if not doesFileExist('moonloader/config/aim.ini') then saveSettings( convertSettingsToString(settings) ) end
loadSettings()

local cx = representIntAsFloat(readMemory(0xB6EC10, 4, false))
local cy = representIntAsFloat(readMemory(0xB6EC14, 4, false))
local w, h = getScreenResolution()
local xc, yc = w * cy, h * cx

function getpx()
    return ((w / 2) / getCameraFov()) * settings.field_of_search
end

function canPedBeShot(ped)
    local ax, ay, az = convertScreenCoordsToWorld3D(xc, yc, 0) -- getCharCoordinates(1)
    local bx, by, bz = getCharCoordinates(ped)
    return not select(1, processLineOfSight(ax, ay, az, bx, by, bz + 0.7, true, false, false, true, false, true, false, false))
end

function getcond(ped)
    if settings.through_walls or isKeyDown(keys.VK_E) then return true
    else return canPedBeShot(ped) end
end

function getDistanceFromPed(ped)
    local ax, ay, az = getCharCoordinates(1)
    local bx, by, bz = getCharCoordinates(ped)
    return math.sqrt( (ax - bx) ^ 2 + (ay - by) ^ 2 + (az - bz) ^ 2 )
end

function getClosestPlayerFromCrosshair()
    local R1, target = getCharPlayerIsTargeting(0)
    local R2, player = sampGetPlayerIdByCharHandle(target)
    if R2 then return player, target end
    local minDist = getpx()
    local closestId, closestPed = -1, -1
    for i = 0, 999 do
        local res, ped = sampGetCharHandleBySampPlayerId(i)
        if res then
            if getDistanceFromPed(ped) < settings.max_distance then
            local xi, yi = convert3DCoordsToScreen(getCharCoordinates(ped))
            local dist = math.sqrt( (xi - xc) ^ 2 + (yi - yc) ^ 2 )
            if dist < minDist then
                minDist = dist
                closestId, closestPed = i, ped
            end
            end
        end
    end
    return closestId, closestPed
end

function rand() return math.random(-50, 50) / 100 end

function getDamage(weap)
    local damage = {
        [22] = 8.25,
        [23] = 13.2,
        [24] = 46.200000762939,
        [25] = 30,
        [26] = 30,
        [27] = 30,
        [28] = 6.6,
        [29] = 8.25,
        [30] = 9.9,
        [31] = 9.9000005722046,
        [32] = 6.6,
        [33] = 25,
        [38] = 46.2
    }
    return (damage[weap] or 0) + math.random(1e9)/1e15
end

local shotindex = 0

function events.onSendBulletSync(data)
    math.randomseed(os.clock())
    if not state then return end
    local weap = getCurrentCharWeapon(1)
    if not getDamage(weap) then return end
    local id, ped = getClosestPlayerFromCrosshair()
    if id == -1 then return debugSay('В зоне вокруг прицела не было найдено игроков') end
    local vmes =    sampGetPlayerNickname(id) .. ' > ' .. math.floor(getDistanceFromPed(ped)) .. 'm > ' ..
            math.floor(getCharSpeed(1) * 3) .. ' vs ' .. math.floor(getCharSpeed(ped) * 3) .. ' > '
    if data.targetType == 1 then return debugSay(vmes .. 'Попадание без помощи аима') end
    if math.random(1, 100) < settings.miss_ratio and not isKeyDown(keys.VK_E) then return debugSay(vmes .. 'Выстрел отменен (имитация промахов)') end
    if not getcond(ped) then return debugSay(vmes .. 'Выстрел отменен (игрок за текстурами)') end
    debugSay(vmes .. 'OK')
    data.targetType = 1
    local px, py, pz = getCharCoordinates( ped )
    data.targetId = id

    data.target = { x = px + rand(), y = py + rand(), z = pz + rand() }
    data.center = { x = rand(), y = rand(), z = rand() }

    lua_thread.create(function ()
        wait(1)
        sampSendGiveDamage(id, getDamage(weap), weap, 3)
    end)
end

function showmenu()
    local output =    ' \t \n' ..
            'Статус:\t' .. (state and '{00AA00}ON' or '{AA0000}OFF') .. '\n' ..
            'Стрельба сквозь текстуры:\t' .. (settings.through_walls and '{00AA00}ON' or '{AA0000}OFF') .. '\n' ..
            'Радиус поиска:\t{ABCDEF}' .. settings.field_of_search .. '{FFFFFF} градусов\n' ..
            'Показывать радиус поиска:\t' .. (settings.show_circle and '{00AA00}ON' or '{AA0000}OFF') .. '\n' ..
            'Кнопка активации:\t{ABCDEF}' .. keys.id_to_name(settings.key_activation) .. '\n' ..
            'Лимит дистанции:\t{ABCDEF}' .. settings.max_distance .. '{FFFFFF} метров\n' ..
            'Вероятность промаха:\t{ABCDEF}' .. settings.miss_ratio .. '{FFFFFF} %\n' ..
            'Информация о выстрелах:\t' .. (debugMode and '{00AA00}ON' or '{AA0000}OFF') .. '\n' ..
            'Показать справку'
    sampShowDialog(900, '{00CC00}Silent Aim by astynk | Настройки', output, 'Выбрать', 'Закрыть', 5)
    saveSettings( convertSettingsToString(settings) )
end

local faqtext = 'Данный аим имитирует выстрел по ближайшему к прицелу игроку.\n' ..
        'Таким образом, достаточно просто стрелять хотя бы в ту сторону, где находится игрок.\n' ..
        'Открыть меню настроек аима - /aimset\nВключить/выключить аим - J (по умолчанию)\n\n' ..
        'Подробная информация по всем настройкам:\n' ..
        'Стрельба сквозь текстуры - позволяет стрелять в игроков сквозь текстуры. Есть и зажимной вариант (на клавишу "E")\n' ..
        'Радиус поиска - зона вокруг прицела, в пределах которой будет производиться поиск игроков\n' ..
        'Показывать радиус поиска - отображает синий круг вокруг прицела, соответствующий радиусу поиска\n' ..
        'Кнопка активации - настраивает кнопку для быстрого включения/выключения аима\n' ..
        'Лимит дистанции - максимальное расстояние до игрока, в пределах которого работает аим\n' ..
        'Вероятность промахов - Имитация промахов для предотвращения определения аима\n' ..
        'Информация о выстрелах - показывает дистанцию, скорость и другие параметры, также можно командой /aimdebug\n' ..
        'Все настройки сохраняются при перезаходе.\n' ..
        'Стрельбу сквозь текстуры включать на свой страх и риск, можно в крайних случаях использовать зажимной вариант.'
       

function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('aimset', function ()
        showmenu()
    end)
    sampRegisterChatCommand('aimdebug', function ()
        debugMode = not debugMode
    end)
    local PI = 3.14159
    while true do
        wait(0)
            if state and settings.show_circle and isKeyDown(2) and isCharOnFoot(1) and getDamage(getCurrentCharWeapon(1)) then
            local px = getpx()
            local step = px / 1e4
            for i = 0, 6.28, step do
                if
                    i > PI * 1.875 or i < PI * 0.125 or
                    i > PI * 0.875 and i < PI * 1.125 or
                    i > PI * 0.375 and i < PI * 0.625 or
                    i > PI * 1.375 and i < PI * 1.625
                then
                    renderDrawBox(xc + math.cos(i) * px, yc + math.sin(i) * px, 3, 3, 0x55007FFF)
                end
            end
        end

        local res1, but1, list1 = sampHasDialogRespond(900)
        if res1 and but1 == 1 then
            if list1 == 0 then state = not state; showmenu() end
            if list1 == 1 then settings.through_walls = not settings.through_walls; showmenu() end
            if list1 == 2 then sampShowDialog(901, "{00CC00}Введите радиус поиска", '', "ОК", "Закрыть", 1) end
            if list1 == 3 then settings.show_circle = not settings.show_circle; showmenu() end
            if list1 == 4 then sampShowDialog(902, "{00CC00}Введите кнопку активации", '', "ОК", "Закрыть", 1) end
            if list1 == 5 then sampShowDialog(903, "{00CC00}Введите лимит дистанции", '', "ОК", "Закрыть", 1) end
            if list1 == 6 then sampShowDialog(904, "{00CC00}Введите вероятность промаха", '', "ОК", "Закрыть", 1) end
            if list1 == 7 then debugMode = not debugMode; showmenu() end
            if list1 == 8 then sampShowDialog(905, "{00CC00}Silent Aim by astynk | Справка", faqtext, "ОК") end
        end

        local res2, but2, list2, input2 = sampHasDialogRespond(901)
        if res2 and but2 == 1 then
            input2 = tonumber(input2)
            if not input2 or input2 < 0 or input2 > 100 then
                sampAddChatMessage('Введено неверное значение.', 0xAFAFAF)
            else
                settings.field_of_search = input2
            end
            showmenu()
        end
        if res2 and but2 == 0 then showmenu() end

        local res3, but3, list3, input3 = sampHasDialogRespond(902)
        if res3 and but3 == 1 then
            local k = keys.name_to_id(input3)
            if not k then
                sampAddChatMessage('Введено некорректное название клавиши.', 0xAFAFAF)
            else
                settings.key_activation = k
            end
            showmenu()
        end
        if res3 and but3 == 0 then showmenu() end

        local res4, but4, list4, input4 = sampHasDialogRespond(903)
        if res4 and but4 == 1 then
            input4 = tonumber(input4)
            if not input4 or input4 < 0 or input4 > 1000 then
                sampAddChatMessage('Введено неверное значение.', 0xAFAFAF)
            else
                settings.max_distance = input4
            end
            showmenu()
        end
        if res4 and but4 == 0 then showmenu() end

        local res5, but5, list5, input5 = sampHasDialogRespond(904)
        if res5 and but5 == 1 then
            input5 = tonumber(input5)
            if not input5 or input5 < 0 or input5 > 100 then
                sampAddChatMessage('Введено неверное значение.', 0xAFAFAF)
            else
                settings.miss_ratio = input5
            end
            showmenu()
        end
        if res5 and but5 == 0 then showmenu() end


        local res6, but6, list6, input6 = sampHasDialogRespond(905)
        if res6 then
            showmenu()
        end

        [COLOR=rgb(209, 72, 65)]if wasKeyPressed(settings.key_activation) and not (sampIsChatInputActive() or sampIsDialogActive()) then
                state = not state
                print( and 'ВКЛ' or 'ВЫКЛ')[/COLOR]
        end
    end
end
Подскажи, пожалуйста, чайнику, как поставить чтобы при активации был один звук, а при выключении другой. Я пытался пытался, но ничего не вышло :D
Lua:
if wasKeyPressed(settings.key_activation) and not (sampIsChatInputActive() or sampIsDialogActive()) then
    state = not state
    print( and 'ВКЛ' or 'ВЫКЛ')
    if state then addOneOffSound(0, 0, 0, 1137) else addOneOffSound(0, 0, 0, 1138) end
end
 
  • Влюблен
Реакции: Narkizo

Sanchez.

Известный
704
187
У меня вопрос. Какой код легче и лучше? (они одинаковые, только измененные)

1 код:
Lua:
function cmd_givepass(arg)
    var1 = string.match(arg, "(%d+)")
    if var1 == nill or var1 == ""
    then
        sampAddChatMessage(tag .. "Введите: /givepass [id]", -1)
    else
        lua_thread.create(function()
        sampSendChat("/me достал чистый бланк из под стола")
        wait(1400)
        sampSendChat("/me достал ручку и начал заполнять документы")
        wait(1400)
        sampSendChat("/do Бланк документов заполнен.")
        wait(1400)
        sampSendChat("/me положил бланки в папку и передал человеку паспорт")
        wait(1)
        sampSendChat('/givepass ' ..var1) end)
    end
    end

2 код:
Код:
function cmd_givepass(arg)
    if #arg == 0
    then
        sampAddChatMessage(tag .. "Введите: /givepass [id]", -1)
    else
        lua_thread.create(function()
        sampSendChat("/me достал чистый бланк из под стола")
        wait(1400)
        sampSendChat("/me достал ручку и начал заполнять документы")
        wait(1400)
        sampSendChat("/do Бланк документов заполнен.")
        wait(1400)
        sampSendChat("/me положил бланки в папку и передал человеку паспорт")
        wait(1)
        sampSendChat('/givepass ' .. arg) end)
    end
    end
 

Squeezy737

Известный
14
2
У меня вопрос. Какой код легче и лучше? (они одинаковые, только измененные)

1 код:
Lua:
function cmd_givepass(arg)
    var1 = string.match(arg, "(%d+)")
    if var1 == nill or var1 == ""
    then
        sampAddChatMessage(tag .. "Введите: /givepass [id]", -1)
    else
        lua_thread.create(function()
        sampSendChat("/me достал чистый бланк из под стола")
        wait(1400)
        sampSendChat("/me достал ручку и начал заполнять документы")
        wait(1400)
        sampSendChat("/do Бланк документов заполнен.")
        wait(1400)
        sampSendChat("/me положил бланки в папку и передал человеку паспорт")
        wait(1)
        sampSendChat('/givepass ' ..var1) end)
    end
    end

2 код:
Код:
function cmd_givepass(arg)
    if #arg == 0
    then
        sampAddChatMessage(tag .. "Введите: /givepass [id]", -1)
    else
        lua_thread.create(function()
        sampSendChat("/me достал чистый бланк из под стола")
        wait(1400)
        sampSendChat("/me достал ручку и начал заполнять документы")
        wait(1400)
        sampSendChat("/do Бланк документов заполнен.")
        wait(1400)
        sampSendChat("/me положил бланки в папку и передал человеку паспорт")
        wait(1)
        sampSendChat('/givepass ' .. arg) end)
    end
    end
второй вроде как)
 

Squeezy737

Известный
14
2
Lua:
if window_setting.v then
    local sw, sh = getScreenResolution()
    imgui.SetNextWindowSize(imgui.ImVec2(400, 350), imgui.Cond.FirstUseEver) -- задать размер окна
    imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5)) -- задать позицию окна
    imgui.Begin(u8'Настройки##1', window_setting, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoMove)
        imgui.BeginChild('childwindow', imgui.ImVec2(385, 280), true)
        imgui.Text(u8'Ваш никнейм: ')
        imgui.SameLine()
        imgui.PushItemWidth(200)
        imgui.InputText('##nick', textname)
        imgui.PopItemWidth()
        imgui.Text(u8'Ваша организация: ')
        imgui.SameLine()
        imgui.PushItemWidth(200)
        imgui.InputText('##frak', textfrak)
        imgui.PopItemWidth()
        imgui.Text(u8'Ваша должность: ')
        imgui.SameLine()
        imgui.PushItemWidth(200)
        imgui.InputText('##rang', textrang)
        imgui.PopItemWidth()
        imgui.Separator()
        imgui.EndChild()
        imgui.SetCursorPosX(320)
        if imgui.Button(u8'Сохранить') then
                if textname.v == '' then textname.v = 'Name Surname' end
                if textfrak.v == '' then textfrak.v = '«СМИ г. »' end
                if textrang.v == '' then textrang.v = 'репортер' end
                local data =
                {
                    main =
                    {
                        nickname = u8:decode(textname.v),
                        rang = u8:decode(textrang.v),
                        frak = u8:decode(textfrak.v),
                    },
                };
                iniwrite('moonloader/config/efir.ini', data);
                sampAddChatMessage('Новые настройки были успешно применены.', color)
                updatesettings()
            end

Подскажите почему не срабатывает updatesettings?

Ошибка:


[ML] (error) efir: D:\Nikita\Clear\moonloader\efir.lua:180: attempt to call global 'updatesettings' (a nil value)
stack traceback:
D:\Nikita\Clear\moonloader\efir.lua:180: in function 'OnDrawFrame'
D:\Nikita\Clear\moonloader\lib\imgui.lua:1378: in function <D:\Nikita\Clear\moonloader\lib\imgui.lua:1367>
[ML] (error) efir: Script died due to an error. (01A591E4)
помогите
 

Sanchez.

Известный
704
187
Lua:
script_name('[Absolute RP] SMI Helper')
script_author('Sanchez.')
script_description('SMI Helper for Absolute Role Play.')

require "lib.moonloader"

local encoding = require 'encoding'
local imgui = require 'imgui'
local sampev = require 'lib.samp.events'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local tag = "{1E90FF}SMI {FFFFFF}Helper: "

local selected = 1

local fa = require 'faIcons'
local fa_glyph_ranges = imgui.ImGlyphRanges({ fa.min_range, fa.max_range })

function imgui.BeforeDrawFrame()
    if fa_font == nil then
        local font_config = imgui.ImFontConfig()
        font_config.MergeMode = true
        fa_font = imgui.GetIO().Fonts:AddFontFromFileTTF('moonloader/resource/fonts/fontawesome-webfont.ttf', 14.0, font_config, fa_glyph_ranges)
    end
end

local main_window_state = imgui.ImBool(false)
local sw, sh = getScreenResolution() -- получить разрешение экрана

local checked_radio = imgui.ImInt(1) -- Радио кнопка

function imgui.TextColoredRGB(text)
    local style = imgui.GetStyle()
    local colors = style.Colors
    local ImVec4 = imgui.ImVec4

    local explode_argb = function(argb)
        local a = bit.band(bit.rshift(argb, 24), 0xFF)
        local r = bit.band(bit.rshift(argb, 16), 0xFF)
        local g = bit.band(bit.rshift(argb, 8), 0xFF)
        local b = bit.band(argb, 0xFF)
        return a, r, g, b
    end

    local getcolor = function(color)
        if color:sub(1, 6):upper() == 'SSSSSS' then
            local r, g, b = colors[1].x, colors[1].y, colors[1].z
            local a = tonumber(color:sub(7, 8), 16) or colors[1].w * 255
            return ImVec4(r, g, b, a / 255)
        end
        local color = type(color) == 'string' and tonumber(color, 16) or color
        if type(color) ~= 'number' then return end
        local r, g, b, a = explode_argb(color)
        return imgui.ImColor(r, g, b, a):GetVec4()
    end

    local render_text = function(text_)
        for w in text_:gmatch('[^\r\n]+') do
            local text, colors_, m = {}, {}, 1
            w = w:gsub('{(......)}', '{%1FF}')
            while w:find('{........}') do
                local n, k = w:find('{........}')
                local color = getcolor(w:sub(n + 1, k - 1))
                if color then
                    text[#text], text[#text + 1] = w:sub(m, n - 1), w:sub(k + 1, #w)
                    colors_[#colors_ + 1] = color
                    m = n
                end
                w = w:sub(1, n - 1) .. w:sub(k + 1, #w)
            end
            if text[0] then
                for i = 0, #text do
                    imgui.TextColored(colors_[i] or colors[1], u8(text[i]))
                    imgui.SameLine(nil, 0)
                end
                imgui.NewLine()
            else imgui.Text(u8(w)) end
        end
    end

    render_text(text)
end

function imgui.TextQuestion(text)
    imgui.SameLine()
    imgui.TextDisabled('(?)')
    if imgui.IsItemHovered() then
        imgui.BeginTooltip()
        imgui.PushTextWrapPos(450)
        imgui.TextUnformatted(text)
        imgui.PopTextWrapPos()
        imgui.EndTooltip()
    end
end

function style() -- стиль имгуи
    imgui.SwitchContext()
    local style  = imgui.GetStyle()
    local colors = style.Colors
    local clr    = imgui.Col
    local ImVec4 = imgui.ImVec4
    local ImVec2 = imgui.ImVec2

    style.WindowPadding       = ImVec2(10, 10)
    style.WindowRounding      = 10
    style.ChildWindowRounding = 2
    style.FramePadding        = ImVec2(5, 4)
    style.FrameRounding       = 11
    style.ItemSpacing         = ImVec2(4, 4)
    style.TouchExtraPadding   = ImVec2(0, 0)
    style.IndentSpacing       = 21
    style.ScrollbarSize       = 16
    style.ScrollbarRounding   = 16
    style.GrabMinSize         = 11
    style.GrabRounding        = 16
    style.WindowTitleAlign    = ImVec2(0.5, 0.5)
    style.ButtonTextAlign     = ImVec2(0.5, 0.5)

    colors[clr.Text]                 = ImVec4(1.00, 1.00, 1.00, 1.00)
    colors[clr.TextDisabled]         = ImVec4(0.73, 0.75, 0.74, 1.00)
    colors[clr.WindowBg]             = ImVec4(0.09, 0.09, 0.09, 0.94)
    colors[clr.ChildWindowBg]        = ImVec4(10.00, 10.00, 10.00, 0.01)
    colors[clr.PopupBg]              = ImVec4(0.08, 0.08, 0.08, 0.94)
    colors[clr.Border]               = ImVec4(0.20, 0.20, 0.20, 0.50)
    colors[clr.BorderShadow]         = ImVec4(0.00, 0.00, 0.00, 0.00)
    colors[clr.FrameBg]              = ImVec4(0.00, 0.39, 1.00, 0.65)
    colors[clr.FrameBgHovered]       = ImVec4(0.11, 0.40, 0.69, 1.00)
    colors[clr.FrameBgActive]        = ImVec4(0.11, 0.40, 0.69, 1.00)
    colors[clr.TitleBg]              = ImVec4(0.00, 0.00, 0.00, 1.00)
    colors[clr.TitleBgActive]        = ImVec4(0.00, 0.24, 0.54, 1.00)
    colors[clr.TitleBgCollapsed]     = ImVec4(0.00, 0.22, 1.00, 0.67)
    colors[clr.MenuBarBg]            = ImVec4(0.08, 0.44, 1.00, 1.00)
    colors[clr.ScrollbarBg]          = ImVec4(0.02, 0.02, 0.02, 0.53)
    colors[clr.ScrollbarGrab]        = ImVec4(0.31, 0.31, 0.31, 1.00)
    colors[clr.ScrollbarGrabHovered] = ImVec4(0.41, 0.41, 0.41, 1.00)
    colors[clr.ScrollbarGrabActive]  = ImVec4(0.51, 0.51, 0.51, 1.00)
    colors[clr.ComboBg]              = ImVec4(0.20, 0.20, 0.20, 0.99)
    colors[clr.CheckMark]            = ImVec4(1.00, 1.00, 1.00, 1.00)
    colors[clr.SliderGrab]           = ImVec4(0.34, 0.67, 1.00, 1.00)
    colors[clr.SliderGrabActive]     = ImVec4(0.84, 0.66, 0.66, 1.00)
    colors[clr.Button]               = ImVec4(0.00, 0.39, 1.00, 0.65)
    colors[clr.ButtonHovered]        = ImVec4(0.00, 0.64, 1.00, 0.65)
    colors[clr.ButtonActive]         = ImVec4(0.00, 0.53, 1.00, 0.50)
    colors[clr.Header]               = ImVec4(0.00, 0.62, 1.00, 0.54)
    colors[clr.HeaderHovered]        = ImVec4(0.00, 0.36, 1.00, 0.65)
    colors[clr.HeaderActive]         = ImVec4(0.00, 0.53, 1.00, 0.00)
    colors[clr.Separator]            = ImVec4(0.43, 0.43, 0.50, 0.50)
    colors[clr.SeparatorHovered]     = ImVec4(0.71, 0.39, 0.39, 0.54)
    colors[clr.SeparatorActive]      = ImVec4(0.71, 0.39, 0.39, 0.54)
    colors[clr.ResizeGrip]           = ImVec4(0.71, 0.39, 0.39, 0.54)
    colors[clr.ResizeGripHovered]    = ImVec4(0.84, 0.66, 0.66, 0.66)
    colors[clr.ResizeGripActive]     = ImVec4(0.84, 0.66, 0.66, 0.66)
    colors[clr.CloseButton]          = ImVec4(0.41, 0.41, 0.41, 1.00)
    colors[clr.CloseButtonHovered]   = ImVec4(0.98, 0.39, 0.36, 1.00)
    colors[clr.CloseButtonActive]    = ImVec4(0.98, 0.39, 0.36, 1.00)
    colors[clr.PlotLines]            = ImVec4(0.61, 0.61, 0.61, 1.00)
    colors[clr.PlotLinesHovered]     = ImVec4(1.00, 0.43, 0.35, 1.00)
    colors[clr.PlotHistogram]        = ImVec4(0.90, 0.70, 0.00, 1.00)
    colors[clr.PlotHistogramHovered] = ImVec4(1.00, 0.60, 0.00, 1.00)
    colors[clr.TextSelectedBg]       = ImVec4(0.26, 0.59, 0.98, 0.35)
    colors[clr.ModalWindowDarkening] = ImVec4(0.80, 0.80, 0.80, 0.35)
end
style()

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end

    while not isSampAvailable() do wait(100) end

    sampAddChatMessage(tag .. "{FFFFFF}Скрипт для радиоцентра: включен! Автор: {1E90FF}Sanchez.", -1)


    while true do
        wait(0)

        if sampGetCurrentDialogId() == 32 and sampIsDialogActive() then
            main_window_state.v = true
            imgui.Process = true
        else
            main_window_state.v = false
            imgui.Process = false
        end
    end

    imgui.Process = false

end

function imgui.OnDrawFrame()

    imgui.SetNextWindowSize(imgui.ImVec2(420, 300), imgui.Cond.FirstUseEver)

    imgui.SetNextWindowPos(imgui.ImVec2((sw / 1.3), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))

    --imgui.WindowFlags.NoResize

    imgui.Begin(fa.ICON_BULLHORN .. u8" Помощник для объявлений.", main_window_state, imgui.WindowFlags.NoCollapse)
    --imgui.SameLine(150)
    imgui.BeginChild("Select Gorod", imgui.ImVec2(135, 108), true)
        imgui.Text(u8"Выберите город:") imgui.TextQuestion(u8"Вы должны выбрать тот город, в котором вы работаете. (ОБЯЗАТЕЛЬНО!)")
        if imgui.Button(fa.ICON_GLOBE .. u8" LS", selected == 2) then selected = 1 end
        if imgui.Button(fa.ICON_GLOBE .. u8" LV", selected == 3) then selected = 2 end
        if imgui.Button(fa.ICON_GLOBE .. u8" SF", selected == 4) then selected = 3 end
   -- if imgui.Button(u8"Куплю машину", imgui.ImVec2(175, 40)) then
    --     sampSetCurrentDialogEditboxText('Куплю автомобиль марки "". Цена: ')
    --end
    imgui.EndChild()
    imgui.SameLine()
    imgui.BeginChild("Osnova", imgui.ImVec2(-1, -1), true)
        if selected == 0 then
            -- LS -----------------------
        elseif selected == 1 then
            imgui.SameLine(45) imgui.Text(u8"Выбрано:") imgui.SameLine() imgui.TextColoredRGB("{00FF00}LS (Los-Santos)")
            if imgui.CollapsingHeader(fa.ICON_CAR .. u8" Покупка/продажа Т.С " .. fa.ICON_MOTORCYCLE) then
                imgui.BeginChild("1", imgui.ImVec2(-1, 175), true)
                imgui.SameLine(75) imgui.Text(fa.ICON_CAR .. u8" Машины:")
                if imgui.Button(u8"Куплю машину. Цена в цифрах", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Куплю автомобиль марки " ". Цена: $')
                end
                if imgui.Button(u8"Куплю машину. Цена: договорн.", imgui.ImVec2(203, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Куплю автомобиль марки " ". Цена: договорная')
                end
                imgui.Text("")
                imgui.Separator()
                imgui.Text("")
                if imgui.Button(u8"Продам машину. Цена в цифрах", imgui.ImVec2(198, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Продам автомобиль марки " ". Цена: $')
                end
                if imgui.Button(u8"Продам машину. Цена: договорн.", imgui.ImVec2(207, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Продам автомобиль марки " ". Цена: договорная')
                end
                imgui.Separator()
                imgui.Text("")
                imgui.SameLine(70) imgui.Text(fa.ICON_MOTORCYCLE .. u8" Мотоциклы:")
                if imgui.Button(u8"Куплю мото. Цена в цифрах", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Куплю мотоцикл марки " ". Цена: $')
                end
                if imgui.Button(u8"Куплю мото. Цена: договорн.", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Куплю мотоцикл марки " ". Цена: договорная')
                end
                imgui.Text("")
                imgui.Separator()
                imgui.Text("")
                if imgui.Button(u8"Продам мото. Цена в цифрах", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Продам мотоцикл марки " ". Цена: $')
                end
                if imgui.Button(u8"Продам мото. Цена: договорн.", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Продам мотоцикл марки " ". Цена: договорная')
                end


                imgui.EndChild()
            end
            if imgui.CollapsingHeader(fa.ICON_HOME .. u8" Покупка/продажа домов " .. fa.ICON_HOME) then
                imgui.BeginChild("11", imgui.ImVec2(-1, 500), true)
                imgui.SameLine(45) imgui.Text(fa.ICON_HOME .. u8" Дома в г. Лос-Сантос:")
                if imgui.Button(u8"Куплю дом. Цена в цифрах", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Куплю дом ?-го класса в г. Лос-Сантос. Цена: $')
                end
                if imgui.Button(u8"Куплю дом. Цена договорн.", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Куплю дом ?-го класса в г. Лос-Сантос. Цена: договорная')
                end
                imgui.Text("")
                imgui.Separator() imgui.Text("")
                if imgui.Button(u8"Продам дом. Цена в цифрах", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Продам дом ?-го класса в г. Лос-Сантос. Цена: $')
                end
                if imgui.Button(u8"Продам дом. Цена договорн.", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Продам дом ?-го класса в г. Лос-Сантос. Цена: договорная')
                end
                imgui.Text("")
                imgui.Separator() imgui.Text("")
                imgui.SameLine(40) imgui.Text(fa.ICON_HOME .. u8" Дома в г. Лас-Вентурас:")
                if imgui.Button(u8"Куплю дом. Цена в цифрах", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Куплю дом ?-го класса в г. Лас-Вентурас. Цена: $')
                end
                if imgui.Button(u8"Куплю дом. Цена договорн.", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Куплю дом ?-го класса в г. Лас-Вентурас. Цена: договорная')
                end
                imgui.Text("")
                imgui.Separator() imgui.Text("")
                if imgui.Button(u8"Продам дом. Цена в цифрах", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Продам дом ?-го класса в г. Лас-Вентурас. Цена: $')
                end
                if imgui.Button(u8"Продам дом. Цена договорн.", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Продам дом ?-го класса в г. Лас-Вентурас. Цена: договорная')
                end
                imgui.Text("")
                imgui.Separator()
                imgui.Text("")
                imgui.SameLine(40) imgui.Text(fa.ICON_HOME .. u8" Дома в г. Сан-Фиерро:")
                if imgui.Button(u8"Куплю дом. Цена в цифрах", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Куплю дом ?-го класса в г. Сан-Фиерро. Цена: $')
                end
                if imgui.Button(u8"Куплю дом. Цена договорн.", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Куплю дом ?-го класса в г. Сан-Фиерро. Цена: договорная')
                end
                imgui.Text("")
                imgui.Separator() imgui.Text("")
                if imgui.Button(u8"Продам дом. Цена в цифрах", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Продам дом ?-го класса в г. Сан-Фиерро. Цена: $')
                end
                if imgui.Button(u8"Продам дом. Цена договорн.", imgui.ImVec2(190, 22)) then
                    sampSetCurrentDialogEditboxText('LS | Продам дом ?-го класса в г. Сан-Фиерро. Цена: договорная')
                end
                imgui.EndChild()
            end
            -- LS ------------------------------


            -- LV ------------------------
        elseif selected == 2 then
            imgui.SameLine(45) imgui.Text(u8"Выбрано:") imgui.SameLine() imgui.TextColoredRGB("{00FF00}LV (Las-Venturas)")
            if imgui.CollapsingHeader(fa.ICON_CAR .. u8" Покупка/продажа Т.С " .. fa.ICON_MOTORCYCLE) then -- не обращать внимания
                imgui.BeginChild("2", imgui.ImVec2(-1, 100), true) -- то что будет в колапсе
                imgui.Text(u8"ауе ауе")
                imgui.EndChild()
            end
            if imgui.CollapsingHeader(fa.ICON_HOME .. u8" Покупка/продажа домов " .. fa.ICON_HOME) then -- не обращать внимания
                imgui.BeginChild("22", imgui.ImVec2(-1, 100), true)
                imgui.Text(u8"ауе ауе")
                imgui.EndChild()
            end
            -- LV ---------------------------


            -- SF -----------------------------
        elseif selected == 3 then
            imgui.SameLine(45) imgui.Text(u8"Выбрано:") imgui.SameLine() imgui.TextColoredRGB("{00FF00}SF (San-Fierro)")
            if imgui.CollapsingHeader(fa.ICON_CAR .. u8" Покупка/продажа Т.С " .. fa.ICON_MOTORCYCLE) then -- не обращать внимания
                imgui.BeginChild("3", imgui.ImVec2(-1, 100), true)
                imgui.Text(u8"ауе ауе")
                imgui.EndChild()
            end
            if imgui.CollapsingHeader(fa.ICON_HOME .. u8" Покупка/продажа домов " .. fa.ICON_HOME) then -- не обращать внимания
                imgui.BeginChild("33", imgui.ImVec2(-1, 100), true)
                imgui.Text(u8"ауе ауе")
                imgui.EndChild()
            end
        end
            -- SF ---------------------------

    imgui.EndChild()

    --imgui.SameLine()


    --imgui.BeginChild("Gorod", imgui.ImVec2(185, 60), true)

    --imgui.Text(u8"Выберите ваш город")

--    imgui.RadioButton("LS", checked_radio, 1)
--    imgui.RadioButton("LV", checked_radio, 2)
--    imgui.RadioButton("SF", checked_radio, 3)

--    imgui.EndChild()

    imgui.End()
end
Короче, делаю скрипт для радиоцентра (для абсолют рп), и у меня все началось с if imgui.CollapsingHeader(fa.ICON_HOME .. u8" Покупка/продажа домов " .. fa.ICON_HOME) then. У меня работает вставка текста в диалог с городом Лос-Сантос, а с другими городами не работает. Что делать? Вот видео:
так кто нибудь поможет?
 

Squeezy737

Известный
14
2
you must show the code where the function is executed.
Lua:
iniwrite('moonloader/config/efir.ini', data);
                sampAddChatMessage('Новые настройки были успешно применены.', color)
                updatesettings()
if there is no problem, show the complete code
Lua:
function iniwrite(fileName, data)
    assert(type(fileName) == 'string', 'Parameter "fileName" must be a string.');
    assert(type(data) == 'table', 'Parameter "data" must be a table.');
    local file = assert(io.open(fileName, 'w+b'), 'Error loading file :' .. fileName);
    local contents = '';
    for section, param in pairs(data) do
        contents = contents .. ('[%s]\n'):format(section);
        for key, value in pairs(param) do
            contents = contents .. ('%s=%s\n'):format(key, tostring(value));
        end
        contents = contents .. '\n';
    end
    file:write(contents);
    file:close();
end
 

morti.

Участник
63
3
Lua:
require "lib.moonloader"
local sampev = require 'lib.samp.events'

function main()
   if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampAddChatMessage('test', -1)
    sampRegisterChatCommand(testing, func)
    lua = lua_thread.create(sampev.onServerMessage)
    while true do
        wait(0)
    end
end

function sampev.onServerMessage(color, text)
    if string.find (text, 'Передал вам оружие: ', 1, true) then
        wait(1000)
        sampSendChat('/dropgun')
    end
end

Что не так? Хелпаните. Вот код из moonloader.log:
Код:
[01:22:49.330529] (error)    huy.lua: D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:16: bad argument #1 to 'find' (string expected, got nil)
stack traceback:
    [C]: in function 'find'
    D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:16: in function <D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:15>
stack traceback:
    [C]: in function 'create'
    D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:9: in function <D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:4>
[01:22:49.330529] (error)    huy.lua: Script died due to an error. (88D1D16C)
 

Joni Scripts

Известный
535
374
Lua:
require "lib.moonloader"
local sampev = require 'lib.samp.events'

function main()
   if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampAddChatMessage('test', -1)
    sampRegisterChatCommand(testing, func)
    lua = lua_thread.create(sampev.onServerMessage)
    while true do
        wait(0)
    end
end

function sampev.onServerMessage(color, text)
    if string.find (text, 'Передал вам оружие: ', 1, true) then
        wait(1000)
        sampSendChat('/dropgun')
    end
end

Что не так? Хелпаните. Вот код из moonloader.log:
Код:
[01:22:49.330529] (error)    huy.lua: D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:16: bad argument #1 to 'find' (string expected, got nil)
stack traceback:
    [C]: in function 'find'
    D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:16: in function <D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:15>
stack traceback:
    [C]: in function 'create'
    D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:9: in function <D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:4>
[01:22:49.330529] (error)    huy.lua: Script died due to an error. (88D1D16C)
В 16 строке string замени на text
У тебя функция выдает text, а ты пытаешься проверить string
lua = lua_thread.create(sampev.onServerMessage) тоже можно убрать, это не нужно для работы
 
  • Нравится
Реакции: morti.

morti.

Участник
63
3
В 16 строке string замени на text
У тебя функция выдает text, а ты пытаешься проверить string
lua = lua_thread.create(sampev.onServerMessage) тоже можно убрать, это не нужно для работы
мне нужно задержку поставить, а вне main() wait просто так не прописать
 

ollydbg

Известный
163
113
Lua:
require "lib.moonloader"
local sampev = require 'lib.samp.events'

function main()
   if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampAddChatMessage('test', -1)
    sampRegisterChatCommand(testing, func)
    lua = lua_thread.create(sampev.onServerMessage)
    while true do
        wait(0)
    end
end

function sampev.onServerMessage(color, text)
    if string.find (text, 'Передал вам оружие: ', 1, true) then
        wait(1000)
        sampSendChat('/dropgun')
    end
end

Что не так? Хелпаните. Вот код из moonloader.log:
Код:
[01:22:49.330529] (error)    huy.lua: D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:16: bad argument #1 to 'find' (string expected, got nil)
stack traceback:
    [C]: in function 'find'
    D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:16: in function <D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:15>
stack traceback:
    [C]: in function 'create'
    D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:9: in function <D:\Games\ARIZONA GAMES\bin\Arizona\moonloader\huy.lua:4>
[01:22:49.330529] (error)    huy.lua: Script died due to an error. (88D1D16C)
Lua:
require "lib.moonloader"
local sampev = require 'lib.samp.events'

function main()
   if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    --sampRegisterChatCommand(testing, func)
    while true do
        wait(0)
    end
end

function sampev.onServerMessage(color, text)
    if string.find (text, 'Передал вам оружие: ', 1, true) then
        lua_thread.create(function()
        wait(1000)
         sampSendChat('/dropgun')
    end)
    end
end
or if you want to add wait you must do it like this
 
Последнее редактирование: