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

Andrinall

Известный
704
527
Конфиг тот же, то бишь грязный, неорганизованный: упр. Raspuns4; Raspuns9; и т. д.
Вот мой конфигурационный файл ini с вашим методом:]
Lua:
[Intrebare3]
rand2=
rand1=
[Intrebare15]
rand2=
rand1=
[Intrebare6]
rand2=
rand1=
[Intrebare14]
rand2=
rand1=
[Intrebare1]
rand2=
rand1=
[Intrebare13]
rand2=
rand1=
[Intrebare4]
rand2=
rand1=
[Raspuns]
1=
2=
3=
4=
5=
6=
7=
8=
9=
10=
11=
12=
13=
14=
15=
[Intrebare7]
rand2=
rand1=
[Intrebare12]
rand2=
rand1=
[Intrebare2]
rand2=
rand1=
[Intrebare11]
rand2=
rand1=
[Intrebare5]
rand2=
rand1=
[Intrebare10]
rand2=
rand1=
[Intrebare8]
rand2=
rand1=
[Intrebare9]
rand2=
rand1=
Я хочу, чтобы это было организовано так:
Raspuns1
Raspuns2
Raspuns3
...и т. д

Могу предложить только костыль с переопределением метода библиотеки.
Lua:
local inicfg = require 'inicfg'
local HLcfg = inicfg.load({
    Raspuns = {
        [1]  = " ",
        [2]  = " ",
        [3]  = " ",
        [4]  = " ",
        [5]  = " ",
        [6]  = " ",
        [7]  = " ",
        [8]  = " ",
        [9]  = " ",
        [10] = " ",
        [11] = " ",
        [12] = " ",
        [13] = " ",
        [14] = " ",
        [15] = " "
    },
    Intrebare1 = {
        rand1 = " ",
        rand2 = " "
    },
    Intrebare2 = {
        rand1 = " ",
        rand2 = " "
    },
    Intrebare3 = {
        rand1 = " ",
        rand2 = " "
    },
    Intrebare4 = {
        rand1 = " ",
        rand2 = " "
    },
    Intrebare5 = {
        rand1 = " ",
        rand2 = " "
       },
    Intrebare6 = {
        rand1 = " ",
        rand2 = " "
    },
    Intrebare7 = {
        rand1 = " ",
        rand2 = " "
    },
    Intrebare8 = {
        rand1 = " ",
        rand2 = " "
    },
    Intrebare9 = {
        rand1 = " ",
        rand2 = " "
    },
    Intrebare10 = {
        rand1 = " ",
        rand2 = " "
    },
    Intrebare11 = {
        rand1 = " ",
        rand2 = " "
    },
    Intrebare12 = {
        rand1 = " ",
        rand2 = " "
    },
    Intrebare13 = {
        rand1 = " ",
        rand2 = " "
    },
    Intrebare14 = {
        rand1 = " ",
        rand2 = " "
    },
    Intrebare15 = {
        rand1 = " ",
        rand2 = " "
    }
}, "TestHelper.ini")

