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

SAMP.ASI

Известный
223
53
Почему bind.lua:20: attempt to call global 'sampAddChatMessage' (a nil value)

Lua:
script_name("aaaa")
script_author("aaa")

require "lib.moonloader"
local notf = import 'imgui_notf.lua'

local notf_cunt = 1
local notf_life = 3

function main()
  while true do
    wait(0)
    if isKeyDown(VK_1) and isPlayerPlaying(playerHandle) then
               notf.addNotification(string.format("Notification #%d\n\n\n\n\n\nTime: %s\n\nЭто будет жить аж 25 сек!!11\nSA:MP notification", notf_cunt, os.date()), notf_life)
               notf_cunt = notf_cunt + 1
      while isKeyDown(VK_1) do wait(100) end

       elseif isKeyDown(VK_2) and isPlayerPlaying(playeHande) then
           sampAddChatMessage(string.format("Test"), 0x00DD00)
       end
    end
  end
 

trefa

Известный
Всефорумный модератор
2,097
1,231
Почему bind.lua:20: attempt to call global 'sampAddChatMessage' (a nil value)

Lua:
script_name("aaaa")
script_author("aaa")

require "lib.moonloader"
local notf = import 'imgui_notf.lua'

local notf_cunt = 1
local notf_life = 3

function main()
  while true do
    wait(0)
    if isKeyDown(VK_1) and isPlayerPlaying(playerHandle) then
               notf.addNotification(string.format("Notification #%d\n\n\n\n\n\nTime: %s\n\nЭто будет жить аж 25 сек!!11\nSA:MP notification", notf_cunt, os.date()), notf_life)
               notf_cunt = notf_cunt + 1
      while isKeyDown(VK_1) do wait(100) end

       elseif isKeyDown(VK_2) and isPlayerPlaying(playeHande) then
           sampAddChatMessage(string.format("Test"), 0x00DD00)
       end
    end
  end
Зачем юзать string.format где это не нужно?
Lua:
sampAddChatMessage("Test", 0x00DD00)
ещё на это замени
Lua:
isPlayerPlaying(PLAYER_PED)
 
Последнее редактирование:

trefa

Известный
Всефорумный модератор
2,097
1,231
Чет не работает
И не будет, проверки вообще ужас
Lua:
if getAllChars() ~= nil then
for i, val in pairs(getAllChars()) do
if doesCharExist(val) then
res , id = sampGetPlayerIdByCharHandle(val)
if res then
if id == pID then print("проверка") end
end
end
end
end
 
  • Нравится
Реакции: KH9I3b_MuJIOCJIABCKu

SAMP.ASI

Известный
223
53
Вот что не так, в логе просто завершен скрипт

Lua:
script_name('example')
require "lib.moonloader"

local notf = import 'imgui_notf.lua'

local notf_cunt = 1
local notf_life = 3

function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
        while true do
                   wait(0)
                   if isKeyDown(VK_1) and isPlayerPlaying(PLAYER_PED) then
                       notf.addNotification(string.format("Notification #%d\n\n\n\n\n\nTime: %s\n\nЭто будет жить аж 25 сек!!11\nSA:MP notification", notf_cunt, os.date()), notf_life)
             notf_cunt = notf_cunt + 1

               elseif isKeyDown(VK_2) and isPlayerPlaying(PLAYER_PED) then
                   sampAddChatMessage("Test", 0x00DD00)
               end
     end
end
 

trefa

Известный
Всефорумный модератор
2,097
1,231
Вот что не так, в логе просто завершен скрипт

Lua:
script_name('example')
require "lib.moonloader"

local notf = import 'imgui_notf.lua'

local notf_cunt = 1
local notf_life = 3

function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
        while true do
                   wait(0)
                   if isKeyDown(VK_1) and isPlayerPlaying(PLAYER_PED) then
                       notf.addNotification(string.format("Notification #%d\n\n\n\n\n\nTime: %s\n\nЭто будет жить аж 25 сек!!11\nSA:MP notification", notf_cunt, os.date()), notf_life)
             notf_cunt = notf_cunt + 1

               elseif isKeyDown(VK_2) and isPlayerPlaying(PLAYER_PED) then
                   sampAddChatMessage("Test", 0x00DD00)
               end
     end
end
sampfuncs установлен?
imgui установлен?
 

SAMP.ASI

Известный
223
53
sampfuncs установлен?
imgui установлен?
Да

Код:
[21:04:59.168626] (system)   Session started.
[21:04:59.169626] (debug)   Module handle: 68A50000

MoonLoader v.026-beta loaded.
Developers: FYP, hnnssy, EvgeN 1137

Copyright (c) 2016, BlastHack Team
https://www.blast.hk/moonloader/

[21:04:59.169626] (info)   Working directory: D:\GAMES\samp\pav\moonloader
[21:04:59.169626] (debug)   FP Control: 0009001F
[21:04:59.169626] (debug)   Game: GTA SA 1.0.0.0 US
[21:04:59.169626] (system)   Installing pre-game hooks...
[21:04:59.169626] (system)   Hooks installed.
[21:05:00.467700] (warn)   Memory test "Win32API: ShowCursor" at address 752C1FC7 has failed. Value is 'E9 84 CE 60 8F', expected 'E9 34 B8 7A F3'.
[21:05:02.421812] (debug)   Initializing opcode handler table
[21:05:02.421812] (debug)   package.path = D:\GAMES\samp\pav\moonloader\lib\?.lua;D:\GAMES\samp\pav\moonloader\lib\?\init.lua;D:\GAMES\samp\pav\moonloader\?.lua;D:\GAMES\samp\pav\moonloader\?\init.lua;.\?.lua;D:\GAMES\samp\pav\moonloader\lib\?.luac;D:\GAMES\samp\pav\moonloader\lib\?\init.luac;D:\GAMES\samp\pav\moonloader\?.luac;D:\GAMES\samp\pav\moonloader\?\init.luac;.\?.luac
[21:05:02.421812] (debug)   package.cpath = D:\GAMES\samp\pav\moonloader\lib\?.dll;
[21:05:02.422812] (system)   Loading script 'D:\GAMES\samp\pav\moonloader\bind.lua'...
[21:05:02.422812] (debug)   New script: 06D90254
[21:05:02.425812] (system)   Loading script 'D:\GAMES\samp\pav\moonloader\imgui_notf.lua'...
[21:05:02.425812] (debug)   New script: 06D903DC
[21:05:02.436813] (system)   imgui_notf.lua: Loaded successfully.
[21:05:02.436813] (system)   example: Loaded successfully.
[21:05:02.436813] (system)   Loading script 'D:\GAMES\samp\pav\moonloader\reload_all.lua'...
[21:05:02.436813] (debug)   New script: 06D94D0C
[21:05:02.437813] (system)   ML-ReloadAll: Loaded successfully.
[21:05:02.437813] (system)   Loading script 'D:\GAMES\samp\pav\moonloader\SF Integration.lua'...
[21:05:02.437813] (debug)   New script: 06D9FA1C
[21:05:02.441813] (system)   SF Integration: Loaded successfully.
[21:05:05.219972] (system)   Installing post-load hooks...
[21:05:05.219972] (system)   Hooks installed.
[21:05:05.219972] (system)   example: Script terminated. (06D90254)
 
Последнее редактирование модератором:

Musaigen

abobusnik
Проверенный
1,583
1,302
Screenshot_10.png

int id ID игрока
float damage количество урона
int weapon ID оружия
int bodypart часть тела
Хуйню сморозил.