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

#SameLine

Активный
417
37

Что есть переменные которые отвечают за фары? что бы сделать стробоскопы​

 

Shepard

Активный
459
88
Делаю трейсер к объекту, но когда поварачиваюсь в другую сторону - он остается, только уже в другой стороне
 

lorgon

Известный
657
268
Неправильно декодируется json конфиг.

Когда из скрипта добавляю в таблицу значения - всё идеально, но после того как сохраняю в кфг и перезахожу - всё ломается.
Lua:
local roads = {
    [1] = {['inf']={{121, 352, 123}, 0.00}, [4]=1 },
    [2] = {['inf']={{1256, 332, 232}, 0.01}, [1]=1 },
    [3] = {['inf']={{123, 332, 222}, 0.00}, [2]=1 },
    [4] = {['inf']={{123, 332, 222}, 0.00}, [3]=1 },
}
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    roads = read(getGameDirectory().."\\moonloader\\cfg\\roads.json")
    while true do
        if wasKeyReleased(vkeys.VK_K) then
            write(getGameDirectory().."\\moonloader\\cfg\\roads.json", roads)
        end
        wait(0)
    end
end


function read(path)
    if doesFileExist(path) then
        local f = io.open(path, 'a+')
        local data = decodeJson(f:read('*a'))
        f:close()
        return data
    else
        return roads -- empty data
    end -- read json
end
function write(path, data)
    if doesFileExist(path) then
        os.remove(path) -- newbie double writing fix, but i think io.input fix it
    end

    if type(data) ~= 'table' then
        return
    end

    local f = io.open(path, 'a+')
    local writing_data = encodeJson(data)
    f:write(writing_data) -- new json data

    f:close() --write json
end
JSON:
[{"inf":[[121,352,123],0],"4":1},{"inf":[[1256,332,232],0.01],"1":1},{"inf":[[123,332,222],0],"2":1},{"inf":[[123,332,222],0],"3":1}]
Сам решил эту проблему написанием своих функций encoding и decoding таблицам(конкретно под свою). Поэтому оставляю сообщение без кода.
 

Стэнфорд

Потрачен
1,058
540
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
ку, как сделать так, что бы в нужный файл записывалась нужный текст с новой строки?
 

Rice.

https://t.me/riceoff
Модератор
1,687
1,423
Первый раз работаю с таблицами, помогите пожалуйста сделать проверку на ник.
Lua:
local owners = {
    'Yuki_Rice',
    'Rice_Yuki'
}


function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
    while not sampIsLocalPlayerSpawned() do wait(0) end

        _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
        nick = sampGetPlayerNickname(id)

        if nick == owners then
            owner = true
            GHsms('Вы вошли в режим Разработчика!')
        end
    while true do
    wait(0)
    end
end

UPD: Нашел вариант проверки
Lua:
local owners = {
    'Yuki_Rice',
    'Rice_Yuki'
}

function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
    while not sampIsLocalPlayerSpawned() do wait(0) end

        _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
        nick = sampGetPlayerNickname(id)

        for i=1, #owners do
            if nick == owners[i] then
                owner = true
                GHsms('Вы вошли в режим Разработчика!')
            end
        end
      
    while true do
    wait(0)
    end
end
 
Последнее редактирование:

sep

Известный
672
76

Что есть переменные которые отвечают за фары? что бы сделать стробоскопы​

нахрена изабретать колесо если скрипт уже есть

код:
script_name("Stroboscopes")
script_version("0.3.0")
script_description("use siren in car or /strobes or L. Alt down for 1 second")
script_author("AppleThe")

require "lib.moonloader"

function main()
    if not isCleoLoaded() or not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
    
    sampRegisterChatCommand("st", function()
        if isCharInAnyCar(PLAYER_PED) then
            local car = storeCarCharIsInNoSave(PLAYER_PED)
            local driverPed = getDriverOfCar(car)
            
            if PLAYER_PED == driverPed then
                local state = not isCarSirenOn(car)
                switchCarSiren(car, state)
            end
        end
    end)
    lua_thread.create(strobe)
    lua_thread.create(strobeText)
    
    while true do
        wait(0)
        
        if isCharInAnyCar(PLAYER_PED) then
        
            local car = storeCarCharIsInNoSave(PLAYER_PED)
            local driverPed = getDriverOfCar(car)
            
            if isKeyDown(VK_LMENU) and isKeyCheckAvailable() and driverPed == PLAYER_PED then
                local state = true
                
                for i = 1, 10 do
                    wait(100)
                    if not isKeyDown(VK_LMENU) then state = false end
                end
                
                if isKeyDown(VK_LMENU) and state then
                    
                    local state = not isCarSirenOn(car)
                    switchCarSiren(car, state)
                    
                    while isKeyDown(VK_LMENU) do wait(0) end
                
                end
                
            end
            
        end
        
        
    end
