Доброго времени суток.
Уже достаточно долгое время мучаюсь с небольшим куском кода. После изучения всяческих способов реализации ООП в луа, решил попробовать сделать его своими силами. И, фактически, все работает, но не так, как мне хотелось бы.
Тут мы раскладываем объекты по какой-то карте, при этом, каждый объект создается для каждой ячейки и индивидуален.
function map_lay()
for y = 1, map_w do
for x = 1, map_h do
local f = NEW(floor) --Создаем новый объект.
f.x = x * f.w -- Вот тут выдает ошибку attempt to index local "f" (nil value)
f.y = y * f.h
map[x][y] = f
end
end
end
Вот тут и сам процесс создания.
function NEW(p) --Определяем тип и сортируем в таблицы для удобной работы с объектами. Ну и да, сама функция создает объект.
o = {}
o.Parent = p.name --На самом деле, я начал проверку отсюда сразу, как только выдало ошибку. Ребенок и правда рождается мертвым, а именно - nil
--Если у объекта есть родитель, передаем ребенка по назначению при помощи метатаблицы.
if o.Parent == nil then
do end
else
function o.Parent:newCreate(o)
setmetatable(o, {__index = o.Parent})
end
end
if o.Type == "tile" then
table.insert(Turfs, o)
o.id = math.random(1, 999999) -- На скорую руку для проверки количества объектов в действительности, а не просто #Turfs, где все объекты вполне могут быть одним единственным.
end
created(o) -- Если создан, выполняется код из функции. Например, отрисовка или логирование.
return o
end end
Сами объекты, чьи, грубо говоря, шаблоны используются в массовом создании.
tile = {
name = tile,
w = 32,
h = 32,
x = 0,
y = 0,
Type = "tile",
Parent,
id
}
--Интересный момент. Если это объявить вместо local f = NEW(floor), получается ровно то, что я и хотел, и все работает (То самое "фактически"). Ну, точнее, если еще и объявлять локально.
floor = {
name = floor,
w = 32,
h = 32,
x = 0,
y = 0,
Type = "tile",
Parent = tile
}
В общем, никак не могу понять, что я делаю не так. Испробовал различные варианты, пытался переписывать, но в итоге nil и все тут. Словно функция NEW() вовсе и не получает никаких таблиц. Вполне может быть, что косяк в какой-нибудь мелочи. У меня так часто бывает.
Пожалуйста, объясните где ошибка и, желательно, почему так происходит? А то который час сижу и пытаюсь понять в чем суть. Уже аж мозги сварились.
Извиняюсь, если подобные вопросы были. Искал, но что-то не нашел.
Skip to content
This repository has been archived by the owner on Oct 15, 2019. It is now read-only.
-
Notifications
-
Fork
43
Comments
Error:[string «— Hello!
…»]:12: .lua/helpers.lua:542: attempt to index a nil value (field ‘directories’)
Do you have access to the internet while using the table?
…
Did you edited «config.ini»?
Anyway, delete it. It’s located in ‘C:UsersUSERNAMEDocumentsFIFA 19Cheat Tabledata’
Главная » Основные форумы » Программирование на языке Lua
Страницы:
1
Алекс Лепс
Сообщений: 5 |
#1 23.08.2016 18:13:47 Знаю что возможно это уже обсуждалось, но я очень плохо знаю языки программирования. Этот код работает если в стакане есть все строки, если нет то выдает ошибку nil. Стакан 20 на 20, |
Николай Камынин
Сообщений: 2514 |
#2 23.08.2016 18:48:03 mm=getQuoteLevel2(«SPBFUT»,»NKZ6″) |
Алекс Лепс
Сообщений: 5 |
#3 23.08.2016 19:23:20 Спасибо за ответ, но это для меня ничего не меняет, возможно вы что то не дописали или я просто не понимаю что вы хотите сказать) |
Николай Камынин
Сообщений: 2514 |
#4 23.08.2016 19:50:38 mm=getQuoteLevel2(«SPBFUT»,»NKZ6″) |
Алекс Лепс
Сообщений: 5 |
#5 23.08.2016 20:04:54 Спасибо за вашу помощь, я попробую переделать. |
Алекс Лепс
Сообщений: 5 |
#6 24.08.2016 11:51:20 на самом деле то ли я не понимаю то ли меня, я упростил пример function main() в этом примере программа обращается к 10 строке стакана и запрашивает количество, но так как стакан полупустой |
Sergey Denegin
Сообщений: 450 |
#7 24.08.2016 12:04:35 для проверки значения, можно использовать условие: if mm.bid[mm.bid_count-10] ~= nil then у тебя ошибка возникает, т.к. сам элемент mm.bid[mm.bid_count-10] равен nil, а ты пытаешься взять из него поле quantity Напиши, если помог |
Алекс Лепс
Сообщений: 5 |
#8 24.08.2016 12:17:04 Да, спасибо. Таким образом программа выполняется без ошибки. Кое что проясняется. Теперь попробую воткнуть это в свой код. Спасибо! |
Sergey Denegin
Сообщений: 450 |
#9 24.08.2016 12:20:04 всегда пожалуйста |
Николай Камынин
Сообщений: 2514 |
#10 24.08.2016 15:59:18
В примере написано две проверки |
||
Вячеслав +
Сообщений: 95 |
#11 27.08.2016 04:30:37 Алекс Лепс
, |
rbatar
Сообщений: 13 |
#12 08.09.2016 17:51:59 Помогите избавиться от ошибки nil. 78 if getItem(«futures_client_limits»,0).cbplused ~= nil then |
rbatar
Сообщений: 13 |
#13 08.09.2016 18:28:15 Реализовал пока так, но хотелось бы не использовать массив var |
swerg
Сообщений: 1181 миру мир! |
#14 08.09.2016 19:15:41
Сначала следует проверить, что вот эта часть не равна nil В следующем посте вы это, собственно, и сделали, правда несколько экзотическим образом. if getItem(«futures_client_limits»,0) ~= nil then или |
||
rbatar
Сообщений: 13 |
#15 08.09.2016 19:22:08 Спасибо за помощь. Ваш 1-й вариант то, что надо
|
||
Николай Камынин
Сообщений: 2514 |
#16 08.09.2016 20:23:21 а так: |
rbatar
Сообщений: 13 |
#17 08.09.2016 20:39:22
Да, так тоже очень неплохо. Спасибо, Николай, возьму на вооружение. |
||
Вячеслав
Сообщений: 3 |
#18 14.04.2017 22:23:46 Доброго дня! Уважаемые мастера программирования, у меня (как и у Алекс Лепс) Квиком выдается ошибка «attempt to index field ‘?’ (a nil value)» Я подозреваю что неправильно написал перебор элементов массива в коде, для которых потом выполняется функция. Вот кусок кода: p_seccode={«PPPP»,»YYYY»,»AAAA»,»GGGG»,»NNNN»,»RRRR»,»HHHH»} — это массив бумаг for i,v in pairs(p_seccode) do function robot() for i,v in pairs(chart) do Я не знаток языка Lua, поэтому буду очень благодарен помощи! Спасибо! |
Sergey Gorokhov
Сообщений: 3874 |
#19 14.04.2017 22:38:46 Здравствуйте, Если нужен дальнейший анализ, приведите полный код и укажите строку на которой возникает ошибка (написано в тексте ошибки) |
Вячеслав
Сообщений: 3 |
#20 14.04.2017 23:46:37 Сергей, пока не уловил как надо. Строчка, которую Вы написали, полностью совпадает с моей кроме кавычек. Наверное что то не вижу. Вот более полный код: —Параметры: —Служебные переменные function main() function to_log(a_msg) for i,v in pairs(p_seccode) do function robot() for i,v in pairs(chart) do if (in_trade) then if not(in_trade) then if (in_trade) then if not (in_trade) then end end |
Sergey Gorokhov
Сообщений: 3874 |
#21 14.04.2017 23:53:51
Вот именно. кавычки — это строковое значение, а без кавычек это переменная которая меняет значения. |
||
Вячеслав
Сообщений: 3 |
#22 15.04.2017 13:30:28 Точно, я же говорю в упор не вижу чего то)) Сергей спасибо большое, буду исправлять. |
Страницы:
1
Читают тему (гостей: 1)
frilovsky 0 / 0 / 0 Регистрация: 05.10.2020 Сообщений: 23 |
||||
1 |
||||
30.03.2021, 23:17. Показов 11051. Ответов 7 Метки lua (Все метки)
Скрипт работает стабильно. Но через какое либо время вылетает с такой ошибкой: attempt to index global ‘file’ (a nil value) Я ещё понимаю он сразу вылетал, но он примерно 1-2 минуты работает нормально а потом вылет. Подскажите как исправить.
__________________
0 |
944 / 1520 / 168 Регистрация: 07.05.2013 Сообщений: 3,324 Записей в блоге: 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 |
944 / 1520 / 168 Регистрация: 07.05.2013 Сообщений: 3,324 Записей в блоге: 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 4736 / 2992 / 462 Регистрация: 01.06.2013 Сообщений: 6,296 Записей в блоге: 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 4736 / 2992 / 462 Регистрация: 01.06.2013 Сообщений: 6,296 Записей в блоге: 9 |
||||
31.03.2021, 21:46 |
8 |
|||
Сообщение было отмечено frilovsky как решение Решение
Используя ваш код, я переделал под себя Зачем же, когда возникает ошибка, снова пытаться открывать файл. Посмотрите что у меня после if ferr ~= nil then, и что у вас. Добавлено через 57 секунд Добавлено через 1 минуту
0 |
On 12/6/2018 at 3:35 AM, Wolf_EX said:
If i had to take a shot in the dark my guess would be something from LeftClickPicker and SetTigerActions functions in the aikawa.lua.
I think one of your errors is coming from componentactions.lua executing EntityScript:CollectActions which gets called from playeractionpicker.lua
I never messed with playeractionpicker before but my guess is that it shouldn’t be ran on the client and is for some reason?
@Wolf_EX
I really appreciate it !! Thank you very much for your time !!
Okay I’ll try to looks at the componentactions.lua !!
hmmmm… okay.. I have… try to take a look and try to understand at those first error line…
[string "scripts/componentactions.lua"]:1182: attempt to index a nil value LUA ERROR stack traceback: scripts/componentactions.lua:1182 in (method) CollectActions (Lua) <1168-1194>
line : 1182 <1168 -1194 > in componentactions.lua
Spoiler
at this line why it has stopped at the » End, » before close if function ? : o
Maybe ,Dose that mean … I need to adds
those actions …
to my custom SG .. ?
Or create /add function to my *modmain : o ?
*( I just added TheSim:GetGameID to link the actions to the game in modmain.lua but I didn’t test it with anyone yet. :’D )
———————————————————————
here is my files if you want to see :
SGweretiger.lua
modmain.lua
This file is my custom Sg use in Second Form of this Character.
Like Woodie is werebeaver form but , I modified to base on Creatures ‘s stagegraphs. ( not on werebeaver is stategraphs.)
================================================================================
ok let’s move on !
Now I tried to looks at those 3 line :
Spoiler
scripts/components/playeractionpicker.lua:97 in (method) GetSceneActions (Lua) <94-119> scripts/components/playeractionpicker.lua:215 in (method) GetLeftClickActions (Lua) <176-234> scripts/components/playeractionpicker.lua:322 in (method) DoGetMouseActions (Lua) <284-326>
line : 97 < 94 — 119 > in playeractionpicker.lua
Spoiler
line : 215 < 176 — 234 > in playeractionpicker.lua
Spoiler
line : 322 < 284 — 326 > in playeractionpicker.lua
Spoiler
As I understand …
If I Change the * LeftClickPicker and SetTigerActions to something else ?
or
** removing it?? maybe it can be fixed ?
*( unfortunately I’ve tried this .. and have same error. :/ )
**( also.. I’ve tried this one too and my char can’t do anything in another form can move around only , BTW
It has a this old error that idk how to fixed it it’s call.. : actions are out of sync :») )
Or If i try to add («inspectable») components ,
And create new function and link to Inspectable Components
maybe.. it might be work :’) ?
here is my prefeb file : aikawa.lua
==============================================================================
Or maybe I just can’t really understand what it going to tell me X»D
If that’s true… If you don’t mind, could you help me understanding it more please?
< I’m very sorry about my dumby chicken brain X»D >
PS: And Thank you very much for your suggestion!! <<<333
SGweretiger.lua
Edited December 7, 2018 by Yagenius
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,