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

Cutler18

Известный
160
2
DJ6cK.png

Нужно взять номер и отправить его в чат сразу
 

Glockersik

Участник
86
3
Помогите пожалуйста , что не так?
Код:
local name=Amber

local sampev = require 'lib.samp.events' 
function main() 
while true do wait(0) end 
 if name = sampGetCurrentServerName() then
sampSendChat ("/log pass") 
end

end
 

FBenz

Активный
328
40
Помогите пожалуйста , что не так?
Код:
local name=Amber

local sampev = require 'lib.samp.events'
function main()
while true do wait(0) end
 if name = sampGetCurrentServerName() then
sampSendChat ("/log pass")
end

end
Цикл бесконечный должен содержать не только Wait(0) , но и тело скрипта
 

Glockersik

Участник
86
3
Почему скрипт флудит?
Lua:
local sampev = require 'lib.samp.events'
function main()
while not isSampAvailable() do wait(100) end
end

function sampev.onShowDialog(id, style, title, b1, b2, text)
if title:find("Авторизация") then
lua_thread.create(login)
end
if title:find("Вход") then
lua_thread.create(login2)
end
return true
end

function login()
wait(5)
sampProcessChatInput('/log pass1')
end


function login2()
wait (5)
sampCloseCurrentDialogWithButton(1)
wait(5)
sampProcessChatInput('/log pass2')
wait(5)
sampProcessChatInput('/ahun')
end
 

Shamanije

Известный
Друг
961
920
DJ6cK.png

Нужно взять номер и отправить его в чат сразу
Lua:
local sampev = require 'lib.samp.events'

function sampev.onServerMessage(col, msg)
    if msg:match('[G]') then
        sampSendChat(msg:match('[G] .*%: (%d+)'))
    end
end

samp.lua установи если нету

Почему скрипт флудит?
Lua:
local sampev = require 'lib.samp.events'
function main()
while not isSampAvailable() do wait(100) end
end

function sampev.onShowDialog(id, style, title, b1, b2, text)
if title:find("Авторизация") then
lua_thread.create(login)
end
if title:find("Вход") then
lua_thread.create(login2)
end
return true
end

function login()
wait(5)
sampProcessChatInput('/log pass1')
end


function login2()
wait (5)
sampCloseCurrentDialogWithButton(1)
wait(5)
sampProcessChatInput('/log pass2')
wait(5)
sampProcessChatInput('/ahun')
end
Потому что говнокод
Lua:
local sampev = require 'lib.samp.events'

function main()
    while not isSampAvailable() do wait(100) end
    wait(-1)
end

function sampev.onShowDialog(id, style, title, b1, b2, text)
    if title:find("Авторизация") then
        lua_thread.create(function()
            wait(5)
            sampProcessChatInput('/log pass1')
        end)
        return false
    elseif title:find("Вход") then
        lua_thread.create(function()
            wait(5)
            sampProcessChatInput('/log pass2')
            wait(5)
            sampProcessChatInput('/ahun')
        end)
        return false
    end
end
 

Cameron_Bawerman

Участник
99
1
Помогите, из за чего ошибка?
Lua:
[ML] (error) test.lua: ...TA San Andreas MultiPlayer\moonloader\test.lua:5: attempt to index global 'inifiles' (a nil value)
stack traceback:
...TA San Andreas MultiPlayer\moonloader\test.lua:5: in main chunk
[ML] (error) test.lua: Script died due to an error. (01A69D04)

а вот код

Lua:
local sampev = require "lib.samp.events"
local key = require "vkeys"
local inicfg = require 'inicfg'
local inifiles = inicfg.load(nil,"settings")
local enablescrean = inifiles.settings.screan
 

Shamanije

Известный
Друг
961
920
Помогите, из за чего ошибка?
Lua:
[ML] (error) test.lua: ...TA San Andreas MultiPlayer\moonloader\test.lua:5: attempt to index global 'inifiles' (a nil value)
stack traceback:
...TA San Andreas MultiPlayer\moonloader\test.lua:5: in main chunk
[ML] (error) test.lua: Script died due to an error. (01A69D04)

а вот код

Lua:
local sampev = require "lib.samp.events"
local key = require "vkeys"
local inicfg = require 'inicfg'
local inifiles = inicfg.load(nil,"settings")
local enablescrean = inifiles.settings.screan
Нету ини файла в папке config
upd: или в ини нету подмассива с указанной переменной
 

Glockersik

Участник
86
3
что не так ?
Lua:
local sampev = require 'lib.samp.events'

function main()
while true do wait(0) end

end

function sampGetCurrentServerAddress(ip,port)
if ip:find("185.169.134.61") then
lua_thread.create(login)

end
end


function login()

wait(5)
sampProcessChatInput('/log pass1')


end
 

Shamanije

Известный
Друг
961
920
что не так ?
Lua:
local sampev = require 'lib.samp.events'

function main()
while true do wait(0) end

end

function sampGetCurrentServerAddress(ip,port)
if ip:find("185.169.134.61") then
lua_thread.create(login)

end
end


function login()

wait(5)
sampProcessChatInput('/log pass1')


end
Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    if select(1, sampGetCurrentServerAddress()):match('185.169.134.61') then
        wait(5)
        sampProcessChatInput('/log pass1')
    end
    wait(-1)
end
Отстань ты от этого потока уже
 

Natami

Участник
377
26
Крашит
Lua:
local config = inicfg.load({
    settings = {
        text = false;
    }
  }, 'cfgg')

local textvod = imgui.ImBuffer(""..tostring(config.input.text), 256)

if imgui.Button(u8"qq", btn_size) then
    imgui.OpenPopup(u8"qq")
end
imgui.SetNextWindowSize(imgui.ImVec2(400, 570), imgui.Cond.FirstUseEver)
if imgui.BeginPopupModal(u8"qq") then
    imgui.PushItemWidth(100)
    imgui.InputText("", textvod)
    imgui.PopItemWidth()
end
if imgui.Button("Отправить", btnz) then
    pInfo.set.text = textvod.v
    inicfg.save(pInfo, "cfgg")
end
if imgui.Button('Close') then imgui.CloseCurrentPopup() end
    imgui.EndPopup()
end
 

Eugene Crabs

Активный
544
30
Ну так что? Как сделать на игровых координатах отрезок, перпендикулярный другому отрезку? Или все хз?
 

MrYurkoo

Известный
102
9
Lua:
function main()
    if not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
        while true do
        wait(0)
        admDraw()
        if isKeyJustPressed(0x79) and cmd ~= nil then -- F10
            sampProcessChatInput(cmd)
        end
        if isKeyDown(18) and isKeyJustPressed(114) then -- ALT+F3
            nameTagOn()
            printStringNow('ON WH', 1500)
        repeat
            wait(0)
        if isKeyDown(119) then
                nameTagOff()
                wait(1000)
                nameTagOn()
        end
        until isKeyDown(18) and isKeyJustPressed(114)
        while isKeyDown(18) or isKeyDown(114) do
            wait(10)
        end
            nameTagOff()
            printStringNow('OFF WH', 1500)
        end
    end
end

admDraw() - это таблица вывода отдельных ключевых сообщений из чата в другой.
При включении WH на ALT+3 эта таблица пропадает, а при его выключении ALT+3 возвращается обратно. Нужно пофиксить, чтобы таблица была всегда включена, независимо от ВХ и прочих вещей.