local function spairs(t, order)
    local keys = {}
    for k in pairs(t) do keys[#keys+1] = k end
    if order then table.sort(keys, function(a,b) return order(t, a, b) end) else table.sort(keys) end
    local i = 0
    return function() i = i + 1 if keys[i] then return keys[i], t[keys[i]] end end
end

local function find_config(file)
    local workdir = getWorkingDirectory()
    local paths = {
        workdir..[[\config\]]..file..'.ini',
        workdir..[[\config\]]..file,
        file,
    }
    for _, path in ipairs(paths) do
        if doesFileExist(path) then
            return path
        end
    end
    return nil
end

local function ini_value(val)
    local lwr = val:lower()
    if lwr == 'true' then return true end
    if lwr == 'false' then return false end
    return tonumber(val) or val
end

inicfg.save = function(data, file, order)
	assert(type(data) == 'table')
    local file = file or (script.this.filename..'.ini')
    local path = find_config(file)
    local dir
    if not path then
        if file:match('^%a:[\\/]') then
            dir = file:match('(.+[\\/]).-')
            path = file
        else
            if file:sub(-4):lower() ~= '.ini' then
                file = file..'.ini'
            end
            dir = getWorkingDirectory()..[[\config\]]
            path = dir..file
        end
    end
    if dir and not doesDirectoryExist(dir) then
        createDirectory(dir)
    end
    local f = io.open(path, 'w')
    if f then
        for secname, secdata in spairs(data, order) do
            assert(type(secdata) == 'table')
            f:write('['..tostring(secname)..']\n')
            for key, value in pairs(secdata) do
                f:write(tostring(key)..' = '..tostring(value)..'\n')
            end
            f:write('\n')
        end
		f:close()
        return true
    end
    return false
end

function sortConfig(t, a, b)
	local reg = "(%d+)$"
	if not a:find(reg) and not b:find(reg) then return true end
	if not a:find(reg) and b:find(reg) then return true end
	if a:find(reg) and not b:find(reg) then return false end

	local an, bn = a:match(reg), b:match(reg)
	if not tonumber(an) then return false end
	if not tonumber(bn) then return true end
	return tonumber(an) < tonumber(bn)
end

function main()
	inicfg.save(HLcfg, "TestHelper.ini", sortConfig)
end
Код:
[Raspuns]
1 = 
2 = 
3 = 
4 = 
5 = 
6 = 
7 = 
8 = 
9 = 
10 = 
11 = 
12 = 
13 = 
14 = 
15 = 

[Intrebare1]
rand2 = 
rand1 = 

[Intrebare2]
rand2 = 
rand1 = 

[Intrebare3]
rand2 = 
rand1 = 

[Intrebare4]
rand2 = 
rand1 = 

[Intrebare5]
rand2 = 
rand1 = 

[Intrebare6]
rand2 = 
rand1 = 

[Intrebare7]
rand2 = 
rand1 = 

[Intrebare8]
rand2 = 
rand1 = 

[Intrebare9]
rand2 = 
rand1 = 

[Intrebare10]
rand2 = 
rand1 = 

[Intrebare11]
rand2 = 
rand1 = 

[Intrebare12]
rand2 = 
rand1 = 

[Intrebare13]
rand2 = 
rand1 = 

[Intrebare14]
rand2 = 
rand1 = 

[Intrebare15]
rand2 = 
rand1 =
 
  • Нравится
Реакции: sssilvian

NikkiReuz

Участник
53
4
Я хочу в func main скачать недостающие файлы если их нет в папке
В while true do сделал команды со скачиванием
Сразу после main пишутся local imgui, local themes = ...(их и надо скачать) и в итоге скрипт сразу видит что нет файла, но не скачивает его(то есть среагировал на импорт, а не на if not doesFileExist).

lua:
local dlstatus = require('moonloader').download_status
local download1 = false
local download2 = false
local download3 = false
 
 if not doesFileExist("moonloader/resource/fonts/fontawesome-webfont.ttf") then
        sampAddChatMessage('{FF0000}[Menu]{FFFFFF}: Шрифт с иконами не был найден, началось автоматическое скачивание', -1)
        download1 = true
        end
 if not doesFileExist("moonloader/lib/faIcons.lua") then
        sampAddChatMessage('{FF0000}[Menu]{FFFFFF}: Не был найден плагин для иконок, началось автоматическое скачивание', -1)
        download2 = true
        end
 if not doesFileExist("moonloader/resource/imgui_themes.lua") then
        sampAddChatMessage('{FF0000}[Menu]{FFFFFF}: Не были найдены стили для imgui, началось автоматическое скачивание', -1)
        download3 = true
        end
 
 while true do
     wait(0)
     if download1 then
        downloadUrlToFile("https://drive.google.com/uc?export=download&confirm=no_antivirus&id=1IRMZRh1kSQoE1Dhe84WCol22wIM0_d0r", getWorkingDirectory()..'/resource/fonts/fontawesome-webfont.ttf', function(id, status)
          if status == dlstatus.STATUS_ENDDOWNLOADDATA then sampAddChatMessage('{FF0000}[Menu]{FFFFFF}: Скачивание шрифта успешно завершено.', -1) end
        end)
    end
     if download2 then
        downloadUrlToFile("https://drive.google.com/uc?export=download&confirm=no_antivirus&id=1PG7NLVa0_EJFdJMp5YIr-EqrG0Y70AG6", getWorkingDirectory()..'/lib/faIcons.lua', function(id, status)
        if status == dlstatus.STATUS_ENDDOWNLOADDATA then sampAddChatMessage('{FF0000}[Menu]{FFFFFF}: Скачивание иконок успешно завершено.', -1) end
        end)
    end       
     if download3 then
        downloadUrlToFile("https://drive.google.com/uc?export=download&confirm=no_antivirus&id=1V2BKLWjInyKuAfLhWT5uLN2v967Q2Jq2", getWorkingDirectory()..'/resource/imgui_themes.lua', function(id, status)
        if status == dlstatus.STATUS_ENDDOWNLOADDATA then sampAddChatMessage('{FF0000}[Menu]{FFFFFF}: Скачивание стилей успешно завершено.', -1) end
        end)
    end

local imgui = require "imgui"
local mem = require "memory"
local themes = import "resource/imgui_themes.lua"
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local sw, sh = getScreenResolution()
local main_window_state = imgui.ImBool(false)
local page = page
local anim = anim
local inicfg = require 'inicfg'
local directIni = "config//ReuzMenu.ini"
local ini = inicfg.load({
        Themes = {
        theme = 1
        },
        }, directIni)
inicfg.save(ini, directIni)
local checked_radio = imgui.ImInt(ini.Themes.theme)
 

Dmitriy Makarov

25.05.2021
Проверенный
2,516
1,142
Lua:
-- To the beginning
local buf = imgui.ImBuffer(24)

-- Wherever you need
imgui.InputText("ID", buf, imgui.InputTextFlags.CharsDecimal)
if imgui.Button("Give", imgui.ImVec2(80, 30)) then
    if buf.v ~= "" then
        sampSendChat("/givelicense "..buf.v)
    end   
end
 

NikkiReuz

Участник
53
4
Я застрял на этом здесь. Я хочу поместить в это меню ImGui поле ввода, куда идет идентификатор, а кнопка ниже должна отправить следующую команду в чат: /givelicense (идентификатор из ящика)

Код:
        if imgui.BeginTabItem('Sailing') then
            imgui.Text('Licente')
        imgui.SetCursorPos(imgui.ImVec2(10, 100))
    if imgui.Button('Give',imgui.ImVec2(80, 30)) then
    lua_thread.create(function()
        sampSendChat("/givelicense (do the ID here) ")
    end)
    end
            imgui.EndTabItem()
        end
Я хочу сказать, что я не знаю, как сделать поле ввода и передать поле ввода в функцию sampSendChat.


Lua:
local imgui = require 'mimgui'
local wm = require 'windows.message'
local vkeys = require 'vkeys'
local samp = require 'samp.events'
local sampev = require("lib.samp.events")
require "lib.moonloader"
local sw, sh = 400, 500
local active = imgui.new.bool(false)
local checkbox = imgui.new.bool(false)

function sampev.onSendCommand(text)
    if text:lower() == '/recf'--[[text:lower():find('/blm') or text:lower():find('/george_floyd')]] then
        active[0] = not active[0]
    end
end

imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
    imgui.StyleColorsDark()
end)

