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
When executing this code I get an error «attempt to call global ‘forId’ (a nil value)”
function execute(args)
local itemid = 526
local bone = forId(itemid) -- this is where the error occurs
end
function forId(bid)
local xp = 0.0
if bid == 526 or bid == 528 or bid == 2530 or bid == 2859 then
xp = 4.5
elseif bid == 3179 or bid == 3180 or bid == 3183 or bid == 3185 then
xp = 5.0
elseif bid == 530 then
xp = 53
elseif bid == 532 or bid == 3125 then
xp = 15
elseif bid == 4812 then
xp = 22.5
elseif bid == 7839 then
xp = 30
elseif bid == 6812 then
xp = 50
elseif bid == 536 then
xp = 72
end
local bone = Bone:new(bid, xp)
return bone
end
Bone = class(function(b, id, xp)
b.id = id
b.xp = xp
end)
Can anyone tell me why?
Doug Currie
40.3k1 gold badge95 silver badges119 bronze badges
asked Apr 17, 2011 at 15:19
Lua processes and executes files line by line so the order you define them and use them can be important. In this case though it appears you aren’t providing all the code because it looks like you are defining forID
as a global but the error implies otherwise. You can simply try altering the order the functions are defined in to see if it works.
Bone = class(function(b, id, xp)
b.id = id
b.xp = xp
end)
function forId(bid)
local xp = 0.0
if bid == 526 or bid == 528 or bid == 2530 or bid == 2859 then
xp = 4.5
elseif bid == 3179 or bid == 3180 or bid == 3183 or bid == 3185 then
xp = 5.0
elseif bid == 530 then
xp = 53
elseif bid == 532 or bid == 3125 then
xp = 15
elseif bid == 4812 then
xp = 22.5
elseif bid == 7839 then
xp = 30
elseif bid == 6812 then
xp = 50
elseif bid == 536 then
xp = 72
end
local bone = Bone:new(bid, xp)
return bone
end
function execute(args)
local itemid = 526
local bone = forId(itemid) -- this is where the error occurs
end
But since you haven’t provided the full code this might just cause the error to shift elsewhere.
answered Apr 17, 2011 at 18:22
ArrowmasterArrowmaster
9,0732 gold badges28 silver badges25 bronze badges
try caching it as a local first, especially if your using module
:
local forId = forId //or _G.forId
local bone = forId(itemid)
answered Apr 17, 2011 at 16:03
NecrolisNecrolis
25.5k3 gold badges63 silver badges101 bronze badges
1
i think, you should include a library file at first, like i.e.
dofile(core.app_path() .. "\strategies\standard\include\helper.lua");
( the exact command can be found in the documentaries of your software. )
answered Jan 18, 2016 at 19:38
T.ToduaT.Todua
51.2k19 gold badges224 silver badges225 bronze badges
Главная » Основные форумы » Программирование на языке Lua
Страницы:
1
Serge
Сообщений: 10 |
#1 09.06.2022 14:55:30 Где ошибка? MyVar = foo(1,2)—>attempt to call a nil value (global ‘foo’) function foo(a,b) |
Nikolay
Сообщений: 698 |
#2 09.06.2022 14:57:46 В момент вызова foo она еще не определена. https://nick-nh.github.io/ |
Serge
Сообщений: 10 |
#3 09.06.2022 15:48:21
Благодарю) |
||
Владимир
Сообщений: 1588 |
#4 09.06.2022 16:16:52 Nikolay, Как это «в момент вызова foo она еще не определена»? У меня в скрипте первой функцией стоит main, а за ней ещё десятка два, обычно по алфавиту. Всегда все всё прекрасно видят. Да и Квик перед запуском делает что-то вроде компиляции кода. |
Serge
Сообщений: 10 |
#5 09.06.2022 17:12:44
Это зависит из какой области вызывается выражение Если вызов переменной (функции) происходит из main() а сама переменная объявлена за пределами main() (например в body() или во внешнем подключенном файле), то ошибки не будет, Но если объявление также как и вызов внутри main() то порядок имеет значение — сперва объявление, потом обращение. |
||
Serge
Сообщений: 10 |
#6 09.06.2022 17:18:56 например, так работает: function foo() а так — нет: function main() PrintDbgStr(tostring(foo()))—>attempt to call a nil value (global ‘foo’) function foo() end |
nikolz
Сообщений: 2510 |
#7 09.06.2022 18:20:16
Функция main — это дополнительный поток для скрипта и вызывается основным потоком квик после того как весь скрипт загружен, |
||
Владимир
Сообщений: 1588 |
#8 09.06.2022 19:10:00 Serge, При чём тут вооще «из какой области вызывается выражение»? Эта дура его НЕ ВИДИТ! Глобальные переменные у меня действительно объявлены до main, но, полагаю, и это не имеет значения (в смысле, НЕ ДОЛЖНО иметь значения). Я не помню, есть ли у меня неинициализированные глобальные переменные (скорее всего, нет), но, полаю, и это не должно иметь никакого значения — здесь переменные глобальные по умолчанию (что есть ещё один идиотизм языка). Я же говорил не о переменных, а о функциях, которые по определению «объявлены за пределами main». Чо ещё за «body» здесь нарисовалось? nikolz, Лапуль, мне
НАСРАТЬ на всю эту клиническую мутоту с потоками, которая вдарила в головожопы создателей этого, с позволения сказать, «языка». Я в своё время потратил две или три недели, чтобы гарантированно перенести все операции именно в поток main (три стека для этого пришлось завести!), и с тех пор горя не знаю. Так В ГРОБУ я видел такую «матчасть» — учите сами! |
Serge
Сообщений: 10 |
#9 09.06.2022 20:07:58
Вы интересовались откуда взялось «боди» — об этм можно узнать из первых страниц документации по Qlua https://euvgub.github.io/QLua_QUIK/index.html?page=1 в остальном, увы, не знаю как вам можно помочь… |
||
Владимир
Сообщений: 1588 |
#10 09.06.2022 20:20:55 Serge, Да плевать мне, откуда взялось «боди»! Для полноценного программирования на Lua это нафиг не нужно. А мне помогать не надо — мне помогли давно, в первые месяцы моего пребывания здесь. А теперь мой скрипт давно прекрасно работает и прекрасно зарабатывает. Я уже забыл, когда последний раз искал на свою жопу приключений и потому сроду не видывал диагностики, подобной той, которая вынесена в заголовок. |
Страницы:
1
Читают тему (гостей: 1)
bLib = {}
bLib['mimgui'], imgui = pcall(require, 'mimgui')
bLib['ffi'], ffi = pcall(require, 'ffi')
bLib['inicfg'], inicfg = pcall(require, 'inicfg')
bLib['encoding'], encoding = pcall(require, 'encoding')
bLib['fAwesome5'], fa = pcall(require, 'fAwesome5')
bLib['Events'], sampev = pcall(require, 'samp.events')
bLib['requests'], requests = pcall(require, 'requests')
bLib['Matrix3X3'], Matrix3X3 = pcall(require, 'matrix3x3')
bLib['Vector3D'], Vector3D = pcall(require, 'vector3d')
bLib['effil'], effil = pcall(require, 'effil')
bLib['Memory'], memory = pcall(require, 'memory')
bLib['bit'], bit = pcall(require, 'bit')
bLib['Copas'], copas = pcall(require, 'copas')
bLib['Http'], http = pcall(require, 'copas.http')
for lib, bool in pairs(bLib) do
if not bool then
ShowPlayerMessage('Библиотека ' .. lib .. ' не найдена. Запуск скрипта остановлен!', 0x2DF61C)
break
end
end
function ShowPlayerMessage(message, color)
sampAddChatMessage("[CheatHelper] {FFFFFF}" .. message, color or 0x2DF61C)
end
Attempt to call a nil value
Attempt to call a nil value
Description: calling a function that doesn’t exist
printtt(«abc») — printtt is not a function
test() — calling before it’s defined, same error
Unexpected symbol near ‘something’
Unexpected symbol near ‘something’
Description: an invalid character is placed next to a value/keyword/variable/function call
function abc()) end — unexpected symbol near ‘)’
a l= 15 — unexpected symbol near ‘l’
local a = 5] — unexpected symbol near ‘]’
Attempt to index global ‘variable’ (a nil value)
Attempt to index global ‘variable’ (a nil value)
Description: indexing via [key]
or .key
for a variable that doesn’t exist
abc.x = 5 — abc is nil, error
abc = {} — abc defined here
xyz[‘x’] = ‘abc’ — xyz is nil, error
Attempt to perform arithmetic on a nil value
Attempt to perform arithmetic on a nil value
Description: performing arithmetic (*, /, -, +, %, ^) on a nil value
print(xyz + 5) — error, xyz not defined
a = a + 5 — error, a not defined
Attempt to perform arithmetic on field ‘?’ (a nil value)
Attempt to perform arithmetic on field ‘?’ (a nil value)
Description: performing arithmetic (*, /, -, +, %, ^) on a nil value
Attempt to compare nil with <TYPE>
Attempt to compare nil with <TYPE>
Description: using a comparison operator (<, >, ~=, ==, >=, <=) in which one side is a nil value
print(x < y) — y is not defined
Malformed number near <NUMBER>
Malformed number near <NUMBER>
Description: the number has an invalid character next to it
print(12345aaa) — aaa makes it a malformed number
Unfinished capture | Malformed pattern
Unfinished capture | Malformed pattern
Description: the pattern is missing a closing )
, or a closing ]
print(string.match(‘ABC’, ‘(‘)) — unfinished capture
print(string.match(‘ABC’, ‘[‘)) — malformed pattern
When you get an error, Lua provides a stack trace showing you where it originates from, where the error occurs, the function calls that led to the error, and the line number of where it occurred.
A general error will look like this:
file_location:LINE NUMBER: error message
file_location:LINE NUMBER: in <local/function> ‘FUNC’
file_location:LINE NUMBER: in main chunk
C:Usersuserlua_file.lua:5: attempt to perform arithmetic on a nil value (field ‘x’)
C:Usersuserlua_file.lua:5: in local ‘c’
C:Usersuserlua_file.lua:7: in local ‘b’
C:Usersuserlua_file.lua:9: in function ‘a’
C:Usersuserlua_file.lua:12: in main chunk
The code that resulted in this error is:
Here you can see the line number 5
after the file location, which tells us where the exact line with the code that resulted in the error. The stack traceback shows the functions that were called that led up to that.
First, function a
is called at line 12, then function b
is called at line 9 inside of a
, then c
is called at line 7 inside of function b
, and finally at line 5, the error occurs inside of function c
.
A note to add is that comments can offset the line number and make it appear as the error is in a line that doesn’t exist or doesn’t look like an error,
ВНИМАНИЕ! КОММЕНТАРИИ ПЕРВОГО УРОВНЯ В ВОПРОСАХ УПОРЯДОЧИВАЮТСЯ ПО ЧИСЛУ ПЛЮСИКОВ, А НЕ ПО ВРЕМЕНИ ПУБЛИКАЦИИ.
local stopped = false
function OnStop()
stopped = true
return 2000
end
function main ()
local SecCode = «GZZ9»
local PriceRTSBuy = getParamEx(«SPBFUT», SecCode, «LAST»).param_value
local LimitOrderBuy = {
[«ACTION»] =«NEW_ORDER»,
[«ACCOUNT»] =«SPBFUT000ve»,
[«OPERATION»] =«B»,
[«CLASSCODE»] =«SPBFUT»,
[«SECCODE»] = SecCode,
[«PRICE»] = (PriceRTSBuy — 50),
[«QUANTITY»] = 1,
[«TRAND_ID»] = 228322,
}
local Err_Order=SendTransaction(LimitOrderBuy)
message («Err_Order»)
end
- 27 сентября 2019, 21:01
-
Ответить
Hired, тут куча ошибок!
1) функция message должна иметь формат message(«Текст сообщения»,1)
2) в PriceRTSBuy Вы получаете строку, а вычитаете число. Может прокатить, а может быть баг. Нужно tostring(tonumber(PriceRTSBuy)-50)
3)[«QUANTITY»] = «1», — в ключ количество нужно передавать строку
4) Номер транзакции тоже нужно взять в кавычки, т.е. дать строку
- 27 сентября 2019, 21:14
-
Ответить
pessimist, не помогло. указывает на ошибку в строке local Err_Order=SendTransaction(LimitOrderBuy). А если удалить её и message, то после запуска ничего не происходит и никакой реакции нет
- 27 сентября 2019, 21:20
-
Ответить
Hired, а какую ошибку указывает, можно скрин?
- 27 сентября 2019, 21:22
-
Ответить
pessimist, [«QUANTITY»] = tostring(1) тоже не помогает.
ошибка: …script qluaza9vka vistavlenie.lua:20: attempt to call global ‘SendTransaction’ (a nil value), 20я строка это local Err_Order=SendTransaction(LimitOrderBuy)
- 27 сентября 2019, 21:24
-
Ответить
Hired, регистр имеет важное значение, Вы неправильно написали функцию :
sendTransaction
Первая буква должна быть маленькой
- 27 сентября 2019, 21:26
-
Ответить
pessimist, хаха вот фэйл! спасибо! видимо на сегодня пора заканчивать
- 27 сентября 2019, 21:29
-
Ответить
Hired,
всегда — пожалуйста!
- 27 сентября 2019, 21:29
-
Ответить
local stopped = false
function OnStop()
stopped = true
return 2000
end
function main ()
local SecCode = «GZZ9»
local PriceRTSBuy = getParamEx(«SPBFUT», SecCode, «LAST»).param_value
local LimitOrderBuy = {
[«ACTION»] =«NEW_ORDER»,
[«ACCOUNT»] =«SPBFUT000ve»,
[«OPERATION»] =«B»,
[«CLASSCODE»] =«SPBFUT»,
[«SECCODE»] = SecCode,
[«PRICE»] = (PriceRTSBuy — 50),
[«QUANTITY»] = 1,
[«TRAND_ID»] = 228322,
}
local Err_Order=SendTransaction(LimitOrderBuy)
message («Err_Order»)
end
- 27 сентября 2019, 21:01
-
Ответить
Hired, тут куча ошибок!
1) функция message должна иметь формат message(«Текст сообщения»,1)
2) в PriceRTSBuy Вы получаете строку, а вычитаете число. Может прокатить, а может быть баг. Нужно tostring(tonumber(PriceRTSBuy)-50)
3)[«QUANTITY»] = «1», — в ключ количество нужно передавать строку
4) Номер транзакции тоже нужно взять в кавычки, т.е. дать строку
- 27 сентября 2019, 21:14
-
Ответить
pessimist, не помогло. указывает на ошибку в строке local Err_Order=SendTransaction(LimitOrderBuy). А если удалить её и message, то после запуска ничего не происходит и никакой реакции нет
- 27 сентября 2019, 21:20
-
Ответить
Hired, а какую ошибку указывает, можно скрин?
- 27 сентября 2019, 21:22
-
Ответить
pessimist, [«QUANTITY»] = tostring(1) тоже не помогает.
ошибка: …script qluaza9vka vistavlenie.lua:20: attempt to call global ‘SendTransaction’ (a nil value), 20я строка это local Err_Order=SendTransaction(LimitOrderBuy)
- 27 сентября 2019, 21:24
-
Ответить
Hired, регистр имеет важное значение, Вы неправильно написали функцию :
sendTransaction
Первая буква должна быть маленькой
- 27 сентября 2019, 21:26
-
Ответить
pessimist, хаха вот фэйл! спасибо! видимо на сегодня пора заканчивать
- 27 сентября 2019, 21:29
-
Ответить
Hired,
всегда — пожалуйста!
- 27 сентября 2019, 21:29
-
Ответить
Только зарегистрированные и авторизованные пользователи могут оставлять ответы.
Залогиниться
Зарегистрироваться
Community Forum
Error LUA attempt to call global
Forum Overview >> Scripting
Category | Scripting |
Created | 24.12.2018 11:10 |
Baptiste Brossette (Monsieur_Bab) | 24.12.2018 11:10 |
---|---|
Hi, I have an issue in my first script (i’m beginner, sorry if this error is basic ^^) I want to write a code that display the current date in the developper console in fs19. Here is (a part of) my code : When I press the Equals key, an error occurs : Do you know where is my error? Thanks and Merry Christmas ! |
Ben Sollis (sollisb) | 24.12.2018 13:49 |
---|---|
nil value means that getCurrentDate is returning nothing.. I have no idea how tro get the date in FS. In typical LUA it’s something like os.Date or os.Time..
Also, don’t create variables for nothing.. You could just have easily used print(getCurrentDate) and saved time and memory. Not an issue in something small, but all the bad parts add up.. Bear it in mind You might want to visit https://github.com/scfmod/fs19_lua Thats chap has done excellent work for us. |
Bilbo Beutlin (BBeutlin) | 24.12.2018 14:33 |
---|---|
The error message «attempt to call global ‘getCurrentDate’ (a nil value)» means «getCurrentDate» is unknown as global variable. It is component of the localization «l18N» (see https://gdn.giants-software.com/documentation_scripting_fs19.php?version=script&category=83&class=7046) and must be called local currentDate = l18N:getCurrentDate() print(currentDate) |
Baptiste Brossette (Monsieur_Bab) | 25.12.2018 12:05 |
---|---|
Thanks you for your responses! All works well. Thanks for the lua doc on github |
Note: Log in to post. Create a new account here.