Как исправить ошибку lua в гаррис мод

What Are Lua Errors?

A Lua error is caused when the code that is being ran is improper. There are many reasons for why a Lua error might occur, but understanding what a Lua error is and how to read it is an important skill that any developer needs to have.

Effects of Errors on Your Scripts

An error will halt your script’s execution when it happens. That means that when an error is thrown, some elements of your script might break entirely. For example, if your gamemode has a syntax error which prevents init.lua from executing, your entire gamemode will break.

Lua Error Format

The first line of the Lua error contains 3 important pieces of information:

  • The path to the file that is causing the error
  • The line that is causing the error
  • The error itself

Here is an example of a code that will cause a Lua error:

local text = «Hello World»
Print( text )

The code will produce the following error:

[ERROR]addons/my_addon/lua/autorun/server/sv_my_addon_autorun.lua:2: attempt to call global ‘Print’ (a nil value)
1. unknown addons/my_addon/lua/autorun/server/sv_my_addon_autorun.lua:2

That is because Print is not an existing function (print, however, does exist).

The first line includes the path to the file that is causing the error — addons/my_addon/lua/autorun/server/sv_my_addon_autorun.lua

Afterwards, the line that’s producing the error — sv_my_addon_autorun.lua:2 (Line 2)

Lastly, the error itself — attempt to call global ‘Print’ (a nil value)

Below the error, we have the trace of the function. Simplified — If the error is inside a function/chunk of code that is called from somewhere else, it will state where the code is called from.

If the error happens serverside, the text color will be blue. If it happened clientside, it will be yellow. If it’s menu code, it will be green (not a typical scenario). Messages which look like errors but are colored differently, such as red or white, are not Lua errors but rather engine errors.

Printing Your Own

If you want to print your own error messages, there are three functions to do it:

  • error will print your message, halt execution, and print the stack. Normal error behavior.
  • ErrorNoHalt will print the file/line number and your message without halting the script. Useful for warning messages.
  • assert will check to make sure that something is true. If it’s not, it will print your message and halt just like error does.

Common Errors

Attempt to call global ‘?’ a nil value

Description: You tried to call a function that doesn’t exist.

Possible causes:

  • Your function might be defined in another Lua state. (e.g Calling a function on the client that only exists on the * server.)
  • You’re using a metafunction on the wrong kind of object. (e.g. Calling :SteamID() on a Vector)
  • The function you’re calling has an error in it which means it is not defined.
  • You’ve misspelled the name of the function.

Ways to fix:

  • Make sure the function exists
  • Make sure your function is defined in the correct realm
  • Check your function calls for spelling errors

Attempt to perform arithmetic on global ‘?’ (a nil value)

Description: You tried to perform arithmetic (+, -, *, /) on a global variable that is not defined.

Possible causes:

  • You tried to use a local variable that was defined later in the code
  • You’ve misspelled the name of the global variable

Ways to fix:

  • Make sure you define local variables before calling them in the code
  • Check for spelling errors

Attempt to perform arithmetic on ‘?’ (a type value)

Description: You tried to perform arithmetic (+, -, *, /) on a variable that cannot perform arithmetic. (e.g. 2 + «some string»)

Attempt to index global ‘varname’ (a nil value)

Description: You tried to index an undefined variable (e.g. print( variable.index ) where variable is undefined)

Possible causes:

  • The variable is defined in a different realm
  • The variable is local and defined later in the code
  • You’ve misspelled the name of the variable

Ways to fix:

  • Make sure the variable is only accessed in the realm it was defined in
  • If the variable is local, define it before accessing it

Malformed number near ‘number’

Description: There is a malformed number in the code (e.g. 1.2.3, 2f)

Possible causes:

  • An IP address was written as a number instead of a string
  • Incorrect writing of multiplication of a number and a variable
  • Trying to concatenate a number to a string without a space between the number and the operator.

Ways to fix:

  • Store IP addresses as a string
  • Multiply variables with numbers by using the ***** operator
  • Put a space between the concat (..) operator and the number.

Unexpected symbol near ‘symbol’

Description: You typed a symbol in the code that Lua didn’t know how to interpret.

Possible causes:

  • Incorrect syntax (e.g. Forgot to write «then» after an if statement)
  • Not closing brackets and parentheses at the correct locations

Ways to fix:

  • Make sure there are no mistypes in the code
  • Close brackets and parentheses correctly (See: Code Indentation)

‘symbol1’ expected near ‘symbol2’

Description: Lua expected symbol1 instead of symbol2.
When ‘symbol2’ is <eof>, Lua expected a symbol before the end of the file