local mainFrame = imgui.OnFrame(function() return active[0] end, function(self)
    imgui.SetNextWindowSize(imgui.ImVec2(sw, sh), imgui.Cond.FirstUseEver)
    imgui.Begin('SFSI Helper', active)
    if imgui.BeginTabBar('Tabs') then
        if imgui.BeginTabItem('Flying') then
            imgui.Text('Licente')
        imgui.SetCursorPos(imgui.ImVec2(30, 140))
    if imgui.Button('Intrebarea 3',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("Test")
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Done.")
    end)
    end
            imgui.EndTabItem()
        end
        if imgui.BeginTabItem('Sailing') then
            imgui.Text('Licente')
        imgui.SetCursorPos(imgui.ImVec2(10, 100))
    if imgui.Button('Give',imgui.ImVec2(80, 30)) then
    lua_thread.create(function()
        sampSendChat("/givelicense (do the ID here) ")
    end)
    end
            imgui.EndTabItem()
        end
        if imgui.BeginTabItem('Fishing') then
            imgui.Text('cf')
            imgui.Checkbox('Tab 3', checkbox)
            imgui.Checkbox('Tab 3##2', checkbox)
            imgui.EndTabItem()
        end
        if imgui.BeginTabItem('Weapon') then
            imgui.Text('Licente')
            imgui.Checkbox('Tab 3', checkbox)
            imgui.Checkbox('Tab 3##2', checkbox)
            imgui.EndTabItem()
        end
        if imgui.BeginTabItem('Tab 3') then
            imgui.Text('Materials')
           
            imgui.EndTabItem()
        end
        imgui.EndTabBar()
    end
    imgui.End()
end)
Это весь код, если он вам нужен.
Кроме того, как мне изменить его тему? (пользовательские цвета)
С темой помогу, но чуть позже. Щас спать лягу
 

