M
M
Macgluk2015-05-25 15:58:40
Lua
Macgluk, 2015-05-25 15:58:40

Lua: attempt to index nil value or problems with tables?

Good day.
I've been struggling with a small piece of code for quite some time now. After studying all sorts of ways to implement OOP in lua, I decided to try to make it on my own. And, in fact, everything works, but not the way I would like.
Here we lay out the objects on some kind of map, while each object is created for each cell and is individual.

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

Here is the creation process itself.
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

The objects themselves, whose, roughly speaking, templates are used in mass creation.
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
    }

Basically, I can't figure out what I'm doing wrong. I tried various options, tried to rewrite, but in the end nil and that's it. It's as if the NEW() function doesn't get any tables at all. It may well be that the cant is in some trifle. It happens to me so often.
Please explain where the error is and, preferably, why this is happening? And then I sit for an hour and try to understand what the essence is. Already already brains boiled.
I apologize if there have been similar questions. Searched but didn't find anything.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim Misbakh-Soloviev, 2016-07-28
@mva

For starters, try declaring o in NEW locally instead of globally.
Well, to be honest, there is not enough code for testing :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question