Possible causes:

  • Not closing all brackets, parentheses or functions before the end of the file
  • Having too many end statements
  • Wrong operator calling (e.g. «==» instead of «=»)
  • Missing comma after table item.

Ways to Fix

  • Close brackets and parentheses correctly (See: Code Indentation)
  • Use the correct operators
  • Add a comma after a table item

СПОСОБ №1 НЕОБЯЗАТЕЛЕН К ПРИМЕНЕНИЮ, МОЖЕТЕ ПЕРЕХОДИТЬ К СПОСОБУ №2 — «АКТИВАЦИЯ БЕТА-ВЕРСИИ».

Попробуем разобрать решения данной ошибки.

Вам нужно как минимум 2-3 ГБ свободной оперативной памяти, чтобы играть в игру, или как минимум 4-8 ГБ оперативной памяти, установленной, как указано в разделах системных требований на странице Steam Store для Garry’s Mod.
Если вы уверены, что ваше количество оперативной памяти, точно удовлетворяет требованиям игры, попробуйте это

Параметры запуска

1. В Steam, нажмите правой кнопкой мыши по игре Garry’s mod, дальше нажмите Свойства

steam_qzVRv5qOTd.png

2. Найдите поле Параметры запуска

1610871169948.png

Выберите параметры, которые подходят вам:

Если у вас, 2ГБ оперативной памяти

-heapsize 2097152

Если у вас, 4ГБ оперативной памяти

-heapsize 4194304

Если у вас, 6ГБ оперативной памяти

-heapsize 6291456

Если у вас, 8ГБ оперативной памяти (и более)

-heapsize 8388608

Бета-версии

1. В Steam, нажмите правой кнопкой мыши по игре Garry’s mod, дальше нажмите Свойства

steam_qzVRv5qOTd.png

2. Перейдите в раздел Бета-версии и выберите x86-64 — Chromium + 64-bit binaries

1610872320489.png

Отписаться от лишних аддонов

Если ошибка продолжает появляться, попробуйте:

1. Зайти в игру, далее Дополнения

1623499713514.png

2. Гаечный ключ в правом нижнем углу, Удалить всё

1623499836561.png

1623499980058.png

В этом руководстве мы расскажем, как исправить ошибку Gmod LUA PANIC: недостаточно памяти. Garry’s Mod, также известный как Gmod, относится к категории игр-песочниц. Мод основной игры не имеет никаких целей как таковых, позволяя вам свободно перемещаться и выполнять желаемую задачу. С другой стороны, существует множество различных модов, созданных сторонними разработчиками, которые добавляют уникальные и интересные миссии и придают игре новый вид. Кроме того, существует также некоторый пользовательский контент.

Хотя все это делает игровой процесс довольно сложным, но это то, с чем пользователи могут легко соревноваться. Но то, с чем они не могут конкурировать и считают это еще более сложной задачей, — это ошибка Gmod LUA PANIC: недостаточно памяти. Если вы тоже столкнулись с этой проблемой, не волнуйтесь. В этом руководстве мы поделились различными методами исправления этой ошибки. Итак, без лишних слов, давайте начнем с руководства.

gmod Недостаточно памяти

Как исправить Gmod LUA PANIC Недостаточно памяти

Что ж, дело в том, что в ошибке четко указано, что ошибка связана с ограниченными ресурсами оперативной памяти. То есть ваш компьютер не соответствует требуемому уровню оперативной памяти. Однако вот в чем загвоздка. Некоторые пользователи сообщают об этой ошибке, даже если их компьютер соответствует этому базовому требованию к оперативной памяти. Если это так и с вами, воспользуйтесь приведенным ниже методом, чтобы исправить ошибку Gmod LUA PANIC: недостаточно памяти.