end

function stroboscopes(adress, ptr, _1, _2, _3, _4)
    if not isCharInAnyCar(PLAYER_PED) then return end
    
    if not isCarSirenOn(storeCarCharIsInNoSave(PLAYER_PED)) then
        forceCarLights(storeCarCharIsInNoSave(PLAYER_PED), 0)
        callMethod(7086336, ptr, 2, 0, 1, 3)
        callMethod(7086336, ptr, 2, 0, 0, 0)
        callMethod(7086336, ptr, 2, 0, 1, 0)
        markCarAsNoLongerNeeded(storeCarCharIsInNoSave(PLAYER_PED))
        return
    end

    callMethod(adress, ptr, _1, _2, _3, _4)
end

function strobeText()
    local sequence = true
    while true do
        wait(0)
        if isCharInAnyCar(PLAYER_PED) then
        
            local car = storeCarCharIsInNoSave(PLAYER_PED)
            local driverPed = getDriverOfCar(car)
            
            if isCarSirenOn(car) and PLAYER_PED == driverPed then
                
                if sequence then --printStyledString('~n~~n~~n~~n~~n~~n~~n~~n~~n~~n~~b~STROB~w~OS~r~COPES', 1000, 4)
                else --printStyledString('~n~~n~~n~~n~~n~~n~~n~~n~~n~~n~~r~STROB~w~OS~b~COPES', 1000, 4)
                end
                
                sequence = not sequence
                wait(950)
                
            end
        end
    end
end

function strobe()
    while true do
        wait(0)
        
        if isCharInAnyCar(PLAYER_PED) then
        
            local car = storeCarCharIsInNoSave(PLAYER_PED)
            local driverPed = getDriverOfCar(car)
            
            if isCarSirenOn(car) and PLAYER_PED == driverPed then
            
                local ptr = getCarPointer(car) + 1440
                forceCarLights(car, 2)
                wait(50)
                stroboscopes(7086336, ptr, 2, 0, 1, 3)

                while isCarSirenOn(car) do
                    wait(0)
                    for i = 1, 12 do
                        wait(100)
                        stroboscopes(7086336, ptr, 2, 0, 1, 0)
                        wait(100)
                        stroboscopes(7086336, ptr, 2, 0, 0, 0)
                        stroboscopes(7086336, ptr, 2, 0, 1, 1)
                        wait(100)
                        stroboscopes(7086336, ptr, 2, 0, 0, 1)
                        stroboscopes(7086336, ptr, 2, 0, 1, 0)
                        wait(100)
                        stroboscopes(7086336, ptr, 2, 0, 1, 0)
                        stroboscopes(7086336, ptr, 2, 0, 1, 1)
                        if not isCarSirenOn(car) or not isCharInAnyCar(PLAYER_PED) then break end
                    end
                    
                    if not isCarSirenOn(car) or not isCharInAnyCar(PLAYER_PED) then break end

                    for i = 1, 6 do
                        wait(80)
                        stroboscopes(7086336, ptr, 2, 0, 1, 3)
                        stroboscopes(7086336, ptr, 2, 0, 0, 0)
                        wait(80)
                        stroboscopes(7086336, ptr, 2, 0, 1, 0)
                        wait(80)
                        stroboscopes(7086336, ptr, 2, 0, 0, 0)
                        wait(80)
                        stroboscopes(7086336, ptr, 2, 0, 1, 0)
                        if not isCarSirenOn(car) or not isCharInAnyCar(PLAYER_PED) then break end
                        wait(300)
                        stroboscopes(7086336, ptr, 2, 0, 0, 1)
                        wait(80)
                        stroboscopes(7086336, ptr, 2, 0, 1, 1)
                        wait(80)
                        stroboscopes(7086336, ptr, 2, 0, 0, 1)
                        wait(80)
                        stroboscopes(7086336, ptr, 2, 0, 1, 1)
                        if not isCarSirenOn(car) or not isCharInAnyCar(PLAYER_PED) then break end
                    end
                    
                    if not isCarSirenOn(car) or not isCharInAnyCar(PLAYER_PED) then break end

                    for i = 1, 3 do
                        wait(60)
                        stroboscopes(7086336, ptr, 2, 0, 1, 3)
                        stroboscopes(7086336, ptr, 2, 0, 1, 0)
                        stroboscopes(7086336, ptr, 2, 0, 0, 1)
                        wait(60)
                        stroboscopes(7086336, ptr, 2, 0, 1, 1)
                        wait(60)
                        stroboscopes(7086336, ptr, 2, 0, 0, 1)
                        wait(60)
                        stroboscopes(7086336, ptr, 2, 0, 1, 1)
                        wait(60)
                        stroboscopes(7086336, ptr, 2, 0, 0, 1)
                        wait(60)
                        stroboscopes(7086336, ptr, 2, 0, 1, 1)
                        wait(60)
                        stroboscopes(7086336, ptr, 2, 0, 0, 0)
                        wait(60)
                        if not isCarSirenOn(car) or not isCharInAnyCar(PLAYER_PED) then break end
                        stroboscopes(7086336, ptr, 2, 0, 1, 0)
                        wait(60)
                        stroboscopes(7086336, ptr, 2, 0, 0, 0)
                        wait(350)
                        stroboscopes(7086336, ptr, 2, 0, 1, 0)
                        stroboscopes(7086336, ptr, 2, 0, 0, 1)
                        wait(60)
                        if not isCarSirenOn(car) or not isCharInAnyCar(PLAYER_PED) then break end
                        stroboscopes(7086336, ptr, 2, 0, 1, 1)
                        stroboscopes(7086336, ptr, 2, 0, 0, 0)
                        wait(50)
                        stroboscopes(7086336, ptr, 2, 0, 1, 0)
                        stroboscopes(7086336, ptr, 2, 0, 0, 1)
                        wait(50)
                        stroboscopes(7086336, ptr, 2, 0, 1, 1)
                        stroboscopes(7086336, ptr, 2, 0, 0, 0)
                        wait(100)
                        stroboscopes(7086336, ptr, 2, 0, 1, 1)
                        stroboscopes(7086336, ptr, 2, 0, 1, 1)
                        wait(80)
                        stroboscopes(7086336, ptr, 2, 0, 0, 1)
                        stroboscopes(7086336, ptr, 2, 0, 0, 0)
                        wait(100)
                        if not isCarSirenOn(car) or not isCharInAnyCar(PLAYER_PED) then break end
                        stroboscopes(7086336, ptr, 2, 0, 1, 1)
                        stroboscopes(7086336, ptr, 2, 0, 1, 0)
                        wait(80)
                        stroboscopes(7086336, ptr, 2, 0, 0, 1)
                        stroboscopes(7086336, ptr, 2, 0, 0, 0)
                        wait(100)
                        stroboscopes(7086336, ptr, 2, 0, 0, 1)
                        stroboscopes(7086336, ptr, 2, 0, 1, 0)
                        wait(80)
                        stroboscopes(7086336, ptr, 2, 0, 1, 1)
                        stroboscopes(7086336, ptr, 2, 0, 0, 0)
                        if not isCarSirenOn(car) or not isCharInAnyCar(PLAYER_PED) then break end
                    end
                    
                    if not isCarSirenOn(car) or not isCharInAnyCar(PLAYER_PED) then break end
                end
            end
        end
    end
