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

Oxygenius

Потрачен
99
10
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.

arc warden

Участник
139
21
123:
local sampev = require "lib.samp.events"

function main()
    repeat wait(0) until isSampAvailable()
    wait(100)
    sampAddChatMessage("Тест скриптов оксигениуса загружен.", -1)
    thread1 = lua_thread.create_suspended(ss)
    while true do
        wait(0)
    end
end

function sampev.onServerMessage(color, text)
    if string.find(text, 'Установлен', 1, true) then
        sampAddChatMessage("Сообщения заблокировано!", -1)
        return false
    end
end

function sampev.onShowDialog(id, style, title, button1, button2, text)
    if title:find('Меню') then
        lua_thread.create(function()
            wait(1000)
            sampAddChatMessage("Успешно", -1)
            sampSendDialogResponse(id, 1, 5, '')
            wait(2500)
            sampSendDialogResponse(id, 1, 5, '')
        end)
    end
end

123:
local sampev = require "lib.samp.events"

function main()
    repeat wait(0) until isSampAvailable()
    wait(100)
    sampAddChatMessage("Тест скриптов оксигениуса загружен.", -1)
    thread1 = lua_thread.create_suspended(ss)
    while true do
        wait(0)
    end
end

function sampev.onServerMessage(color, text)
    if string.find(text, 'Установлен', 1, true) then
        sampAddChatMessage("Сообщения заблокировано!", -1)
        return false
    end
end

function sampev.onShowDialog(id, style, title, button1, button2, text)
    if title:find('Меню') then
        lua_thread.create(function()
            wait(1000)
            sampAddChatMessage("Успешно", -1)
            sampSendDialogResponse(id, 1, 5, '')
            wait(2500)
            sampSendDialogResponse(id, 1, 5, '')
        end)
    end
end
p.s - не тестил так что может не робить
 

Oxygenius

Потрачен
99
10
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
123:
local sampev = require "lib.samp.events"

function main()
    repeat wait(0) until isSampAvailable()
    wait(100)
    sampAddChatMessage("Тест скриптов оксигениуса загружен.", -1)
    thread1 = lua_thread.create_suspended(ss)
    while true do
        wait(0)
    end
end

function sampev.onServerMessage(color, text)
    if string.find(text, 'Установлен', 1, true) then
        sampAddChatMessage("Сообщения заблокировано!", -1)
        return false
    end
end

function sampev.onShowDialog(id, style, title, button1, button2, text)
    if title:find('Меню') then
        lua_thread.create(function()
            wait(1000)
            sampAddChatMessage("Успешно", -1)
            sampSendDialogResponse(id, 1, 5, '')
            wait(2500)
            sampSendDialogResponse(id, 1, 5, '')
        end)
    end
end


p.s - не тестил так что может не робить
говнокод:
function sampev.onShowDialog(id, style, title, button1, button2, text)
    if title:find('Меню') then
        lua_thread.create(function()
            wait(600)
            sampSendDialogResponse(id, 1, 1, '')
            sampAddChatMessage("Успешно", -1)
            wait(1700)
            sampSendDialogResponse(id, 1, 3, '')
            sampAddChatMessage("Успешно х2", -1)
        end)
    end
end

сделал так чтобы писало в чат, первое нажимает, а второе нет но все равно пишет успешно х2
 

arc warden

Участник
139
21
говнокод:
function sampev.onShowDialog(id, style, title, button1, button2, text)
    if title:find('Меню') then
        lua_thread.create(function()
            wait(600)
            sampSendDialogResponse(id, 1, 1, '')
            sampAddChatMessage("Успешно", -1)
            wait(1700)
            sampSendDialogResponse(id, 1, 3, '')
            sampAddChatMessage("Успешно х2", -1)
        end)
    end
end

сделал так чтобы писало в чат, первое нажимает, а второе нет но все равно пишет успешно х2
во 2 диалоге точно тайтл "Меню"
 
  • Нравится
Реакции: Oxygenius

nanobrick

Участник
77
48
говнокод:
function sampev.onShowDialog(id, style, title, button1, button2, text)
    if title:find('Меню') then
        lua_thread.create(function()
            wait(600)
            sampSendDialogResponse(id, 1, 1, '')
            sampAddChatMessage("Успешно", -1)
            wait(1700)
            sampSendDialogResponse(id, 1, 3, '')
            sampAddChatMessage("Успешно х2", -1)
        end)
    end
end

сделал так чтобы писало в чат, первое нажимает, а второе нет но все равно пишет успешно х2
айдишник не обновляется
sampGetCurrentDialogId добавь
 
  • Нравится
Реакции: Oxygenius

percheklii