21Cristi

Новичок
3
0
Lua:
-- To the beginning
local buf = imgui.ImBuffer(24)

-- Wherever you need
imgui.InputText("ID", buf, imgui.InputTextFlags.CharsDecimal)
if imgui.Button("Give", imgui.ImVec2(80, 30)) then
    if buf.v ~= "" then
        sampSendChat("/givelicense "..buf.v)
    end  
end
HOURКак мне сделать "/givelicense ID flying"? или "/sx имя_игрока (ID), привет"Как мне сделать "/givelicense ID flying"? или "/sx имя_игрока (ID), привет"
 

Dmitriy Makarov

25.05.2021
Проверенный
2,516
1,142
[ML] (error) cvfain.lua: C:\Users\CRISTIAN\Desktop\samp clasik\moonloader\cvfain.lua:66: unexpected symbol near ')'
[ML] (error) cvfain.lua: Script died due to an error. (0F39A994)
Lua:
local imgui = require 'mimgui'
local samp = require 'samp.events'
local sampev = require("lib.samp.events")
require "lib.moonloader"

local sw, sh = 400, 500
local active = imgui.new.bool(false)
local checkbox = imgui.new.bool(false)
local buf = imgui.ImBuffer(24)

function sampev.onSendCommand(text)
    if text:lower() == '/recf'--[[text:lower():find('/blm') or text:lower():find('/george_floyd')]] then
        active[0] = not active[0]
    end
end

imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
    imgui.StyleColorsDark()
end)

local mainFrame = imgui.OnFrame(function() return active[0] end, function(self)
    imgui.SetNextWindowSize(imgui.ImVec2(sw, sh), imgui.Cond.FirstUseEver)
    imgui.Begin('SFSI Helper', active)
    if imgui.BeginTabBar('Tabs') then
        if imgui.BeginTabItem('Flying') then
            imgui.Text('Licente')
        imgui.SetCursorPos(imgui.ImVec2(30, 140))
    if imgui.Button('Intrebarea 3',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("Test")
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Done.")
    end)
    end
            imgui.EndTabItem()
        end
        if imgui.BeginTabItem('Sailing') then
            imgui.Text('Licente')
    imgui.InputText("ID", buf, imgui.InputTextFlags.CharsDecimal)
    if imgui.Button("Give", imgui.ImVec2(80, 30)) then
    if buf.v ~= "" then
        sampSendChat("/givelicense "..buf.v)
    end  
            imgui.EndTabItem()
        end
        if imgui.BeginTabItem('Fishing') then
            imgui.Text('cf')
            imgui.Checkbox('Tab 3', checkbox)
            imgui.Checkbox('Tab 3##2', checkbox)
            imgui.EndTabItem()
        end
        if imgui.BeginTabItem('Weapon') then
            imgui.Text('Licente')
            imgui.Checkbox('Tab 3', checkbox)
            imgui.Checkbox('Tab 3##2', checkbox)
            imgui.EndTabItem()
        end
        if imgui.BeginTabItem('Tab 3') then
            imgui.Text('Materials')
           
            imgui.EndTabItem()
        end
        imgui.EndTabBar()
    end
    imgui.End()
end)
Что я делаю не так?
I don't know, I can't understand because of broken tabs. I also noticed that you use mimgui, and I gave you an example with imgui. So, replace the example I gave with this one.
Lua:
-- To the beginning
local ffi = require "ffi"
local buf = imgui.new.char[24]()