end

function isKeyCheckAvailable()
  if not isSampfuncsLoaded() then
    return not isPauseMenuActive()
  end
  local result = not isSampfuncsConsoleActive() and not isPauseMenuActive()
  if isSampLoaded() and isSampAvailable() then
    result = result and not sampIsChatInputActive() and not sampIsDialogActive()
  end
  return result
end

function isCharInAnyCar(ped)
    local vehicles = {602, 545, 496, 517, 401, 410, 518, 600, 527, 436, 589, 580, 419, 439, 533, 549, 526, 491, 474, 445, 467, 604, 426, 507, 547, 585, 405, 587, 409, 466, 550, 492, 566, 546, 540, 551, 421, 516, 529, 485, 552, 431, 438, 437, 574, 420, 525, 408, 416, 596, 433, 597, 427, 599, 490, 528, 601, 407, 428, 544, 523, 470, 598, 499, 588, 609, 403, 498, 514, 524, 423, 532, 414, 578, 443, 486, 515, 406, 531, 573, 456, 455, 459, 543, 422, 583, 482, 478, 605, 554, 530, 418, 572, 582, 413, 440, 536, 575, 534, 567, 535, 576, 412, 402, 542, 603, 475, 568, 557, 424, 471, 504, 495, 457, 483, 508, 500, 444, 556, 429, 411, 541, 559, 415, 561, 480, 560, 562, 506, 565, 451, 434, 558, 494, 555, 502, 477, 503, 579, 400, 404, 489, 505, 479, 442, 458}
    for i, v in ipairs(vehicles) do
        if isCharInModel(ped, v) then return true end
    end
    return false
end
 

Warklot

Участник
112
3
When i'm testing in chat and i write Test 25 it does nothing ,but when i write Test 25 56 it writes /Arrest 25 , /Arrest 56.So why first one doesn't work? it should write /Arrest 25.
Lua:
function sampev.onServerMessage(color,text)
    if enabled then
        if color==-65110 then
            if  text:len() <=8 then
                if text:find("Test.(%d+)")  then
                    id1 = text:match("Test.(%d+)")
                    sampAddChatMessage("/Arrest "..id1,-1)     
                end
            end
        end
    end