Шаги для выполнения

  1. Прежде всего, запустите приложение Steam на своем ПК.
  2. Перейдите в раздел библиотеки, где показаны все ваши установленные игры.
  3. Щелкните правой кнопкой мыши Gmod (Garry’s Mod) и выберите «Свойства». Свойства Gmod LUA PANIC
    Источник: Форум Steam
  4. В диалоговом окне свойств Garry’s Mod перейдите на вкладку Общие и нажмите УСТАНОВИТЕ ОПЦИИ ЗАПУСКА.
    установить вариант запуска
  5. Под УСТАНОВИТЬ ОПЦИИ ЗАПУСКА В диалоговом окне вам нужно будет ввести следующие данные в зависимости от вашей оперативной памяти.
    Gmod RAM heapsize
  6. Если у вас 2 ГБ оперативной памяти, введите:
    - размер 2097152

    С другой стороны, для 4 ГБ ОЗУ введите:

    - размер 4194304

    Или, если у вас 8 ГБ ОЗУ, введите:

    - размер 8388608
  7. Как только вы это сделаете, запустите Gmod и загрузите сервер, посмотрите, была ли исправлена ​​ошибка Gmod LUA PANIC Недостаточно памяти или нет.
  8. Если нет, вы можете внести несколько поправок. Для этого снова перейдите в диалоговое окно SET LAUNCH OPTIONS и внесите следующие изменения:
  9. Если у вас 8 ГБ ОЗУ, введите:
    - размер 4194304

    С другой стороны, пользователи, имеющие 4 ГБ ОЗУ, должны ввести:

    - размер 2097152
  10. Как только это будет сделано, сохраните его и запустите игру. Для тех, кто задается вопросом, что мы только что сделали, мы только что перераспределили размер кучи. Например, для 8 ГБ ОЗУ был выделен размер кучи 4 ГБ, а последнему был выделен размер кучи 2 ГБ. В любом случае, теперь попробуйте запустить игру, и ошибка должна была быть исправлена.

Вывод

Итак, это все было от нас в этом руководстве. Мы надеемся, что описанный выше метод должен был исправить ошибку Gmod LUA PANIC: недостаточно памяти. Если у вас все еще есть сомнения, задавайте свои вопросы в разделе комментариев ниже. В связи с этим не забудьте ознакомиться с нашими Советы и хитрости iPhone, Советы и хитрости для ПК, а также Советы и хитрости для Android.

Статьи по Теме

  • Исправить ошибку модуля Garry’s Mod Engine, фатальный выход из приложения и ошибку записи на диск
  • Как исправить дополнения, которые не загружаются в игре / отсутствуют загруженные файлы Ошибка: Garry’s Mod

Neon

  • #1

В этой теме я научу читать и понимать ошибки, возникающие в коде

от криворукости

из-за невнимательности.
1. Разбор структуры ошибок. Структура у всех ошибок одинаковая и состоит из названия файла, строки, описания ошибки и трассировки ошибки.
Рассмотрим на примере

Код:

[ERROR] addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:119: Tried to use a NULL entity!
1. SetModel - [C]:-1
2. SpawnEntity - addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:119
3. LeftClick - addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:142
4. unknown - gamemodes/sandbox/entities/weapons/gmod_tool/shared.lua:251

Название файла — где произошла ошибка:

Код:

addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua

Строка ошибки: 119
Описание ошибки: Tried to use a NULL entity!
Трассировка — показывает какие функции и в каких файлах предшествуют нашей ошибке:

Код:

1. SetModel - [C]:-1
2. SpawnEntity - addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:119
3. LeftClick - addons/ttt weapon placer/lua/weapons/gmod_tool/stools/tttweaponplacer.lua:142
4. unknown - gamemodes/sandbox/entities/weapons/gmod_tool/shared.lua:251