-- Wherever you need
imgui.InputText("ID", buf, ffi.sizeof(buf), imgui.InputTextFlags.CharsDecimal)
if imgui.Button("Give", imgui.ImVec2(80, 30)) then
    if ffi.string(buf) ~= "" then
        sampSendChat("/givelicense "..ffi.string(buf))
    end
end
 

Andrinall

Известный
704
527
Я хочу в func main скачать недостающие файлы если их нет в папке
В while true do сделал команды со скачиванием
Сразу после main пишутся local imgui, local themes = ...(их и надо скачать) и в итоге скрипт сразу видит что нет файла, но не скачивает его(то есть среагировал на импорт, а не на if not doesFileExist).

lua:
local dlstatus = require('moonloader').download_status
local download1 = false
local download2 = false
local download3 = false
 
 if not doesFileExist("moonloader/resource/fonts/fontawesome-webfont.ttf") then
        sampAddChatMessage('{FF0000}[Menu]{FFFFFF}: Шрифт с иконами не был найден, началось автоматическое скачивание', -1)
        download1 = true
        end
 if not doesFileExist("moonloader/lib/faIcons.lua") then
        sampAddChatMessage('{FF0000}[Menu]{FFFFFF}: Не был найден плагин для иконок, началось автоматическое скачивание', -1)
        download2 = true
        end
 if not doesFileExist("moonloader/resource/imgui_themes.lua") then
        sampAddChatMessage('{FF0000}[Menu]{FFFFFF}: Не были найдены стили для imgui, началось автоматическое скачивание', -1)
        download3 = true
        end
 
 while true do
     wait(0)
     if download1 then
        downloadUrlToFile("https://drive.google.com/uc?export=download&confirm=no_antivirus&id=1IRMZRh1kSQoE1Dhe84WCol22wIM0_d0r", getWorkingDirectory()..'/resource/fonts/fontawesome-webfont.ttf', function(id, status)
          if status == dlstatus.STATUS_ENDDOWNLOADDATA then sampAddChatMessage('{FF0000}[Menu]{FFFFFF}: Скачивание шрифта успешно завершено.', -1) end
        end)
    end
     if download2 then
        downloadUrlToFile("https://drive.google.com/uc?export=download&confirm=no_antivirus&id=1PG7NLVa0_EJFdJMp5YIr-EqrG0Y70AG6", getWorkingDirectory()..'/lib/faIcons.lua', function(id, status)
        if status == dlstatus.STATUS_ENDDOWNLOADDATA then sampAddChatMessage('{FF0000}[Menu]{FFFFFF}: Скачивание иконок успешно завершено.', -1) end
        end)
    end       
     if download3 then
        downloadUrlToFile("https://drive.google.com/uc?export=download&confirm=no_antivirus&id=1V2BKLWjInyKuAfLhWT5uLN2v967Q2Jq2", getWorkingDirectory()..'/resource/imgui_themes.lua', function(id, status)
        if status == dlstatus.STATUS_ENDDOWNLOADDATA then sampAddChatMessage('{FF0000}[Menu]{FFFFFF}: Скачивание стилей успешно завершено.', -1) end
        end)
    end

local imgui = require "imgui"
local mem = require "memory"
local themes = import "resource/imgui_themes.lua"
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local sw, sh = getScreenResolution()
local main_window_state = imgui.ImBool(false)
local page = page
local anim = anim
local inicfg = require 'inicfg'
local directIni = "config//ReuzMenu.ini"
local ini = inicfg.load({
        Themes = {
        theme = 1
        },
        }, directIni)
