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

ufdhbi

Известный
Проверенный
1,455
861
Привет! Скажите пожалуйста как узнать modelid машины по его vehicleid, пример.
Lua:
local VEHICLE_HANDLE = storeCarCharIsInNoSave( PLAYER_PED )
local result, vehicleid = sampGetVehicleIdByCarHandle( VEHICLE_HANDLE )
*Тут функция*, допустим local modelid = getCarModelIdByVehicleId( vehicleid );
if ( modelid == 411 ) then
    return sampAddChatMessage( "Current vehicle: Infernus", -1 );
end
В вике смотрел, к сожалению не нашел.
Lua:
local cars = {"Landstalker","Bravura","Buffalo","Linerunner","Perrenial","Sentinel","Dumper","Firetruck","Trashmaster","Stretch","Manana","Infernus","Voodoo","Pony","Mule","Cheetah","Ambulance","Leviathan","Moonbeam","Esperanto","Taxi","Washington","Bobcat","Whoopee","BFInjection","Hunter","Premier","Enforcer","Securicar","Banshee","Predator","Bus","Rhino","Barracks","Hotknife","Trailer","Previon","Coach","Cabbie","Stallion","Rumpo","RCBandit","Romero","Packer","Monster","Admiral","Squalo","Seasparrow","Pizzaboy","Tram","Trailer","Turismo","Speeder","Reefer","Tropic","Flatbed","Yankee","Caddy","Solair","Berkley'sRCVan","Skimmer","PCJ-600","Faggio","Freeway","RCBaron","RCRaider","Glendale","Oceanic","Sanchez","Sparrow","Patriot","Quad","Coastguard","Dinghy","Hermes","Sabre","Rustler","ZR-350","Walton","Regina","Comet","BMX","Burrito","Camper","Marquis","Baggage","Dozer","Maverick","NewsChopper","Rancher","FBIRancher","Virgo","Greenwood","Jetmax","Hotring","Sandking","BlistaCompact","PoliceMaverick","Boxvillde","Benson","Mesa","RCGoblin","HotringRacerA","HotringRacerB","BloodringBanger","Rancher","SuperGT","Elegant","Journey","Bike","MountainBike","Beagle","Cropduster","Stunt","Tanker","Roadtrain","Nebula","Majestic","Buccaneer","Shamal","hydra","FCR-900","NRG-500","HPV1000","CementTruck","TowTruck","Fortune","Cadrona","FBITruck","Willard","Forklift","Tractor","Combine","Feltzer","Remington","Slamvan","Blade","Freight","Streak","Vortex","Vincent","Bullet","Clover","Sadler","Firetruck","Hustler","Intruder","Primo","Cargobob","Tampa","Sunrise","Merit","Utility","Nevada","Yosemite","Windsor","Monster","Monster","Uranus","Jester","Sultan","Stratum","Elegy","Raindance","RCTiger","Flash","Tahoma","Savanna","Bandito","FreightFlat","StreakCarriage","Kart","Mower","Dune","Sweeper","Broadway","Tornado","AT-400","DFT-30","Huntley","Stafford","BF-400","NewsVan","Tug","Trailer","Emperor","Wayfarer","Euros","Hotdog","Club","FreightBox","Trailer","Andromada","Dodo","RCCam","Launch","PoliceCar","PoliceCar","PoliceCar","PoliceRanger","Picador","S.W.A.T","Alpha","Phoenix","GlendaleShit","SadlerShit","Luggage","Luggage","Stairs","Boxville","Tiller","UtilityTrailer"}

if isCharInAnyCar(playerPed) then
carh = storeCarCharIsInNoSave(playerPed)
cmdl = getCarModel(carh)
carname = cars[cmdl-399]
end

--carname будет содержать имя кара, к примеру infernus
 
  • Нравится
Реакции: imring, AnWu и eiuhuth

SAMP.ASI

Известный
223
53
Как сделать регистрацию команды /фн . Что бы после ее ввода /фн апельсин. В чат отправлялось /f (( апельсин )). Апельсин для теста(значение переменной)
 
  • Нравится
Реакции: eiuhuth

ufdhbi

Известный
Проверенный
1,455
861
Как сделать регистрацию команды /фн . Что бы после ее ввода /фн апельсин. В чат отправлялось /f (( апельсин )). Апельсин для теста(значение переменной)
Lua:
script_name('example')
require "lib.moonloader"


function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
        sampRegisterChatCommand('фн', fn)
        while true do
        wait(0)
       
        end
end

function fn(arg)
    if arg ~= nil then
        sampSendChat(string.format('/f (( %s ))', tostring(arg)))
    end
end
 
  • Нравится
Реакции: SAMP.ASI

AnWu

