Вопросы по 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
 
Последнее редактирование:

trefa

Известный
Всефорумный модератор
2,097
1,233
Я сделал счетчик онлайна, как мне каждый день сохранять этот онлайн в ини файле. Весь онлайн за последние 7 дней по датам.
Типо:
07-08-2021: 02:50:55
08-08-2021: 02:50:53
09-08-2021: 02:20:52
10-08-2021: 02:40:56
11-08-2021: 02:50:55
12-08-2021: 02:50:54
13-08-2021: 02:00:54
Подскажите пожалуйста.
Lua:
ini[os.date("%x")] = os.clock()
 
  • Нравится
Реакции: McLore

niki4

Участник
92
10
Lua:
ini[os.date("%x")] = os.clock()
У меня переменная называется inicfg, то-есть нужно вот так было?
Lua:
local inicfg = require "inicfg"
    
local directIni = "moonloader\\config\\Jail-Helper.ini"
local mainIni = inicfg.load(nil,directIni)
local stateIni = inicfg.save(mainIni, directIni)

function main()
    
    while true do
        wait(0)
        function savetime()
            inicfg[os.date("%x")] = os.clock()
            inicfg.save(mainIni, directIni)
        end
    end
end
 

trefa

Известный
Всефорумный модератор
2,097
1,233
У меня переменная называется inicfg, то-есть нужно вот так было?
Lua:
local inicfg = require "inicfg"
    
local directIni = "moonloader\\config\\Jail-Helper.ini"
local mainIni = inicfg.load(nil,directIni)
local stateIni = inicfg.save(mainIni, directIni)

function main()
    
    while true do
        wait(0)
        function savetime()
            inicfg[os.date("%x")] = os.clock()
            inicfg.save(mainIni, directIni)
        end
    end
end
Читай основы, а особенно про таблицы.

Псс, кто очень хорошо шарит, подскажите, почему картинки при добавлении в imgui начинают дико жрать FPS, мб это как-то фиксится?
очень нужно решить эту проблему
Мб код?
 
Последнее редактирование:

sdfaw

Активный
718
150
Lua:
local sampev = require "lib.samp.events"
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then
    return
  end
  while not isSampAvailable() do
    wait(100)
  end
    wait(-1)
end

function sampev.onShowDialog(id, style, title, button1, button3, text)
if id == 2526 then
sampSendDialogResponse(2526, 0, nil, '#hateu')
end
end
почему не работает?
 

niki4

Участник
92
10
Читай основы, а особенно про таблицы.
Я посмотрел вики, такого примера как ты там нет.
Вот такой будет работать?

Lua:
local inicfg = require "inicfg"
    
local directIni = "moonloader\\config\\Jail-Helper.ini"
local mainIni = inicfg.load(nil,directIni)
local stateIni = inicfg.save(mainIni, directIni)