Известный
733
269
Когда пишу текст в поле ввода "InputTextWithHint" к примеру цыфру 1, то оно сохраняет в конфиг "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" а когда пишу буквы, перезагружаю скрипт/перезахожу в игру, и пытаюсь удалить его, крашит игру

Lua:
local inicfg = require('inicfg')
local directIni = 'LALA.ini'
local mainIni = inicfg.load(inicfg.load({
    lala = {
          text = u8''
    }
}, directIni))
inicfg.save(mainIni, directIni)

local lalatext = {
      text = new.char[256](mainIni.lala.text)
{
--В окне
        if imgui.InputTextWithHint(faicons('USER')..u8' Текст', u8'Введите текст', lalatext.text, 256) then
            mainIni.lala.text = lalatext.text[0]
        end
Lua:
local imgui = require("mimgui")
local ffi = require("ffi")
local inicfg = require("inicfg")
local encoding = require("encoding")
encoding.default = ("CP1251")
local u8 = encoding.UTF8

local ini = inicfg.load({
    text = {
        test = "hui"
    }
}, "test.ini")

local window = imgui.new.bool()

imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
end)

local text = imgui.new.char[256](u8(ini.text.test))

imgui.OnFrame(function() return window[0] end, function(player)
    local sx, sy = getScreenResolution()
    imgui.SetNextWindowSize(imgui.ImVec2(200, 200))
    imgui.SetNextWindowPos(imgui.ImVec2(sx / 2, sy / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.Begin("", window, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoResize)

    if imgui.InputTextWithHint(u8"Текст", u8"Введите текст", text, 256) then
        ini.text.test = u8:decode(ffi.string(text))
        inicfg.save(ini, "test.ini")
    end

    imgui.End()
end)

function main()
    repeat wait(0) until isSampAvailable()
    sampRegisterChatCommand("test", function() window[0] = not window[0] end)
    wait(-1)
end
 
  • Нравится
Реакции: tsunamiqq

хуега)

РП игрок
Модератор
2,560
2,255
Из-за чего может рендерится лишняя строка?
Lua:
local mimgui = {   
    elements = {     
        combos = {
            places = {text = u8("Спавн"), val = new.int(0), list = {"Автовокзал", "База огранизации", "База семьи", "Место выхода", "Дом", "Квартира/Общежитие"}}
        }
    }
}


imgui.ComboStr("##spawn", mimgui.elements.combos.places.val, u8(table.concat(mimgui.elements.combos.places.list, "\0")), #mimgui.elements.combos.places.list)
1690566394615.png
 
  • Вау
Реакции: percheklii

Fomikus

Известный
Проверенный
474
342
Из-за чего может рендерится лишняя строка?
Lua:
local mimgui = {  
    elements = {    
        combos = {
            places = {text = u8("Спавн"), val = new.int(0), list = {"Автовокзал", "База огранизации", "База семьи", "Место выхода", "Дом", "Квартира/Общежитие"}}
        }
    }
}


imgui.ComboStr("##spawn", mimgui.elements.combos.places.val, u8(table.concat(mimgui.elements.combos.places.list, "\0")), #mimgui.elements.combos.places.list)
Посмотреть вложение 209837
Lua:
imgui.ComboStr("##spawn", mimgui.elements.combos.places.val, u8(table.concat(mimgui.elements.combos.places.list, "\0") .. "\0"), #mimgui.elements.combos.places.list)
 

tsunamiqq

Участник
429
16
Ошибка

cannot convert 'string' to 'bool [1]' stack traceback:

Lua:
local mainIni = inicfg.load(inicfg.load({
    autopiar = {
        adchecked = false,
        vrchecked = false,
        famchecked = false,
        jchecked = false,
        adtext = u8'',
        vrtext = u8'',
        famtext = u8'',
        jtext = u8'',
        addelay = 60000,
        vrdelay = 60000,
        famdelay = 60000,
        jdelay = 60000,
        checkedautopiar = false,
    }
}, directIni))
inicfg.save(mainIni, directIni)

local AUTOPIAR = {
    adchecked = new.bool(mainIni.autopiar.adchecked),
    vrchecked = new.bool(mainIni.autopiar.vrchecked),
    famchecked = new.bool(mainIni.autopiar.famchecked),
    jchecked = new.bool(mainIni.autopiar.jchecked),
    adtext = new.char[256](u8(mainIni.autopiar.adtext)),
    vrtext = new.char[256](u8(mainIni.autopiar.vrtext)),
    famtext = new.char[256](u8(mainIni.autopiar.famtext)),
    jtext = new.char[256](u8(mainIni.autopiar.jtext)),
    addelay = new.int(mainIni.autopiar.addelay),
    vrdelay = new.int(mainIni.autopiar.vrdelay),
    famdelay = new.int(mainIni.autopiar.famdelay),
    jdelay = new.int(mainIni.autopiar.jdelay),
    checkedautopiar = new.bool(mainIni.autopiar.checkedautopiar) --Ошибка на этой строке
}

if mainIni.autopiar.checkedautopiar then
        if mainIni.autopiar.vrchecked then
            lua_thread.create(function()
                sampSendChat('/vr '..mainIni.autopiar.vrtext)
                wait(mainIni.autopiar.vrdelay)
                return true
            end)
        end
        if mainIni.autopiar.adchecked then
            lua_thread.create(function()
                sampSendChat('/ad '..mainIni.autopiar.adtext)
                wait(mainIni.autopiar.addelay)
                return true
            end)
        end
        if mainIni.autopiar.famchecked then
            lua_thread.create(function()
                sampSendChat('/fam '..mainIni.autopiar.famtext)
                wait(mainIni.autopiar.famdelay)
                return true
            end)
        end
        if mainIni.autopiar.jchecked then
            lua_thread.create(function()
            sampSendChat('/j '..mainIni.autopiar.jtext)
            wait(mainIni.autopiar.jdelay)
            return true
        end)
    end
end
 

Akionka

akionka.lua
Проверенный
742
500
Ошибка

cannot convert 'string' to 'bool [1]' stack traceback:

Lua:
local mainIni = inicfg.load(inicfg.load({
    autopiar = {
        adchecked = false,
        vrchecked = false,
        famchecked = false,
        jchecked = false,
        adtext = u8'',
        vrtext = u8'',
        famtext = u8'',
        jtext = u8'',
        addelay = 60000,
        vrdelay = 60000,
        famdelay = 60000,
        jdelay = 60000,
        checkedautopiar = false,
    }
}, directIni))
inicfg.save(mainIni, directIni)

local AUTOPIAR = {
    adchecked = new.bool(mainIni.autopiar.adchecked),
    vrchecked = new.bool(mainIni.autopiar.vrchecked),
    famchecked = new.bool(mainIni.autopiar.famchecked),
    jchecked = new.bool(mainIni.autopiar.jchecked),
    adtext = new.char[256](u8(mainIni.autopiar.adtext)),
    vrtext = new.char[256](u8(mainIni.autopiar.vrtext)),
    famtext = new.char[256](u8(mainIni.autopiar.famtext)),
    jtext = new.char[256](u8(mainIni.autopiar.jtext)),
    addelay = new.int(mainIni.autopiar.addelay),
    vrdelay = new.int(mainIni.autopiar.vrdelay),
    famdelay = new.int(mainIni.autopiar.famdelay),
    jdelay = new.int(mainIni.autopiar.jdelay),
    checkedautopiar = new.bool(mainIni.autopiar.checkedautopiar) --Ошибка на этой строке
}

if mainIni.autopiar.checkedautopiar then
        if mainIni.autopiar.vrchecked then
            lua_thread.create(function()
                sampSendChat('/vr '..mainIni.autopiar.vrtext)
                wait(mainIni.autopiar.vrdelay)
                return true
            end)
        end
        if mainIni.autopiar.adchecked then
            lua_thread.create(function()
                sampSendChat('/ad '..mainIni.autopiar.adtext)
                wait(mainIni.autopiar.addelay)
                return true
            end)
        end
        if mainIni.autopiar.famchecked then
            lua_thread.create(function()
                sampSendChat('/fam '..mainIni.autopiar.famtext)
                wait(mainIni.autopiar.famdelay)
                return true
            end)
        end
        if mainIni.autopiar.jchecked then
            lua_thread.create(function()
            sampSendChat('/j '..mainIni.autopiar.jtext)
            wait(mainIni.autopiar.jdelay)
            return true
        end)
    end
end
конфиг сломался каким-то образом, inicfg не смог превратить то что в ключе этом в boolean и сделал строкой, а ты потом пытаешься сделать boolean из строки ну и короче оно так не работает. не знаю попробуй пересоздать конфиг просто

мужики подскажите есть какой-то пул того что создает addBlipForCoord а то хочу все маркеры которые есть в игре проверить на что-то и потом с ними что-то сделать
 

tsunamiqq

Участник
429
16
конфиг сломался каким-то образом, inicfg не смог превратить то что в ключе этом в boolean и сделал строкой, а ты потом пытаешься сделать boolean из строки ну и короче оно так не работает. не знаю попробуй пересоздать конфиг просто
Помогло, но вот такое сохраняет в конфиг
checkedautopiar=function: 0x19acb370
UPD:Исправил

Ошибка

cannot convert 'string' to 'bool [1]' stack traceback:

Lua:
local mainIni = inicfg.load(inicfg.load({
    autopiar = {
        adchecked = false,
        vrchecked = false,
        famchecked = false,
        jchecked = false,
        adtext = u8'',
        vrtext = u8'',
        famtext = u8'',
        jtext = u8'',
        addelay = 60000,
        vrdelay = 60000,
        famdelay = 60000,
        jdelay = 60000,
        checkedautopiar = false,
    }
}, directIni))
inicfg.save(mainIni, directIni)

local AUTOPIAR = {
    adchecked = new.bool(mainIni.autopiar.adchecked),
    vrchecked = new.bool(mainIni.autopiar.vrchecked),
    famchecked = new.bool(mainIni.autopiar.famchecked),
    jchecked = new.bool(mainIni.autopiar.jchecked),
    adtext = new.char[256](u8(mainIni.autopiar.adtext)),
    vrtext = new.char[256](u8(mainIni.autopiar.vrtext)),
    famtext = new.char[256](u8(mainIni.autopiar.famtext)),
    jtext = new.char[256](u8(mainIni.autopiar.jtext)),
    addelay = new.int(mainIni.autopiar.addelay),
    vrdelay = new.int(mainIni.autopiar.vrdelay),
    famdelay = new.int(mainIni.autopiar.famdelay),
    jdelay = new.int(mainIni.autopiar.jdelay),
    checkedautopiar = new.bool(mainIni.autopiar.checkedautopiar) --Ошибка на этой строке
}

if mainIni.autopiar.checkedautopiar then
        if mainIni.autopiar.vrchecked then
            lua_thread.create(function()
                sampSendChat('/vr '..mainIni.autopiar.vrtext)
                wait(mainIni.autopiar.vrdelay)
                return true
            end)
        end
        if mainIni.autopiar.adchecked then
            lua_thread.create(function()
                sampSendChat('/ad '..mainIni.autopiar.adtext)
                wait(mainIni.autopiar.addelay)
                return true
            end)
        end
        if mainIni.autopiar.famchecked then
            lua_thread.create(function()
                sampSendChat('/fam '..mainIni.autopiar.famtext)
                wait(mainIni.autopiar.famdelay)
                return true
            end)
        end
        if mainIni.autopiar.jchecked then
            lua_thread.create(function()
            sampSendChat('/j '..mainIni.autopiar.jtext)
            wait(mainIni.autopiar.jdelay)
            return true
        end)
    end
end
Эта функция работает только после перезагрузки скрипта, и отключается так-же, даже если выключил чекбокс, то все равно продолжает работать, как исправить?
 
Последнее редактирование:

Дядя Энрик.

Активный
319
75
Помогло, но вот такое сохраняет в конфиг
checkedautopiar=function: 0x19acb370
UPD:Исправил


Эта функция работает только после перезагрузки скрипта, и отключается так-же, даже если выключил чекбокс, то все равно продолжает работать, как исправить?
значит на чекбокс нет проверки на конфиг, смотри конфиг
 

Piratekapitan

Известный
59
17
Ситуация такова есть диалог со списком, при нажатие на один из элеметов списка, должен отображаться следующий диалог, но вызываю sampSendDialogResponse ничего не происходит, и при попытке выбора элемента из списка в ручную диалог просто закрывается, что может быть?
Второй аргумент пытался ставить и 0 и 1, но результат один и тот же.
CODE:
function events()
    function sampev.onShowDialog(DdialogId, Dstyle, Dtitle, Dbutton1, Dbutton2, Dtext)
        print(Dtitle, flag)
        if(flag) then
            print("id1", sampGetCurrentDialogId())
            if DdialogId == 1405 then
                print("id2", sampGetCurrentDialogId())
                sampSendDialogResponse(1405, 0, 2, "")
            end
        end
    end
end
 
Последнее редактирование:

Oxygenius

Потрачен
99
10
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
айдишник не обновляется
sampGetCurrentDialogId добавь
говнокод:
local sampev = require "lib.samp.events"

function main()
    repeat wait(0) until isSampAvailable()
    wait(100)
    sampAddChatMessage("Тест скриптов оксигениуса загружен.", -1)
    while true do
        wait(0)
    end
end

function sampev.onServerMessage(color, text)
    if string.find(text, 'Установлен', 1, true) then
        sampAddChatMessage("Сообщения заблокировано!", -1)
        return false
    end
end

function sampev.onShowDialog(id, style, title, button1, button2, text)
    if title:find('Меню') then
        lua_thread.create(function()
            wait(600)
            sampSendDialogResponse(id, 1, 5, '')
            sampAddChatMessage("Успешно", -1)
            wait(1700)
            dialog_gun = sampGetCurrentDialogId()
            sampSendDialogResponse(dialog_gun, 1, 12, '')
            sampAddChatMessage("Успешно х2", -1)
        end)
    end
end

сделал так = не работает