Guardian of Order
Всефорумный модератор
4,686
5,166
Lua:
script_name('example')
require "lib.moonloader"


function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
        sampRegisterChatCommand('фн', fn)
        while true do
        wait(0)
      
        end
end

function fn(arg)
    if arg ~= nil then
        sampSendChat(string.format('/f (( %s ))', tostring(arg)))
    end
end
Зареганые команды улетают на сервер. Антифлуд будет против твоего кода.
 

SAMP.ASI

Известный
223
53
При использовании такого метода для создания биндов
Lua:
function main() 
  if ( not isSampLoaded() ) then 
  return
  end
  while ( not isSampAvailable() ) do 
  wait( 100 )
  end
  sampRegisterChatCommand('fn', fn)
  sampRegisterChatCommand('sm', sms)
  while true do 
  wait( 0 )
  if ( not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() ) then 
  if ( isKeyJustPressed( VK_MENU ) and isKeyJustPressed( VK_Q ) ) then
  sampSendChat( "/me Обосцал труп" ) 
  wait( 100 )
  sampSendChat( "/anim 62" )
  elseif ( isKeyJustPressed( VK_MENU ) and isKeyJustPressed( VK_P ) ) then 
  sampSendChat( "/healme" )
  end
  end
  end
end
.

Для срабатывания хоткея нужно ждать, как сделать моментальную активацию бинда по нажатию?
 

ufdhbi

Известный
Проверенный
1,455
861
При использовании такого метода для создания биндов
Lua:
function main() 
  if ( not isSampLoaded() ) then 
  return
  end
  while ( not isSampAvailable() ) do 
  wait( 100 )
  end
  sampRegisterChatCommand('fn', fn)
  sampRegisterChatCommand('sm', sms)
  while true do 
  wait( 0 )
  if ( not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() ) then 
  if ( isKeyJustPressed( VK_MENU ) and isKeyJustPressed( VK_Q ) ) then
  sampSendChat( "/me Обосцал труп" ) 
  wait( 100 )
  sampSendChat( "/anim 62" )
  elseif isKeyJustPressed(VK_MENU) and isKeyJustPressed(VK_P) then 
  sampSendChat( "/healme" )
  end
  end
  end
end
.

Для срабатывания хоткея нужно ждать, как сделать моментальную активацию бинда по нажатию?

Lua:
function main()
  if ( not isSampLoaded() ) then
  return
  end
  while ( not isSampAvailable() ) do
  wait( 100 )
  end
  sampRegisterChatCommand('fn', fn)
  sampRegisterChatCommand('sm', sms)
  while true do
  wait( 0 )
  if not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() then 
  if isKeyDown(VK_MENU) and isKeyJustPressed(VK_Q) then
  sampSendChat( "/me Обосцал труп" )
  wait( 100 )
  sampSendChat( "/anim 62" )
  elseif isKeyDown(VK_MENU) and isKeyJustPressed(VK_P) then
  sampSendChat( "/healme" )
  end
  end
  end
end
.
 

SAMP.ASI

Известный
223
53
Lua:
function main()
  if ( not isSampLoaded() ) then
  return
  end
  while ( not isSampAvailable() ) do
  wait( 100 )
  end
  sampRegisterChatCommand('fn', fn)
  sampRegisterChatCommand('sm', sms)
  while true do
  wait( 0 )
  if not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() then 
  if isKeyDown(VK_MENU) and isKeyJustPressed(VK_Q) then
  sampSendChat( "/me Обосцал труп" )
  wait( 100 )
  sampSendChat( "/anim 62" )
  elseif isKeyDown(VK_MENU) and isKeyJustPressed(VK_P) then
  sampSendChat( "/healme" )
  end
  end
  end
end
.
Я не очень понял что изменилось
 

castlefamily

Участник
104
3
Здравствуйте, прошу прощение за такой вопрос, но можно ли sampRegisterChatCommand сделать с несколько входящими параметрами? :(
function cmdabs(str1, str2) <- или нужно всегда разбивать str1 чтобы было несколько параметров?
 

MISTER_GONWIK

Всефорумный гонщик
Всефорумный модератор
1,260
1,740
Здравствуйте, прошу прощение за такой вопрос, но можно ли sampRegisterChatCommand сделать с несколько входящими параметрами? :(
function cmdabs(str1, str2) <- или нужно всегда разбивать str1 чтобы было несколько параметров?
всегда разбивать
 
  • Нравится
Реакции: castlefamily и JEEMBО

k1sher

Известный
201
4
Как можно узнать Id машины в которой сидит игрок? Узнать id машины нужно по id игрока.
 

etoeto

Новичок
7
3
Как использовать эти адреса? Как их активировать?
  • 0xB7CEE4 - [byte/boolean]
  • 0xB7CEE6 - [byte/boolean]