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

meowkins

Новичок
26
0
что не так не запускаеться скрипт
Lua:
function main()
repeat wait(0) until isSampAvailable()
wait(2000)
sampRegisterChatCommand('maf', dialog)
sampAddChatMessage('loading', -1)
while true do
wait(0)
end
end

function dialog
sampShowDialog(1337, '{FF5656}Mafias helper', '{FFFFFF}by sasda', 'ok', 'ne ok', 0)
lua_thread.create(chacker)
end

function chacker
while sampIsDialogActive() do
wait(0)
local result, button, list, input = sampHasDialogRespond(1337)
if result and button == 1 then
sampAddChatMessage('mq', -1)
elseif result and button == 0 then
sampAddChatMessage("qmqmqmqm", -1)
end
end
end
поставь function chacker()
 

Neon3333

Известный
181
71
  • Нравится
Реакции: Morse

Morse

Потрачен
436
70
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Создай обычную кнопку, внутри меняй состояние булевой переменной. Ниже проверяешь true или false и в зависимости от этого показываешь нужный inputtext

---- МОЙ ВОПРОС ----

Как текст в кнопке выставить посередине? заипался через \t и пробелы
не очень понимаю тебя, можно код?
 

Neon3333

Известный
181
71
не очень понимаю тебя, можно код?
 

Morse

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

kizn

\ 0 _ 0 /
Всефорумный модератор
2,408
2,090
нет ты не так понял, что бы звездочки писались я сделал, но мне нужно что бы при нажатии на кнопку звездочки убирались и появлялись символы
Lua:
local checkbox = imgui.ImBool(false) -- в начале кода


-- OnDrawFrame
if checkbox.v then
-- инпут без флага "password"
else
-- инпут с флагом "password"
end

if imgui.Checkbox('Show symbols', checkbox) then
checkbox.v = not checkbox.v
end
Возможный вариант
 
  • Нравится
Реакции: Morse

meowkins

Новичок
26
0
что не так в коде?
хочу что бы выводил мой ник и айди, ну это выводит.ну и что бы оно снизу выводило в каком т/с я нахожусь
вот код
Lua:
events = require 'samp.events'
require 'lib.moonloader'
require 'lib.sampfuncs'
activate = false

font_hud = renderCreateFont("BigNoodleTitlingCyr", 16)
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"}
local _, carid = sampGetVehicleIdByCarHandle(storeCarCharIsInNoSave(PLAYER_PED))
local carname = cars[carid - 399]


function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    local myVehHandle = storeCarCharIsInNoSave(PLAYER_PED)
    sampRegisterChatCommand("carh", carh)
    sampRegisterChatCommand("tp", tp)
    sampRegisterChatCommand("del", asd)
    sampRegisterChatCommand("damag", damag)
    while true do
        renderFontDrawText(font_hud, 'Имя: '..sampGetPlayerNickname(select(2, sampGetPlayerIdByCharHandle(PLAYER_PED)))..' ['.. select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))..' ]', 500, 680, 0xFFFFFFFF)
        renderCreateFont(font_hud, 'Имя ебучего авто: '..cars[select(2, sampGetVehicleIdByCarHandle(storeCarCharIsInNoSave(PLAYER_PED))) - 399, 680, 0xFFFFFFFF])
            wait(0)
    end
end
 

Gat

Участник
52
6
Создай обычную кнопку, внутри меняй состояние булевой переменной. Ниже проверяешь true или false и в зависимости от этого показываешь нужный inputtext

---- МОЙ ВОПРОС ----

Как текст в кнопке выставить посередине? заипался через \t и пробелы
Lua:
-- Центрирование текста в кнопке (кинь в любую часть кода, но не в функцию)
function apply_custom_style()
    imgui.SwitchContext()
    local style = imgui.GetStyle()
    style.ButtonTextAlign = imgui.ImVec2(0.5, 0.5)
end
apply_custom_style()
 

Viem

Известный
49
5
Кто знает, как поменять скорость JetPack без изменения скорости игры)
Знаю что через память, нужен конкретно код если есть.
 

moreveal

Известный
Проверенный
925
624
что не так в коде?
хочу что бы выводил мой ник и айди, ну это выводит.ну и что бы оно снизу выводило в каком т/с я нахожусь
вот код
Lua:
events = require 'samp.events'
require 'lib.moonloader'
require 'lib.sampfuncs'
activate = false

font_hud = renderCreateFont("BigNoodleTitlingCyr", 16)
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"}
local _, carid = sampGetVehicleIdByCarHandle(storeCarCharIsInNoSave(PLAYER_PED))
local carname = cars[carid - 399]


function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    local myVehHandle = storeCarCharIsInNoSave(PLAYER_PED)
    sampRegisterChatCommand("carh", carh)
    sampRegisterChatCommand("tp", tp)
    sampRegisterChatCommand("del", asd)
    sampRegisterChatCommand("damag", damag)
    while true do
        renderFontDrawText(font_hud, 'Имя: '..sampGetPlayerNickname(select(2, sampGetPlayerIdByCharHandle(PLAYER_PED)))..' ['.. select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))..' ]', 500, 680, 0xFFFFFFFF)
        renderCreateFont(font_hud, 'Имя ебучего авто: '..cars[select(2, sampGetVehicleIdByCarHandle(storeCarCharIsInNoSave(PLAYER_PED))) - 399, 680, 0xFFFFFFFF])
            wait(0)
    end
end

Lua:
local events = require 'samp.events'
require 'lib.moonloader'
require 'lib.sampfuncs'
activate = false

font_hud = renderCreateFont("BigNoodleTitlingCyr", 16)

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"}


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

    sampRegisterChatCommand("carh", carh)
    sampRegisterChatCommand("tp", tp)
    sampRegisterChatCommand("del", asd)
    sampRegisterChatCommand("damag", damag)

    while true do
        wait(0)

        local playerid = select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))
        if isCharInAnyCar(PLAYER_PED) then
            local myVehHandle = storeCarCharIsInNoSave(PLAYER_PED)
            local carid = select(2, sampGetVehicleIdByCarHandle(myVehHandle))
            local carname = cars[carid - 399]
            renderFontDrawText(font_hud, 'Имя: '..sampGetPlayerNickname(playerid)..' [ '..playerid..' ]\nИмя ебучего авто: '..carname, 500, 680, 0xFFFFFFFF)
        else
            renderFontDrawText(font_hud, 'Имя: '..sampGetPlayerNickname(playerid)..' [ '..playerid..' ]', 500, 680, 0xFFFFFFFF)
        end
    end
end
 
Последнее редактирование:
  • Влюблен
Реакции: meowkins