I guess this will be a multipart answer…
Lexical scoping
The typical example:
do
local foo = 20
function bar() return foo end
end
print(tostring(foo)) -- prints "nil", foo is out of scope
print(bar()) -- prints 20, bar still knows about foo
In your case it’s the other way around
function bar() return foo end
-- foo does not exist as a local yet, so Lua tries accessing a global foo
do
local foo = 20
print(tostring(bar())) -- prints nil because bar doesn't know foo
end -- forget about local foo
foo = 30 -- global
local foo = 20
print(bar()) -- prints 30, because it doesn't know the local foo
Your problem
That’s basically what happens in your example. You declare the player
variable after the function, so by the time the function is declared, no local variable player
exists, thus it compiles a function that accesses a global player
variable. Since that global does not exist, it’s treated as nil, and when you attempt to index it Lua complains.
Fixes
- Either remove the
local
and makeplayer
a global variable (easy to do, but global variables are the devil and you shouldn’t use them lightly) - Or declare it with just
local player
above the function, then you can assign a value to it further down.
Note that the function will save the variable, not its value when the function is created. Here’s an example of what I mean:
local foo = 20
function bar() return foo end
foo = 30
print(bar()) -- prints 30, not 20
There’s more to it than that, but this is about all you need to know to solve your problem. If you want to learn more, just google for lexical scoping in lua and you’ll surely find some better explanations than I could ever give you.
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
script_name('FastMakeGun')
script_author('Endo')
script_description('Fast create a gun')
require "lib.moonloader"
local main_color = 0x06DFFF
local id = sampGetCurrentDialogId()
function main()
if not isSampLoaded() or not isSampfuncsLoaded() then return end
while not isSampAvailable() do wait(100) end
sampAddChatMessage("Script FastMakeGun for Grand RP loaded", main_color)
sampAddChatMessage(id)
sampRegisterChatCommand("gd", cmd_gd); wait(-1)
sampRegisterChatCommand("gm", cmd_gm)
sampRegisterChatCommand("ogd", cmd_ogd)
sampRegisterChatCommand("ogm", cmd_ogm)
thread = lua_thread.create_suspended(All_Thread)
end
function cmd_gd(arg) --Дигл
thread:run("gd", arg )
--if arg == "" then
--sampAddChatMessage("Введите количество патронов", 0xFFFFFF)
-- else
--sampSendChat("/makegun")
--sampSendDialogResponse(888, 1, 1, '')
--sampSendDialogResponse(889, 1, '', arg)
end
function cmd_gm(arg) --М4
if arg == "" then
sampAddChatMessage("Введите количество патронов", 0xFFFFFF)
else
sampSendChat("/makegun")
sampSendDialogResponse(888, 1, 4, _)
--sampSendDialogResponse(889, _, _, arg)
end
end
function All_Thread(option, arg)
if option == "gd" then
if arg == "" then
sampAddChatMessage("Введите количество патронов", 0xFFFFFF)
else
sampSendChat("/makegun")
sampSendDialogResponse(888, 1, 1, '')
wait(250)
sampSendDialogResponse(889, '', '', arg)
wait(500)
SampCloseCurrentDialogWithButton(1)
end
end
end
--function cmd_ogd(arg) -- /o Дигл
--if arg == "" then
--sampAddChatMessage("Введите количество патронов", 0xFFFFFF)
--else
--sampSendChat("/makegun")
--sampSendDialogResponse(888, 1, 4, _)
--sampSendDialogResponse(889, _, _, arg)
--end
--end
--function cmd_ogm(arg) -- /o М4
--if arg == "" then
--sampAddChatMessage("Введите количество патронов", 0xFFFFFF)
--else
--sampSendChat("/makegun")
--sampSendDialogResponse(888, 1, 4, _)
--sampSendDialogResponse(889, _, _, arg)
--end
--end
frilovsky 0 / 0 / 0 Регистрация: 05.10.2020 Сообщений: 23 |
||||
1 |
||||
30.03.2021, 23:17. Показов 12692. Ответов 7 Метки lua (Все метки)
Скрипт работает стабильно. Но через какое либо время вылетает с такой ошибкой: attempt to index global ‘file’ (a nil value) Я ещё понимаю он сразу вылетал, но он примерно 1-2 минуты работает нормально а потом вылет. Подскажите как исправить.
0 |
965 / 1665 / 171 Регистрация: 07.05.2013 Сообщений: 3,596 Записей в блоге: 12 |
|
30.03.2021, 23:24 |
2 |
file = io.open(getGameDirectory()..»//moonloader//log.txt», «a») Зачем открывать файл дважды ?
2 |
0 / 0 / 0 Регистрация: 05.10.2020 Сообщений: 23 |
|
31.03.2021, 08:26 [ТС] |
3 |
Случайно второй раз написал. Так то его нет
0 |
965 / 1665 / 171 Регистрация: 07.05.2013 Сообщений: 3,596 Записей в блоге: 12 |
|
31.03.2021, 09:08 |
4 |
Попробуйте заменить на: Код file = io.open(getGameDirectory().."/moonloader/log.txt", "a")
1 |
0 / 0 / 0 Регистрация: 05.10.2020 Сообщений: 23 |
|
31.03.2021, 12:30 [ТС] |
5 |
Не помогло attempt to index global ‘file’ (a nil value)
0 |
Curry Модератор 4909 / 3143 / 498 Регистрация: 01.06.2013 Сообщений: 6,567 Записей в блоге: 9 |
||||
31.03.2021, 20:43 |
6 |
|||
Скрипт работает стабильно. Однако, это же не весь скрипт. Потому что
через какое либо время вылетает с такой ошибкой: attempt to index global ‘file’ (a nil value) То есть, либо в скрипте этот файл открывается в цикле, то ли сам скрипт что то вызывает много раз.
0 |
frilovsky 0 / 0 / 0 Регистрация: 05.10.2020 Сообщений: 23 |
||||
31.03.2021, 21:33 [ТС] |
7 |
|||
Вы правы на счет цикла. Работает в цикле раз в 5 сек заполняет txt.
0 |
Curry Модератор 4909 / 3143 / 498 Регистрация: 01.06.2013 Сообщений: 6,567 Записей в блоге: 9 |
||||
31.03.2021, 21:46 |
8 |
|||
Решение
Используя ваш код, я переделал под себя Зачем же, когда возникает ошибка, снова пытаться открывать файл. Посмотрите что у меня после if ferr ~= nil then, и что у вас. Добавлено через 57 секунд Добавлено через 1 минуту
0 |
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,