inicfg.save(ini, directIni)
local checked_radio = imgui.ImInt(ini.Themes.theme)

В одном из скриптов у меня есть авто-обновление нужных ресурсов и делается это примерно так.
Lua:
-- где-то там
local download_states = { false, false, false }
local downloads_count = 0

-- в загрузке конфигов
if not doesFileExist(map_image_path) or ( map_ver > script_resource_versions.map_image ) then
	if doesFileExist(map_image_path) then os.remove(map_image_path) end

	download_states[3] = true
	log:write("Загружается ресурс : %s", map_image_path)

	downloadUrlToFile("--link--", map_image_path, function(_, status)
		if status == 6 then
			script_resource_versions.map_image = map_ver
			download_states[3] = false
			downloads_count = downloads_count + 1
			log:write("Загрузка завершена, версия карты : %.2f", script_resource_versions.map_image)
		end
	end)
end

-- в main
repeat wait(100) until not awaitDownloads() -- функа чекающая download_states на true

if downloads_count > 0 then
	local scfile = io.open(scfg_path, 'w')
	scfile:write(encodeJson(script_resource_versions, true))
	scfile:close()

	sampAddChatMessage(scriptname .. " Необходимые ресурсы загружены. Перезагрузка ...", -1)
	thisScript():reload()
end
 
  • Нравится
Реакции: qdIbp

Andrinall

Известный
704
527
как с помощью onGivePlayerWeapon выдать оружие?
Если ты про callback из samp.Lua, то он и так вызывается при выдаче оружия сервером.
Можешь попробовать подменить модель выдаваемого оружия, но сомневаюсь что античит одобрит.
 

Dmitriy Makarov

25.05.2021
Проверенный
2,516
1,142
How do I make it so it types "/givelicense ID flying"?
and if you put the ID in there and press a button (with the script so it types on chat "/sx PlayerName (ID) at me)
Lua:
sampSendChat(string.format("/givelicense %s", ffi.string(buf))
-- /givelicense 123
sampSendChat(string.format("/sx %s %s", sampGetPlayerNickname(ffi.string(buf), ffi.string(buf))
-- /sx Nick_Name 123
 

Dmitriy Makarov

25.05.2021
Проверенный
2,516
1,142
sampSendChat(string.format("/sx L-a acceptat cineva pe %s (%s) ?", sampGetPlayerNickname(ffi.string(buf), ffi.string(buf))
Lua:
sampSendChat(string.format("/sx L-a acceptat cineva pe %s (%s) ?", sampGetPlayerNickname(ffi.string(buf)), ffi.string(buf)))

Another thing, if you can help me. I can't figure out what it can come from. In other mods, the commands work properly, they don't show the message "Eroare: Comanda neconuscuta." which means in english "Error: Unknown command" recognized by the server.
Here is a video so you can understand:
Your command is sent to the server, because of this the server tells you that this is an unknown command:
function sampev.onSendCommand(text) if text:lower() == '/recf'--[[text:lower():find('/blm') or text:lower():find('/george_floyd')]] then active[0] = not active[0] end end
Try this.
Lua:
-- in main()
sampRegisterChatCommand("recf", function()
    active[0] = not active[0]
end)
 
Последнее редактирование:

[SA ARZ]

Известный
394
8
189034

Пытаюсь вытащить по методу /members, но увы - мб кто знает как? и мне желательно в imgui все ники вывести.
 

chapo

tg/inst: @moujeek
Всефорумный модератор
9,203
12,526
Lua:
sampSendChat(string.format("/sx L-a acceptat cineva pe %s (%s) ?", sampGetPlayerNickname(ffi.string(buf)), ffi.string(buf)))
1. можно же вместо string.format('text', var) писать сразу ('text'):format(var)
2. sampGetPlayerNickname вроде бы крашнется если передать в него строку
3. если игрока с идом нет в сети, но при этом ты юзнешь sampGetPlayerNickname, то скрипт вроде бы тоже крашнется
 
  • Нравится
Реакции: Dmitriy Makarov