end



function sampev.onServerMessage(coloras,textas)
    if enabled then
        if coloras==-65110 then
            if  textas:len()>8 then
                if textas:find("Test.(%d+).(%d+)")  then
                    id2,id3 = textas:match("Test.(%d+).(%d+)")
                    sampAddChatMessage("/Arrest "..id2,-1)     
                    sampAddChatMessage("/Arrest "..id3,-1)
                end
            end
        end
    
    end
end
 

GRUZIN RULIT

Новичок
10
0
Скажите(или напишите пжпж)как написать скрипт,который будет тепать с начала на 1 чекпоинт затем на 2,и так по бесконечности
 

Стэнфорд

Потрачен
1,058
540
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Хелп, нужно хукнуть диалог и вытащить из текста предложение "ищу дальних родствеников". Я попытался - но копируется еще и пустая строка. Как скопировать только эту фразу?
{FFFFFF}Сообщение: {33AA33}ищу дальних родствеников

{FFFFFF}Отредактируйте рекламу в нужный формат.
 

Cod

Участник
117
15
Проблемка, при сохранении данных из imgui.InputText
не могу сохранить в u8, всегда сохраняет каракули, куда только эту u8 не ставил.
 

Smeruxa

Известный
1,297
681
Проблемка, при сохранении данных из imgui.InputText
не могу сохранить в u8, всегда сохраняет каракули, куда только эту u8 не ставил.
HLcfg.config.text = u8:decode(input.v)
Хелп, нужно хукнуть диалог и вытащить из текста предложение "ищу дальних родствеников". Я попытался - но копируется еще и пустая строка. Как скопировать только эту фразу?
{FFFFFF}Сообщение: {33AA33}ищу дальних родствеников

{FFFFFF}Отредактируйте рекламу в нужный формат.
хук onShowDialog
и цикл
for text in text:gmatch("[^\r\n]+") do
 
  • Влюблен
Реакции: Cod

Rice.

https://t.me/riceoff
Модератор
1,687
1,423
When i'm testing in chat and i write Test 25 it does nothing ,but when i write Test 25 56 it writes /Arrest 25 , /Arrest 56.So why first one doesn't work? it should write /Arrest 25.
Lua:
function sampev.onServerMessage(color,text)
    if enabled then
        if color==-65110 then
            if  text:len() <=8 then
                if text:find("Test.(%d+)")  then
                    id1 = text:match("Test.(%d+)")
                    sampAddChatMessage("/Arrest "..id1,-1)    
                end
            end
        end
    end
end



function sampev.onServerMessage(coloras,textas)
    if enabled then
        if coloras==-65110 then
            if  textas:len()>8 then
                if textas:find("Test.(%d+).(%d+)")  then
                    id2,id3 = textas:match("Test.(%d+).(%d+)")
                    sampAddChatMessage("/Arrest "..id2,-1)    
                    sampAddChatMessage("/Arrest "..id3,-1)
                end
            end
        end
   
    end
end
Hello maybee i fix you problem. In regular expressions, before the "." sign, you need to put %

Lua:
function sampev.onServerMessage(color, text)
    if enabled then
        if color==-65110 then
            if  text:len() <=8 then
                if text:find("Test%.(%d+)")  then
                    id1 = text:match("Test%.(%d+)")
                    sampAddChatMessage("/Arrest "..id1,-1)    
                end
            end
        end
    end
end



function sampev.onServerMessage(coloras, textas)
    if enabled then
        if coloras==-65110 then
            if  textas:len()>8 then
                if textas:find("Test%.(%d+)%.(%d+)")  then
                    id2, id3 = textas:match("Test%.(%d+)%.(%d+)")
                    sampAddChatMessage("/Arrest "..id2,-1)    
                    sampAddChatMessage("/Arrest "..id3,-1)
                end
            end
        end
   
    end
end
Проблемка, при сохранении данных из imgui.InputText
не могу сохранить в u8, всегда сохраняет каракули, куда только эту u8 не ставил.
код скинь
 
Последнее редактирование:

Warklot

Участник
112
3
Hello maybee i fix you problem. In regular expressions, before the "." sign, you need to put%

[CODE = lua]
function sampev.onServerMessage (color, text)
if enabled then
if color == - 65110 then
if text: len () <= 8 then
if text: find ("Test%. (% d +)") then
id1 = text: match ("Test%. (% d +)")
sampAddChatMessage ("/ Arrest" ..id1, -1)
end
end
end
end
end


throw off the code
Didn't fix ;/