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

ch1ps

Участник
101
3
Код:
local memory = require 'memory'
local playerObj, vehObj = nil, nil

function attachObjectToPlayer( hObject, hPlayer, pOffsets, pAngles )
    if doesObjectExist( hObject ) and doesCharExist( hPlayer ) then
        if not pOffsets then pOffsets = { 0.0, 0.0, 0.0 } end
        if not pAngles then pAngles = { 0.0, 0.0, 0.0 } end
      
        setObjectCoordinates( hObject, getCharCoordinates( hPlayer ) )
        setObjectCollision( hObject, false )
      
        local pointer = getObjectPointer( hObject )
      
        memory.setuint32( pointer + 0xFC, getCharPointer( hPlayer ) )
      
        memory.setfloat( pointer + 0x100, pOffsets[1] )
        memory.setfloat( pointer + 0x104, pOffsets[2] )
        memory.setfloat( pointer + 0x108, pOffsets[3] )

        memory.setfloat( pointer + 0x10C, pAngles[1] )
        memory.setfloat( pointer + 0x110, pAngles[2] )
        memory.setfloat( pointer + 0x114, pAngles[3] )

        return true
    end
    return false
end

function main()
    sampRegisterChatCommand('attach', function( )
        if isCharInAnyCar(PLAYER_PED) and not vehObj then
            local car = storeCarCharIsInNoSave( PLAYER_PED )
            vehObj = createObject( 1083, getCarCoordinates( car ) )
            if attachObjectToVehicle( vehObj, car, { 0.0, 0.0, 5.0 }, { 0.0, 0.0, 3.14/2 } ) then
                print( ("Объект %d прикреплён к авто %d"):format( getObjectModel( vehObj ), getCarModel( car ) ) )
            end
        elseif not isCharInAnyCar( PLAYER_PED ) and not playerObj then
            playerObj = createObject( 1083, getCharCoordinates( PLAYER_PED ) )
            if attachObjectToPlayer( playerObj, PLAYER_PED, { 0.0, 0.0, 5.0 }, { 0.0, 0.0, 3.14/2 } ) then
                print( ("Объект %d прикреплён к педу %d"):format( getObjectModel( playerObj ), PLAYER_PED ) )
            end
        else
            if playerObj then deleteObject( playerObj ); playerObj = nil end
            if vehObj then    deleteObject( vehObj );    vehObj = nil    end
        end
    end)
    while true do
        wait(0)
    end
end
Короче, с помощью функции прикрепления объекта к актёру, я попробовал прикрепить колесо, но по какой-то причине само колесо создается, но сразу же пропадает и само собой не крепится к скину, что не так?
 

ARMOR

kjor32 is legend
Модератор
4,847
6,100
Как можно отрендерить текстуру к примеру из файла hud.txd который находится в папке models?
 

artyr1010