2. Описания ошибок. Чтобы понять как решить задачу, нам надо понять что произошло. В этом нам всегда помогает описание ошибки. Ниже я привожу типичные описания ошибок, наиболее часто встречающихся при разработке. (Список не полный и я буду рад вашим дополнениям)

  • Tried to use a NULL entity! — означает, что пытаешься использовать несуществующую энтити. Проверь что у тебя в переменной.
  • Tried to use a NULL physics object! — вызванная энтити пытается быть физичной, но у неё нет модели.
  • attempt to index global ‘MutantSpawns’ (a nil value) — попытка использовать в коде неинициализированную переменную. Проще говоря, переменная пуста, а к ней происходит обращение.
  • bad argument #1 to ‘FindByClass’ (string expected, got userdata) — неверный аргумент №1. Там должна быть строка, а получена userdata.
  • bad argument #1 to ‘pairs’ (table expected, got nil) — тоже неверный аргумент, должна быть таблица, а получено нулевое значение.
  • bad argument #1 to ‘JSONToTable’ (string expected, got no value) — ещё одна похожая херня, должна быть строка, а получено нулевое значение.
  • attempt to compare nil with number — сравнение числа и нулевой переменной.
  • table index is nil — попытка обращения к нулевому элементу.
  • Couldn’t include file ‘shared.lua’ (File not found) — не найден файл shared.lua
  • Calling net.Start with unpooled message name! [http://goo.gl/qcx0y] — попытка вызвать функцию net.Start с неизвестным идентификатором. Решается строкой util.AddNetworkString(«ваш идентификатор»)

3. Отсутствие ошибок.
Бывают случаи, когда не понятно почему не запускается сам мод. Такое случается когда в коде происходит фатальная ошибка и мод вообще не загружается. Это можно определить по такой строке:

Код:

Couldn't Load Init Script: 'darkrp/gamemode/init.lua'

В этом случае необходимо проверить последние изменения в коде и отменить их при необходимости. Скорее всего дело в пропущенных скобках, нарушающих синтаксис.

Если же сам мод работает, а не запускается определённые аддоны, то это может быть следствием:

  • перекрытия кода (переопределение переменных, функций и пр. в этом или другом файле)
  • файл со скриптом не был подключен
  • нефатальное нарушение синтаксиса

Последнее редактирование: 7 Янв 2019

When working with Garry’s Mod, a good deal of the time you’ll be working with Lua scripts which can be rather particular about how to do things. This serves as a basic guide to help you solve some issues with scripts that don’t work.

Console errors

Errors in the console almost always have the file and line number where the error happened, and if the server has simplerr installed (it comes with DarkRP and a few other mods) the error will also have a few hints regarding what may have gone wrong, the hints are also usually ordered in most likely to least likely

Below is a sample error message that you might see in the console, which a breakdown of the information it gives you:

Example Lua Rrror

The section outlined in red, is the name of the file that the error occurred in, in this case modificationloader.lua

Example Lua Error with filename highlighted

The section outlined in green is the line number inside of that file where the error occurred. in this case 137

Example Lua Error with line number highlighted

The section outlined in blue is the file path where the file can be found, which in this case in /gamemodes/darkrp/gamemode/libraries/ (which is actually found in the /garrysmod/ folder in the main directory, so the full file path is /garrysmod/gamemodes/darkrp/gamemode/libraries/.

Example Lua Error with file path highlighted

There will not be any hints if the exact cause is unknown, in which case the game may output The best help I can give you is this: before the error. This is only true for servers that have Simplerr installed, such as with DarkRP.

As an example:

Example Lua Error with simplerr trace

In addition to the console, Lua errors experienced by a player are put into the /garrysmod/clientside_errors.txt file.

Sample error messages

Couldn't include file 'script.lua' (File not found) (Lua file)

The Lua file tried to import another lua file, but couldn’t find it. Make sure the addon the lua file is from was installed correctly, and that any required addons are also installed.

file.lua:1: attempt to call global 'varName' (a nil value)

An addon or Lua script (in this case file.lua) tried to call a variable or function (in this case varName) that hasn’t been given a value yet (in this case, the call happened at line 1). Usually caused by one of the following:

  • Another addon or Lua script is supposed to be on the server and isn’t

  • Another addon or Lua script failed to load correctly

  • The addon or Lua script is for an older version of the game, and no longer works

file.lua:4: attempt to index local 'varTable' (a nil value)

The Lua script (in this case file.lua) tried to access a table that doesn’t exist. Check the file for when that table was made and see what went wrong (there’s usually going to be another error that caused this one that happened earlier)

For more information and example error messages, you can look here: https://wiki.garrysmod.com/page/Lua_Error_Explanation

Some helpful tips to avoid errors

  • '1' equals 1 will return false, but in any other circumstance they would be interchangeable.

  • When working with and, or, or not, false and nil are ‘falsey’ values, and everything else is ‘truthy’

  • and and or can be a little complicated:

    • a and b returns a if a is false or nil, and b otherwise

    • a or b returns a unless a is false or nil, in which case it returns b

Most other issues you’ll encounter will be with variables, you can read about them here: https://wiki.garrysmod.com/page/Beginner_Tutorial_Variables

Naming conventions

  • Global variables are in ALL_CAPITAL_LETTERS (as well as local variables that are always a copy of a global variable): THE_QUICK_BROWN_FOX_JUMPS_OVER_THE_LAZY_DOG

  • Global functions and Object properties are in PascalCase, where every word has it’s first letter capitalized and there are no spaces: TheQuickBrownFoxJumpsOverTheLazyDog

  • local variables, local functions, and Object functions are in camelCase, which is almost the same as pascal case except the first word is all lowercase. Most of the time, these will also only be a single word: theQuickBrownFoxJumpsOverTheLazyDog

  • Array indexes are usually snake_case (all lowercase, underscores instead of spaces), completelylowercase (all lowercase, no spaces), or Title Case (most words start with a capital, and uses spaces.)

    • (snake_case) the_quick_brown_fox_jumps_over_the_lazy_dog

    • (completelylowercase) thequickbrownfoxjumpsoverthelazydog (Try to keep these to only one or two words long)

    • (Title Case) The Quick Brown Fox jumps over the Lazy Dog

There are exceptions to these, but these are what you can generally expect to see used.

For further reading, see the related article linked at the bottom for a basic introduction to programming in gLua.

Я попытался исправить какой-то аддон Garry’s Mod, и вот что происходит. Я долго пытался исправить это, но я не лучший в кодировании Lua: /. Что не так с этим кодом? Я получаю такую ​​ошибку:

[ERROR] addons/garrys_bombs_5_base_528449144/lua/entities/gb5_shockwave_sound_lowsh.lua:80: bad argument #1 to 'SetPhysicsAttacker' (Entity expected, got nil)
  1. SetPhysicsAttacker - [C]:-1
   2. unknown - addons/garrys_bombs_5_base_528449144/lua/entities/gb5_shockwave_sound_lowsh.lua:80

И код довольно длинный. У меня все файлы работают нормально, но этот файл не работает

    AddCSLuaFile()

DEFINE_BASECLASS( "base_anim" )

if (SERVER) then
    util.AddNetworkString( "gb5_net_sound_lowsh" )
end

ENT.Spawnable                        =  false
ENT.AdminSpawnable                   =  false     

ENT.PrintName                        =  ""        
ENT.Author                           =  ""      
ENT.Contact                          =  ""      

ENT.GBOWNER                          =  nil            
ENT.MAX_RANGE                        = 0
ENT.SHOCKWAVE_INCREMENT              = 0
ENT.DELAY                            = 0
ENT.SOUND                            = ""

net.Receive( "gb5_net_sound_lowsh", function( len, pl )
    local sound = net.ReadString()
    LocalPlayer():EmitSound(sound)

end );

function ENT:Initialize()
     if (SERVER) then
         self.FILTER                           = {}
         self:SetModel("models/props_junk/watermelon01_chunk02c.mdl")
         self:SetSolid( SOLID_NONE )
         self:SetMoveType( MOVETYPE_NONE )
         self:SetUseType( ONOFF_USE ) 
         self.Bursts = 0
         self.CURRENTRANGE = 0
         self.GBOWNER = self:GetVar("GBOWNER")
         self.SOUND = self:GetVar("SOUND")


     end
end

function ENT:Think()        
     if (SERVER) then
     if not self:IsValid() then return end
     local pos = self:GetPos()
     self.CURRENTRANGE = self.CURRENTRANGE+(self.SHOCKWAVE_INCREMENT*10)
     if(GetConVar("gb5_realistic_sound"):GetInt() >= 1) then
         for k, v in pairs(ents.FindInSphere(pos,self.CURRENTRANGE)) do
             if v:IsPlayer() then
                 if not (table.HasValue(self.FILTER,v)) then
                    net.Start("gb5_net_sound_lowsh")
                        net.WriteString(self.SOUND)
                    net.Send(v)
                    v:SetNWString("sound", self.SOUND)
                    if self:GetVar("Shocktime") == nil then
                        self.shocktime = 1
                    else
                        self.shocktime = self:GetVar("Shocktime")
                    end
                    if GetConVar("gb5_sound_shake"):GetInt()== 1 then
                        util.ScreenShake( v:GetPos(), 5555, 555, self.shocktime, 500 )
                    end
                    table.insert(self.FILTER, v)

                 end
             end
         end
     else
        if self:GetVar("Shocktime") == nil then
            self.shocktime = 1
        else
            self.shocktime = self:GetVar("Shocktime")
        end
        local ent = ents.Create("gb5_shockwave_sound_instant")
        ent:SetPos( pos ) 
        ent:Spawn()
        ent:Activate()
        ent:SetPhysicsAttacker(ply)
        ent:SetVar("GBOWNER", self.GBOWNER)
        ent:SetVar("MAX_RANGE",50000)
        ent:SetVar("DELAY",0.01)
        ent:SetVar("Shocktime",self.shocktime)
        ent:SetVar("SOUND", self:GetVar("SOUND"))
        self:Remove()
     end
     self.Bursts = self.Bursts + 1
     if (self.CURRENTRANGE >= self.MAX_RANGE) then
         self:Remove()
     end
     self:NextThink(CurTime() + (self.DELAY*10))
     return true
     end
end
function ENT:OnRemove()
    if SERVER then
        if self.FILTER==nil then return end
        for k, v in pairs(self.FILTER) do
            if not v:IsValid() then return end
            v:SetNWBool("waiting", true)
        end
    end
end
function ENT:Draw()
     return false
end

Есть ли шанс, что кто-нибудь исправит это для меня? Или даже просто сказать мне, что случилось? Мне будет приятно. При необходимости могу отправить все файлы. Ну … Это не мой аддон, но я пытаюсь исправить уже существующий. Кто-то тоже пытался исправить, но он этого не сделал (на самом деле сломал еще больше).

1 ответ

Лучший ответ

Что означает ошибка

  • Внутри своей функции ENT:Think() вы вызываете ent:SetPhysicsAttacker(ply)
  • ply нигде внутри этой функции не определен, поэтому равен nil (Entity expected, got nil)

Как это исправить

Если ни один игрок не несет ответственности за ущерб, причиненный этой сущностью, удалите строку ent:SetPhysicsAttacker(ply).

В противном случае назначьте владельца сущности в момент создания, используя SetOwner.
Это позволит вам использовать self: GetOwner () внутри вашего {{X0} } крюк

Пример

hook.Add("PlayerSay", "SpawnEntity", function(ply, text)

    if string.lower(text) == "!spawnentity" then
        -- Create your entity
        local myEntity = ents.Create("gb5_shockwave_sound_lowsh")
        myEntity:SetPos(ply:GetPos())
        myEntity:SetAngles(ply:GetAngles())
        myEntity:Spawn()

        -- Sets the owner to the player that typed the command
        myEntity:SetOwner(ply)

        return ""
    end

end)


-- Inside your entity code
function ENT:Think()
    print("My owner is: " .. tostring(self:GetOwner()))

    -- ...

    ent:SetPhysicsAttacker(self:GetOwner())
end


2

Badger
28 Май 2020 в 10:45

What Are Lua Errors?

A Lua error is caused when the code that is being ran is improper. There are many reasons for why a Lua error might occur, but understanding what a Lua error is and how to read it is an important skill that any developer needs to have.

Effects of Errors on Your Scripts

An error will halt your script’s execution when it happens. That means that when an error is thrown, some elements of your script might break entirely. For example, if your gamemode has a syntax error which prevents init.lua from executing, your entire gamemode will break.

Lua Error Format

The first line of the Lua error contains 3 important pieces of information:

  • The path to the file that is causing the error
  • The line that is causing the error
  • The error itself

Here is an example of a code that will cause a Lua error:

local text = «Hello World»
Print( text )

The code will produce the following error:

[ERROR]addons/my_addon/lua/autorun/server/sv_my_addon_autorun.lua:2: attempt to call global ‘Print’ (a nil value)
1. unknown addons/my_addon/lua/autorun/server/sv_my_addon_autorun.lua:2

That is because Print is not an existing function (print, however, does exist).

The first line includes the path to the file that is causing the error — addons/my_addon/lua/autorun/server/sv_my_addon_autorun.lua

Afterwards, the line that’s producing the error — sv_my_addon_autorun.lua:2 (Line 2)

Lastly, the error itself — attempt to call global ‘Print’ (a nil value)

Below the error, we have the trace of the function. Simplified — If the error is inside a function/chunk of code that is called from somewhere else, it will state where the code is called from.

If the error happens serverside, the text color will be blue. If it happened clientside, it will be yellow. If it’s menu code, it will be green (not a typical scenario). Messages which look like errors but are colored differently, such as red or white, are not Lua errors but rather engine errors.

Printing Your Own

If you want to print your own error messages, there are three functions to do it:

  • error will print your message, halt execution, and print the stack. Normal error behavior.
  • ErrorNoHalt will print the file/line number and your message without halting the script. Useful for warning messages.
  • assert will check to make sure that something is true. If it’s not, it will print your message and halt just like error does.

Common Errors

Attempt to call global ‘?’ a nil value

Description: You tried to call a function that doesn’t exist.

Possible causes:

  • Your function might be defined in another Lua state. (e.g Calling a function on the client that only exists on the * server.)
  • You’re using a metafunction on the wrong kind of object. (e.g. Calling :SteamID() on a Vector)
  • The function you’re calling has an error in it which means it is not defined.
  • You’ve misspelled the name of the function.

Ways to fix:

  • Make sure the function exists
  • Make sure your function is defined in the correct realm
  • Check your function calls for spelling errors

Attempt to perform arithmetic on global ‘?’ (a nil value)

Description: You tried to perform arithmetic (+, -, *, /) on a global variable that is not defined.

Possible causes:

  • You tried to use a local variable that was defined later in the code
  • You’ve misspelled the name of the global variable

Ways to fix:

  • Make sure you define local variables before calling them in the code
  • Check for spelling errors

Attempt to perform arithmetic on ‘?’ (a type value)

Description: You tried to perform arithmetic (+, -, *, /) on a variable that cannot perform arithmetic. (e.g. 2 + «some string»)

Attempt to index global ‘varname’ (a nil value)

Description: You tried to index an undefined variable (e.g. print( variable.index ) where variable is undefined)

Possible causes:

  • The variable is defined in a different realm
  • The variable is local and defined later in the code
  • You’ve misspelled the name of the variable

Ways to fix:

  • Make sure the variable is only accessed in the realm it was defined in
  • If the variable is local, define it before accessing it

Malformed number near ‘number’

Description: There is a malformed number in the code (e.g. 1.2.3, 2f)

Possible causes:

  • An IP address was written as a number instead of a string
  • Incorrect writing of multiplication of a number and a variable
  • Trying to concatenate a number to a string without a space between the number and the operator.

Ways to fix:

  • Store IP addresses as a string
  • Multiply variables with numbers by using the ***** operator
  • Put a space between the concat (..) operator and the number.

Unexpected symbol near ‘symbol’

Description: You typed a symbol in the code that Lua didn’t know how to interpret.

Possible causes:

  • Incorrect syntax (e.g. Forgot to write «then» after an if statement)
  • Not closing brackets and parentheses at the correct locations

Ways to fix:

  • Make sure there are no mistypes in the code
  • Close brackets and parentheses correctly (See: Code Indentation)

‘symbol1’ expected near ‘symbol2’

Description: Lua expected symbol1 instead of symbol2.
When ‘symbol2’ is <eof>, Lua expected a symbol before the end of the file

Possible causes:

  • Not closing all brackets, parentheses or functions before the end of the file
  • Having too many end statements
  • Wrong operator calling (e.g. «==» instead of «=»)
  • Missing comma after table item.

Ways to fix:

  • Close brackets and parentheses correctly (See: Code Indentation)
  • Use the correct operators
  • Add a comma after a table item

Couldn’t include file ‘file’ — File not found (<nowhere>)

Description: The file system tried to include a file that either doesn’t exist or was added while the server was live.
This error can also be a AddCSLuaFile error.

Possible causes:

  • Attempting to include / AddCSLuaFile a file that doesn’t exist or is empty
  • Creating a file while the server is still live

Ways to fix:

  • Add the non-existent file, make sure the file isn’t empty
  • Restart the server

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Labels

Crash

The issue is a «random» runtime crash.

Comments

@IanTheMemeMan

So, this all started yesterday while I was playing on a sandbox server, when out of the blue, my GMod system completely crashed without even giving me a white screen, I relaunched GMod to face a problem. Every single time I loaded into a server, it would download all the mods and the go to the «Starting Lua» page, then would freeze for about 2 seconds, then crash. I looked at a whole BUNCH of YouTube, and forums to find nothing would work. I have no idea what’s going on, and I just want to play GMod again…
3a47abe8-37f3-41ba-b1a0-6e8707961bd1.txt

Edit: Yes, the game starts completely fine, loads all my mods, and is stable, except of course, when I go into a server.

Edit 2: If you need more crash logs, I can try and find another.

@IanTheMemeMan

Regarding above, to make the crash «crash», you have to pick any server, even singleplayer, launch it, wait for everything to download, then wait for the «Starting Lua» page to pop up, then boom, it freezes, and then fatally crashes.

@robotboy655

You will need to send the .dmp files not the .txt one.

@IanTheMemeMan

«This type of file is not supported»

@robotboy655

@IanTheMemeMan

Alright, it’s done. Do you want me to email you as well?

@MagentaIris

This issue still persists with the new update (Not just on 64 bit, but the normal branch too), Loading specific maps just outright CTD’s the game, namely Minerva, metastasis_1.bsp to be precise.

Was stable a while back but not anymore, Here’s a mdmp, just rename the format. I managed to fix a couple of these issues by using an lump editor and removing all the dynamic props and ropes, but even then it still sometimes does itself in.

Not my MDMP by the way, courtesy of a friend.

hl2_200623_crash_2020_6_25T22_45_44C0.txt

EDIT:

It seems the crash is being caused by prop_* class type entities, I’m not exactly sure why, but removing all of the prop_static/dynamic/physics/overrides with the lump editor seems to stop the map from crashing, Hope this helps.

@MagentaIris

Canals_13 is crashing due to the new update too.

Oh hey and town_01, alongside all of Mission improbable.

@robotboy655

None of those HL2 maps crash without any addons.

@robotboy655

The original crash here is the netchannel somehow becoming nullptr.

@MagentaIris Yours is a vphysics crash. Perhaps you have addons overriding default models or something?

@MagentaIris

Having a Fast Headcrab ragdoll on any map, and having the Default HL2 fast headcrab model extracted from base HL2 in your gmod causes it to crash.

Now that’s pretty fucked up, i’ll look into fixing it personally. (This is a server side ragdoll by the way, Client ragdolls are fine, Just mentioning the default models gave me the idea as well so cheers for that one.)

EDIT:

I have fixed the issue manually, I’ll continue to see if anything else crops up however.

@robotboy655

Thanks, I will see if this is fixable or if we gotta rollback r_flushlod and look for a different fix for vertex CRC error

@MagentaIris

Mayhaps, I tried a couple of recompiles of the normal headcrab with the original qc’s and source animations, it seems the Ragdoll animation when playing it in HLMV sometimes just crashes, and of course, if this happens in HLMV, it crashes gmod if you spawn the ragdoll server side but not client side.

Pretty weird.

@robotboy655

So extracting ragdolls from the vpk did not cause any crashes for me, and at first you were claiming it’s the physics props that doing the crash, now its ragdolls, the dump you linked shows a vphysics crash, but now you claim it happens in HLMV which doesn’t even use vphysics, I don’t know what to believe anymore. You are also seemingly the only person having these issues.

@MagentaIris

Yeah i couldn’t lock it down to the exact entity, but it was 100% the fast headcrab being a server side ragdoll, Extracting the model from the VPK may have freaked out, After re-extracting it safely the issue isn’t there anymore.

Pretty sure that issue can just be ignored now.

Labels

Crash

The issue is a «random» runtime crash.

СПОСОБ №1 НЕОБЯЗАТЕЛЕН К ПРИМЕНЕНИЮ, МОЖЕТЕ ПЕРЕХОДИТЬ К СПОСОБУ №2 — «АКТИВАЦИЯ БЕТА-ВЕРСИИ».

Попробуем разобрать решения данной ошибки.

Вам нужно как минимум 2-3 ГБ свободной оперативной памяти, чтобы играть в игру, или как минимум 4-8 ГБ оперативной памяти, установленной, как указано в разделах системных требований на странице Steam Store для Garry’s Mod.
Если вы уверены, что ваше количество оперативной памяти, точно удовлетворяет требованиям игры, попробуйте это

Параметры запуска

1. В Steam, нажмите правой кнопкой мыши по игре Garry’s mod, дальше нажмите Свойства

steam_qzVRv5qOTd.png

2. Найдите поле Параметры запуска

1610871169948.png

Выберите параметры, которые подходят вам:

Если у вас, 2ГБ оперативной памяти

-heapsize 2097152

Если у вас, 4ГБ оперативной памяти

-heapsize 4194304

Если у вас, 6ГБ оперативной памяти

-heapsize 6291456

Если у вас, 8ГБ оперативной памяти (и более)

-heapsize 8388608

Бета-версии

1. В Steam, нажмите правой кнопкой мыши по игре Garry’s mod, дальше нажмите Свойства

steam_qzVRv5qOTd.png

2. Перейдите в раздел Бета-версии и выберите x86-64 — Chromium + 64-bit binaries

1610872320489.png

Отписаться от лишних аддонов

Если ошибка продолжает появляться, попробуйте:

1. Зайти в игру, далее Дополнения

1623499713514.png

2. Гаечный ключ в правом нижнем углу, Удалить всё

1623499836561.png

1623499980058.png

Вообщем играю на проекте ДаркРП и там есть меню организаций. Подходишь к NPC, кликаешь на него и открывается меню создания своей банды, организации. По разному называют. Но вместо этого у меня. Там где должно быть описание, что можно сделать в этом меню написано «label» на кнопке создать группировку «label» и покинуть группировку «label» Так только у меня. У остальных все норм. Я уже удалял ГМод и скачивал заного. Я даже стим полоностью снес. Не помогло. Есть предположения что это связано с тем, что я тоже создавал свой сервер, и там был этот аддон. Но все папки с сервером удалены. При открытии меню в консоли пишит это:

[ERROR] addons/module_org/lua/entities/ent_npcorg/cl_init.lua:75: attempt to perform arithmetic on a nil value

1. func — addons/module_org/lua/entities/ent_npcorg/cl_init.lua:75

2. unknown — lua/includes/extensions/net.lua:32

Кто знает как лечить?

Понравилась статья? Поделить с друзьями:
  • Вертикальные полосы на телевизоре samsung как исправить
  • Как найти арабские буквы
  • Брандмауэр в браузере как найти
  • Как найти центр галактики млечный путь
  • Как можно найти мультик мимимишки