function main()
    
    while true do
        wait(0)
        function savetime()
            local date = {
            os.date("%x") = {
            param1=test
            param2=test
            }
            inicfg.save(mainIni, directIni)
        end
    end
end
 

Anton Nixon

Активный
474
48
Вот..
Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
        wait(200)
    while true do
        wait(0)
        imgui.Process = m_win.v
        local playerSkin = getCharModel(PLAYER_PED)
        skinPic = imgui.CreateTextureFromFile(getGameDirectory() .. '\\moonloader\\script\\images\\skins\\'..playerSkin..'.png')
        mlogo = imgui.CreateTextureFromFile(getGameDirectory() .. '\\moonloader\\script\\images\\img.png')
end

function imgui.OnDrawFrame()
    if m_win.v then
        if main_stat then
            imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
            imgui.SetNextWindowSize(imgui.ImVec2(360, 232), imgui.Cond.FirstUseEver)
            imgui.Begin(u8"##EXAMPLE", m_win, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoTitleBar)
                if imgui.Button(fa.ICON_FA_USER_EDIT..u8" Личный кабинет", btn) then
                    --personal.v = not personal.v
                    pers_stat = true
                    main_stat = false
                end
                if imgui.Button(fa.ICON_FA_SLIDERS_H..u8" Настройки", btn) then
                    --settings.v = not settings.v
                end
                if imgui.Button(fa.ICON_FA_INFO..u8" Помощь", btn) then
                    --help.v = not help.v
                end
                if imgui.Button(fa.ICON_FA_QUESTION..u8" Информация", btn) then
                    --about.v = not about.v
                end
                if imgui.Button(fa.ICON_FA_POWER_OFF..u8" Выключить скрипт", btn1) then
                    saveSettings()
                    thisScript():unload()
                end
                imgui.SameLine()
                if imgui.Button(fa.ICON_FA_SYNC..u8" Перезагрузка", btn1) then
                    saveSettings()
                    reload_script()
                end
            imgui.End()
        elseif pers_stat then
            imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
            imgui.SetNextWindowSize(imgui.ImVec2(700, 350), imgui.Cond.FirstUseEver)
            imgui.Begin("##personal", personal, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoTitleBar+ imgui.WindowFlags.NoMove)
                imgui.Columns(2, _, true)
                imgui.SetColumnWidth(-1, 260)
                imgui.SetCursorPosX((imgui.GetColumnWidth() - 75) / 2.5)
                imgui.Image(skinPic, imgui.ImVec2(120, 120))
                imgui.SetCursorPosX((imgui.GetColumnWidth() - 75) / 2)
                imgui.Text(myname)
                imgui.NewLine()
                imgui.Text(u8"Номер жетона: "..mid)
                imgui.Text(u8"Пол: "..(MAIN.personal.ssex))
                telephone = string.format(u8"Тел.: %s", hum_phone.v)
                imgui.Text(telephone)
                imgui.Text(u8"Подразделение: "..orgs.v)
                imgui.Text(u8"Звание: "..rangs.v)
                imgui.NewLine()
                imgui.Button(fa.ICON_FA_GLOBE_AMERICAS..u8" База Данных", btn4)
                imgui.NextColumn()
                if pers_edit_stat then
                    imgui.Text(u8"Укажите Ваш пол:")
                    imgui.PushItemWidth(100)
                    imgui.Combo(u8"##sex", select_sex, table_sex)
                    if select_sex.v == 0 then
                        ssex.v = table_sex[1]
                        MAIN.personal.ssex = ssex.v
                    elseif select_sex.v == 1 then
                        ssex.v = table_sex[2]
                        MAIN.personal.ssex = ssex.v
                    end
                    imgui.Text(u8"Введите Ваш номер телефона:")
                    imgui.PushItemWidth(160)
                    imgui.InputText(u8"##num_phone", hum_phone)
                    MAIN.personal.num_phone = hum_phone.v
                    imgui.Text(u8"Укажите Ваше подразделение:")
                    imgui.PushItemWidth(160)
                    imgui.Combo(u8"##org", selec_org, tab_org)
                    if selec_org == 0 then
                        org.v = table_org[1]
                        MAIN.personal.org = org.v
                    elseif selec_org == 1 then
                        org.v = table_org[2]
                        MAIN.personal.org = org.v
                    elseif selec_org == 2 then
                        org.v = table_org[3]
                        MAIN.personal.org = org.v
                    end
                    imgui.PushItemWidth(100)
                    imgui.Text(u8"Укажите Ваше звание:")
                    if select_org == 2 then
                        imgui.Combo(u8"##rang1", sel_rang, tabl_rang_1)
                        if sel_rang == 0 then
                            rang.v = table_rang[1]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 1 then
                            rang.v = table_rang[2]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 2 then
                            rang.v = table_rang[3]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 3 then
                            rang.v = table_rang[4]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 4 then
                            rang.v = table_rang[5]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 5 then
                            rang.v = table_rang[6]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 6 then
                            rang.v = table_rang[7]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 7 then
                            rang.v = table_rang[8]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 8 then
                            rang.v = table_rang[9]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 9 then
                            rang.v = table_rang[10]
                            MAIN.personal.rang = rang.v
                        end
                    else
                        imgui.Combo(u8"##rang2", sel_rang, ta_rang_2)
                        if sel_rang == 0 then
                            rang.v = table_rang[1]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 1 then
                            rang.v = table_rang[2]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 2 then
                            rang.v = table_rang[3]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 3 then
                            rang.v = table_rang[4]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 4 then
                            rang.v = table_rang[5]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 5 then
                            rang.v = table_rang[6]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 6 then
                            rang.v = table_rang[7]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 7 then
                            rang.v = table_rang[8]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 8 then
                            rang.v = table_rang[9]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 9 then
                            rang.v = table_rang[10]
                            MAIN.personal.rang = rang.v
                        end
                    end
                    imgui.NewLine()
                    if imgui.Button(fa.ICON_FA_SAVE..u8" Сохранить", btn2) then
                        saveSettings()
                    end
                    imgui.SameLine()
                    if imgui.Button(fa.ICON_FA_ANGLE_LEFT..u8"  Назад", btn2) then
                        pers_edit_stat = false
                        pers_stat = true
                    end
                else
                    imgui.SetCursorPosX((imgui.GetColumnWidth() - 75) * 1.11)
                    imgui.Image(mlogo,imgui.ImVec2(120, 120))
                    if imgui.Button(fa.ICON_FA_EDIT..u8" Редактировать", btn1) then
                        pers_edit_stat = true
                    end
                    imgui.SameLine()
                    if imgui.Button(fa.ICON_FA_ANGLE_LEFT..u8"  Назад", btn1) then
                        pers_stat = false
                        main_stat = true
                    end
                end
            imgui.End()

        end
    end
end
 

niki4

Участник
92
10
Lua:
local sampev = require "lib.samp.events"
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then
    return
  end
  while not isSampAvailable() do
    wait(100)
  end
    wait(-1)
end

function sampev.onShowDialog(id, style, title, button1, button3, text)
if id == 2526 then
sampSendDialogResponse(2526, 0, nil, '#hateu')
end
end
почему не работает?
Попробуй
Lua:
local sampev = require "lib.samp.events"
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then
    return
  end
  while not isSampAvailable() do
    wait(100)
  end
    wait(-1)
end

function sampev.onShowDialog(id, style, title, button1, button3, text)
if string.find(id,"2526") then
lua_thread.create(function()
wait(500)
sampSendDialogResponse(id, 0, nil, '#hateu')
end)
end
end
Попробуй
Lua:
local sampev = require "lib.samp.events"
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then
    return
  end
  while not isSampAvailable() do
    wait(100)
  end
    wait(-1)
end

function sampev.onShowDialog(id, style, title, button1, button3, text)
if string.find(id,"2526") then
lua_thread.create(function()
wait(500)
sampSendDialogResponse(id, 0, nil, '#hateu')
end)
end
end
К тому же у тебя просто функция, которая нигде не задействована и не будет работать(я так думаю)
 

sdfaw

Активный
718
150
Попробуй
Lua:
local sampev = require "lib.samp.events"
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then
    return
  end
  while not isSampAvailable() do
    wait(100)
  end
    wait(-1)
end

function sampev.onShowDialog(id, style, title, button1, button3, text)
if string.find(id,"2526") then
lua_thread.create(function()
wait(500)
sampSendDialogResponse(id, 0, nil, '#hateu')
end)
end
end

К тому же у тебя просто функция, которая нигде не задействована и не будет работать(я так думаю)
не работает
 

trefa

Известный
Всефорумный модератор
2,097
1,233
Я посмотрел вики, такого примера как ты там нет.
Вот такой будет работать?

Lua:
local inicfg = require "inicfg"
    
local directIni = "moonloader\\config\\Jail-Helper.ini"
local mainIni = inicfg.load(nil,directIni)
local stateIni = inicfg.save(mainIni, directIni)

function main()
    
    while true do
        wait(0)
        function savetime()
            local date = {
            os.date("%x") = {
            param1=test
            param2=test
            }
            inicfg.save(mainIni, directIni)
        end
    end
end
google.com
какое вики, вики только для функций муна. Остальное все в гугле.

Вот..
Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
        wait(200)
    while true do
        wait(0)
        imgui.Process = m_win.v
        local playerSkin = getCharModel(PLAYER_PED)
        skinPic = imgui.CreateTextureFromFile(getGameDirectory() .. '\\moonloader\\script\\images\\skins\\'..playerSkin..'.png')
        mlogo = imgui.CreateTextureFromFile(getGameDirectory() .. '\\moonloader\\script\\images\\img.png')
end

function imgui.OnDrawFrame()
    if m_win.v then
        if main_stat then
            imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
            imgui.SetNextWindowSize(imgui.ImVec2(360, 232), imgui.Cond.FirstUseEver)
            imgui.Begin(u8"##EXAMPLE", m_win, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoTitleBar)
                if imgui.Button(fa.ICON_FA_USER_EDIT..u8" Личный кабинет", btn) then
                    --personal.v = not personal.v
                    pers_stat = true
                    main_stat = false
                end
                if imgui.Button(fa.ICON_FA_SLIDERS_H..u8" Настройки", btn) then
                    --settings.v = not settings.v
                end
                if imgui.Button(fa.ICON_FA_INFO..u8" Помощь", btn) then
                    --help.v = not help.v
                end
                if imgui.Button(fa.ICON_FA_QUESTION..u8" Информация", btn) then
                    --about.v = not about.v
                end
                if imgui.Button(fa.ICON_FA_POWER_OFF..u8" Выключить скрипт", btn1) then
                    saveSettings()
                    thisScript():unload()
                end
                imgui.SameLine()
                if imgui.Button(fa.ICON_FA_SYNC..u8" Перезагрузка", btn1) then
                    saveSettings()
                    reload_script()
                end
            imgui.End()
        elseif pers_stat then
            imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
            imgui.SetNextWindowSize(imgui.ImVec2(700, 350), imgui.Cond.FirstUseEver)
            imgui.Begin("##personal", personal, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoTitleBar+ imgui.WindowFlags.NoMove)
                imgui.Columns(2, _, true)
                imgui.SetColumnWidth(-1, 260)
                imgui.SetCursorPosX((imgui.GetColumnWidth() - 75) / 2.5)
                imgui.Image(skinPic, imgui.ImVec2(120, 120))
                imgui.SetCursorPosX((imgui.GetColumnWidth() - 75) / 2)
                imgui.Text(myname)
                imgui.NewLine()
                imgui.Text(u8"Номер жетона: "..mid)
                imgui.Text(u8"Пол: "..(MAIN.personal.ssex))
                telephone = string.format(u8"Тел.: %s", hum_phone.v)
                imgui.Text(telephone)
                imgui.Text(u8"Подразделение: "..orgs.v)
                imgui.Text(u8"Звание: "..rangs.v)
                imgui.NewLine()
                imgui.Button(fa.ICON_FA_GLOBE_AMERICAS..u8" База Данных", btn4)
                imgui.NextColumn()
                if pers_edit_stat then
                    imgui.Text(u8"Укажите Ваш пол:")
                    imgui.PushItemWidth(100)
                    imgui.Combo(u8"##sex", select_sex, table_sex)
                    if select_sex.v == 0 then
                        ssex.v = table_sex[1]
                        MAIN.personal.ssex = ssex.v
                    elseif select_sex.v == 1 then
                        ssex.v = table_sex[2]
                        MAIN.personal.ssex = ssex.v
                    end
                    imgui.Text(u8"Введите Ваш номер телефона:")
                    imgui.PushItemWidth(160)
                    imgui.InputText(u8"##num_phone", hum_phone)
                    MAIN.personal.num_phone = hum_phone.v
                    imgui.Text(u8"Укажите Ваше подразделение:")
                    imgui.PushItemWidth(160)
                    imgui.Combo(u8"##org", selec_org, tab_org)
                    if selec_org == 0 then
                        org.v = table_org[1]
                        MAIN.personal.org = org.v
                    elseif selec_org == 1 then
                        org.v = table_org[2]
                        MAIN.personal.org = org.v
                    elseif selec_org == 2 then
                        org.v = table_org[3]
                        MAIN.personal.org = org.v
                    end
                    imgui.PushItemWidth(100)
                    imgui.Text(u8"Укажите Ваше звание:")
                    if select_org == 2 then
                        imgui.Combo(u8"##rang1", sel_rang, tabl_rang_1)
                        if sel_rang == 0 then
                            rang.v = table_rang[1]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 1 then
                            rang.v = table_rang[2]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 2 then
                            rang.v = table_rang[3]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 3 then
                            rang.v = table_rang[4]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 4 then
                            rang.v = table_rang[5]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 5 then
                            rang.v = table_rang[6]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 6 then
                            rang.v = table_rang[7]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 7 then
                            rang.v = table_rang[8]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 8 then
                            rang.v = table_rang[9]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 9 then
                            rang.v = table_rang[10]
                            MAIN.personal.rang = rang.v
                        end
                    else
                        imgui.Combo(u8"##rang2", sel_rang, ta_rang_2)
                        if sel_rang == 0 then
                            rang.v = table_rang[1]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 1 then
                            rang.v = table_rang[2]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 2 then
                            rang.v = table_rang[3]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 3 then
                            rang.v = table_rang[4]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 4 then
                            rang.v = table_rang[5]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 5 then
                            rang.v = table_rang[6]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 6 then
                            rang.v = table_rang[7]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 7 then
                            rang.v = table_rang[8]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 8 then
                            rang.v = table_rang[9]
                            MAIN.personal.rang = rang.v
                        elseif sel_rang == 9 then
                            rang.v = table_rang[10]
                            MAIN.personal.rang = rang.v
                        end
                    end
                    imgui.NewLine()
                    if imgui.Button(fa.ICON_FA_SAVE..u8" Сохранить", btn2) then
                        saveSettings()
                    end
                    imgui.SameLine()
                    if imgui.Button(fa.ICON_FA_ANGLE_LEFT..u8"  Назад", btn2) then
                        pers_edit_stat = false
                        pers_stat = true
                    end
                else
                    imgui.SetCursorPosX((imgui.GetColumnWidth() - 75) * 1.11)
                    imgui.Image(mlogo,imgui.ImVec2(120, 120))
                    if imgui.Button(fa.ICON_FA_EDIT..u8" Редактировать", btn1) then
                        pers_edit_stat = true
                    end
                    imgui.SameLine()
                    if imgui.Button(fa.ICON_FA_ANGLE_LEFT..u8"  Назад", btn1) then
                        pers_stat = false
                        main_stat = true
                    end
                end
            imgui.End()

        end
    end
end
У тебя каждый кадр загружается картинка, убирай подгрузку из цикла.
 
Последнее редактирование:
  • Нравится
Реакции: Anton Nixon

Anton Nixon

Активный
474
48
У тебя каждый кадр загружается картинка, убирай подгрузку из цикла.
Смотри, убираю подгрузку картинок из цикла,
остается переменная на получение скина по хендлу в цикле
playerSkin = getCharModel(PLAYER_PED),
но тогда выбивает ошибку attempt to concatenate global 'playerSkin' (a nil value)
Если убрать эту переменную из цикла, то без перезагрузки скрипта не меняются картинки при смене скина, есть варик как сделать чтобы это работало как надо?
 

gucci-scripts

Участник
64
10
function ezd()
sampSendChat(u8:decode(rand1.v))
wait(waitb.v)
sampSendChat(u8:decode(rand3.v))
end
Почему команда не робит
 
Последнее редактирование:

Pasquale Developer

Известный
109
8
lua:
function cmd_rang(text)
    if text:find("^%d+$") then
        if tonumber(text) and (sampIsPlayerConnected(text) or (tonumber(text) == select(2, sampGetPlayerIdByCharHandle(playerPed))) ) then
            lua_thread.create(function()
                sampSendChat(("/do Бейджик в руках %s форма для %s."):format(sampGetPlayerNickname(select(2, sampGetPlayerIdByCharHandle(playerPed))):gsub("_", " "), sampGetPlayerNickname(tonumber(text)):gsub("_", " ")))
                wait(500)
                sampSendChat("/me легким движением рук, передает новый бейджик человеку напротив")
                wait(500)
                sampSendChat(("/rang %d %s"):format(tonumber(text)))
                wait(500)
                sampSendChat("/anim 21")
                wait(700)
                sampSendChat('/do Бейджик передан')
            end)
        else sampAddChatMessage("FF0000}[LUA]{FF8C00} Игрок с данным ID не подключен к серверу.", 0xFFFF0000) end
    else sampAddChatMessage("{FF0000}[LUA] {FF8C00}Используйте: /rang [ID] [+ или -]", 0xFFFF0000) end
end


Можете сказать почему выдает мол неверный формат.

Ввожу /rang 90 +. оно мне такое:


image.png
 

niki4

Участник
92
10
function ezd()
sampSendChat(u8:decode(rand1.v))
wait(waitb.v)
sampSendChat(u8:decode(rand3.v))
end
Почему команда не робит
Функцию wait нельзя использовать вне function main()
Чтобы пофиксить создай поток. Просто сделай такой код:

Lua:
function ezd()
    lua_thread.create(function()
        sampSendChat(u8:decode(rand1.v))
        wait(waitb.v)
        sampSendChat(u8:decode(rand3.v))
    end)
end
lua:
function cmd_rang(text)
    if text:find("^%d+$") then
        if tonumber(text) and (sampIsPlayerConnected(text) or (tonumber(text) == select(2, sampGetPlayerIdByCharHandle(playerPed))) ) then
            lua_thread.create(function()
                sampSendChat(("/do Бейджик в руках %s форма для %s."):format(sampGetPlayerNickname(select(2, sampGetPlayerIdByCharHandle(playerPed))):gsub("_", " "), sampGetPlayerNickname(tonumber(text)):gsub("_", " ")))
                wait(500)
                sampSendChat("/me легким движением рук, передает новый бейджик человеку напротив")
                wait(500)
                sampSendChat(("/rang %d %s"):format(tonumber(text)))
                wait(500)
                sampSendChat("/anim 21")
                wait(700)
                sampSendChat('/do Бейджик передан')
            end)
        else sampAddChatMessage("FF0000}[LUA]{FF8C00} Игрок с данным ID не подключен к серверу.", 0xFFFF0000) end
    else sampAddChatMessage("{FF0000}[LUA] {FF8C00}Используйте: /rang [ID] [+ или -]", 0xFFFF0000) end
end


Можете сказать почему выдает мол неверный формат.

Ввожу /rang 90 +. оно мне такое:


image.png
Попробуй так, добавил просто две переменные в команду
Lua:
function cmd_rang(id, rang)
    if id then
        if id and (sampIsPlayerConnected(tonumber(id)) or (tonumber(id) == select(2, sampGetPlayerIdByCharHandle(playerPed))) ) then
            lua_thread.create(function()
                sampSendChat(("/do Бейджик в руках %s форма для %s."):format(sampGetPlayerNickname(select(2, sampGetPlayerIdByCharHandle(playerPed))):gsub("_", " "), sampGetPlayerNickname(tonumber(id)):gsub("_", " ")))
                wait(500)
                sampSendChat("/me легким движением рук, передает новый бейджик человеку напротив")
                wait(500)
                sampSendChat("/rang " .. id .. " " .. rang)
                wait(500)
                sampSendChat("/anim 21")
                wait(700)
                sampSendChat('/do Бейджик передан')
            end)
        else sampAddChatMessage("FF0000}[LUA]{FF8C00} Игрок с данным ID не подключен к серверу.", 0xFFFF0000) end
    else sampAddChatMessage("{FF0000}[LUA] {FF8C00}Используйте: /rang [ID] [+ или -]", 0xFFFF0000) end
end
Подскажите мне пожалуйста, можно как-то получить серверное время?
 
Последнее редактирование:

Pasquale Developer

Известный
109
8
Функцию wait нельзя использовать вне function main()
Чтобы пофиксить создай поток. Просто сделай такой код:

Lua:
function ezd()
    lua_thread.create(function()
        sampSendChat(u8:decode(rand1.v))
        wait(waitb.v)
        sampSendChat(u8:decode(rand3.v))
    end)
end

Попробуй так, добавил просто две переменные в команду
Lua:
function cmd_rang(id, rang)
    if id then
        if id and (sampIsPlayerConnected(tonumber(id)) or (tonumber(id) == select(2, sampGetPlayerIdByCharHandle(playerPed))) ) then
            lua_thread.create(function()
                sampSendChat(("/do Бейджик в руках %s форма для %s."):format(sampGetPlayerNickname(select(2, sampGetPlayerIdByCharHandle(playerPed))):gsub("_", " "), sampGetPlayerNickname(tonumber(id)):gsub("_", " ")))
                wait(500)
                sampSendChat("/me легким движением рук, передает новый бейджик человеку напротив")
                wait(500)
                sampSendChat("/rang " .. id .. " " .. rang)
                wait(500)
                sampSendChat("/anim 21")
                wait(700)
                sampSendChat('/do Бейджик передан')
            end)
        else sampAddChatMessage("FF0000}[LUA]{FF8C00} Игрок с данным ID не подключен к серверу.", 0xFFFF0000) end
    else sampAddChatMessage("{FF0000}[LUA] {FF8C00}Используйте: /rang [ID] [+ или -]", 0xFFFF0000) end
end
Подскажите мне пожалуйста, можно как-то получить серверное время?
не работает
 

#Rewzeisch

Известный
121
10
Какой функцией можно заменить эту функцию?
P.s. через хук onServerMessage пытался - не ищет этот текст :С

Lua:
str, --[[string]] prefstr, --[[int]] colstr, --[[int]] pcolstr = sampGetChatString(--[[int]] 99)
    if str ==  "** В порт {0088ff}San Fierro {cccccc}прибывает корабль с товаром " then -- сравить строку на полное соответствие
    end
        if  string.find(str, "** В порт {0088ff}San Fierro {cccccc}прибывает корабль с товаром ", 0, true) ~= nil then
--действие от скрипта
end

Актуально, нужна помощь