Новичок
2
0
Всем мастерам своего дела привет!
Недавно начал изучать Lua, и вот сегодня руки дошли написать что-то для сампа..
Сразу скажу изучаю 3-й день.
Вообщем, регистрирую команду, а она не работает.. Можете сказать что в коде не так?(




Lua:
require "lib.moonloader"

local tag = "{FFFFFF}[7P Script]:{FF216F} "
local mc = 0x2DBAFF
local mct = '{2DBAFF}'
local wc = '{FFFFFF}'
local name = ' Холст! '
local version = '0.1'

function main()

    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("cmd", cmd_cmd)
    sampAddChatMessage(tag .. 'Спасибо за установку скрипта!', mc)
    sampAddChatMessage(tag.. 'Скрипт:' .. name ..'успешно загружен!', mc)
    sampAddChatMessage(tag .. 'Версия скрипта: '.. version, mc)
    sampAddChatMessage(tag .. 'Удачной игры!', mc)
end

function cmd_cmd(arg)
    sampAddChatMessage('Работает!', mc)
end
А где изучяаешь луа для сампа, или нужно просто изучать простое луа, ПОМОГИТЕ ПЖ
 

ZonePO

Новичок
6
0
how do i make a loop, i want it to send a text message, then wait some time, then send that message again until i turn the script off? also i get this error attempt to yield across C-call boundary
Lua:
function Testhelp()
        if not enable then sampAddChatMessage(ltu("{34eb37}Script off, {b88d0f}turn it back on with /script.{b88d0f}"), 0xFFFFFF) return end
        while loop do sampAddChatMessage('test', 0xffffffff)
            sampSendChat('/vip testtest)
            wait(30000)
end
 
Последнее редактирование:

YarikVL

Известный
Проверенный
4,796
1,813
how do i make a loop, i want it to send a text message, then wait some time, then send that message again until i turn the script off? also i get this error attempt to yield across C-call boundary
Lua:
function Testhelp()
        if not enable then sampAddChatMessage(ltu("{34eb37}Script off, {b88d0f}turn it back on with /script.{b88d0f}"), 0xFFFFFF) return end
        while loop do sampAddChatMessage('test', 0xffffffff)
            sampSendChat('/vip testtest)
            wait(30000)
end
You don’t use "lua_thread.create" for wait
Lua:
function Testhelp()
        if not enable then
           sampAddChatMessage(ltu("{34eb37}Script off, {b88d0f}turn it back on with /script.{b88d0f}"), 0xFFFFFF)
           return -- I don't know if this will work
        end
        while loop do
           lua_thread.create(function()
              sampAddChatMessage('test', 0xffffffff)
              sampSendChat('/vip testtest")
              wait(30000)
           end)
        end
end
 
Последнее редактирование:

ZonePO

Новичок
6
0
You don't use "lua_thread.create" for wait
Lua:
function Testhelp()
        if not enable then
           sampAddChatMessage(ltu("{34eb37}Script off, {b88d0f}turn it back on with /script.{b88d0f}"), 0xFFFFFF)
           return -- I don't know if this will work
        end
        while loop do
           lua_thread.create(function()
              sampAddChatMessage('test', 0xffffffff)
              sampSendChat('/vip testtest')
              wait(30000)
           end)
end
'end' expected (to close 'function' at line 27) near '<eof>', doesn't work, line 27 is function Testhelp(), nvm i fix it, but no output comes out, script doesnt say it errored
 
Последнее редактирование:

Fichi

Новичок
2
0
Здравствуйте, как сделать чтобы сообщение из игры отпровлялось само в группу вк. Как в группах у кладменов. Например я нешел клад мне пишется кординаты клада и чтобы эти кординаты отпровлялись в группу вк. Надеюсь вы меня поняли заранее спасибо
Помогите пожалуйста. Повторяю вопрос. Как сделать чтобы сообщение из игры автоматически отпровлялось в группу вк
 

YarikVL

Известный
Проверенный
4,796
1,813
Как сделать чтобы сообщение из игры автоматически отпровлялось в группу вк
https://www.blast.hk/threads/33250/ это?

'end' expected (to close 'function' at line 27) near '<eof>', doesn't work, line 27 is function Testhelp(), nvm i fix it, but no output comes out, script doesnt say it errored
Lua:
function Testhelp()
    if enable then
        lua_thread.create(function()
            while loop do
               sampAddChatMessage('test', -1)
               sampSendChat("/vip testtest")
               wait(30000)
            end
        end)
    else
       sampAddChatMessage(ltu("{34eb37}Script off, {b88d0f}turn it back on with /script.{b88d0f}"), 0xFFFFFF)
       --return -- I don't know if this will work
    end
end
Try this code
 
Последнее редактирование:

ZonePO

Новичок
6
0
https://www.blast.hk/threads/33250/ is this?


Lua:
function Testhelp()
    if enable then
        lua_thread.create(function()
            while loop do
               sampAddChatMessage('test', -1)
               sampSendChat("/vip testtest")
               wait(30000)
            end
        end)
    else
       sampAddChatMessage(ltu("{34eb37}Script off, {b88d0f}turn it back on with /script.{b88d0f}"), 0xFFFFFF)
       --return -- I don't know if this will work
    end
end
Try this code
I get no output, doesn't write anything in /vip, no errors.
 

vegas

Известный
640
445
I get no output, doesn't write anything in /vip, no errors.
Try this two types
Lua:
-- Using main function to loop
function Testhelp()
    if not enable then
        sampAddChatMessage(ltu("{34eb37}Script off, {b88d0f}turn it back on with /script.{b88d0f}"), 0xFFFFFF)
        return
    end
end
function Loop()
    if not loop then
        return
    end
    sampAddChatMessage('test', 0xffffffff)
    sampSendChat('/vip testtest')
    wait(30000)
end
function main()
    repeat wait(0) until isSampAvailable()
    while true do wait(0)
        Loop()
    end
end
Lua:
-- Or use lua_thread.create()
function Loop()
    while loop do
        sampAddChatMessage('test', 0xffffffff)
        sampSendChat('/vip testtest')
        wait(30000)
    end
end

function Testhelp()
    if not enable then
        sampAddChatMessage(ltu("{34eb37}Script off, {b88d0f}turn it back on with /script.{b88d0f}"), 0xFFFFFF)
        return
    end
    lua_thread.create(Loop)
end
 

kizn

О КУ)))
Всефорумный модератор
2,405
2,060
Try this two types
Lua:
-- Using main function to loop
function Testhelp()
    if not enable then
        sampAddChatMessage(ltu("{34eb37}Script off, {b88d0f}turn it back on with /script.{b88d0f}"), 0xFFFFFF)
        return
    end
end
function Loop()
    if not loop then
        return
    end
    sampAddChatMessage('test', 0xffffffff)
    sampSendChat('/vip testtest')
    wait(30000)
end
function main()
    repeat wait(0) until isSampAvailable()
    while true do wait(0)
        Loop()
    end
end
Lua:
-- Or use lua_thread.create()
function Loop()
    while loop do
        sampAddChatMessage('test', 0xffffffff)
        sampSendChat('/vip testtest')
        wait(30000)
    end
end

function Testhelp()
    if not enable then
        sampAddChatMessage(ltu("{34eb37}Script off, {b88d0f}turn it back on with /script.{b88d0f}"), 0xFFFFFF)
        return
    end
    lua_thread.create(Loop)
end
а что за функция ltu вообще?
 

YarikVL

Известный
Проверенный
4,796
1,813
Я хуй знает, это у чела такая функция в вопросе стоит, я трогать не стал
Он мне написал в лс, я поменял переменные немного на "рабочие" ( поменял ltu и loop ) и он сказал что код заработал, я думаю у него loop имеет false
98018FB8-2338-4576-857B-90D107B3545E.jpeg

Вроде ответил на его вопросы и помог ему
 

XRLM

Известный
2,552
870
как убрать задержку в ответе на диалог?
Lua:
require 'lib.moonloader'
local sampev = require 'lib.samp.events'

function sampev.onShowDialog(id, style, title, button1, button2, text)
    if id == 179 then
        lua_thread.create(function()
            wait(0)
            sampSendDialogResponse(179, 1, 0, "1")
        end)
    end
end
в свит коннекте отвечает без задержки на диалоги, а у меня она есть.