Taner Seytgaziyev
Taner Seytgaziyev

Reputation: 93

Why is my lua table object empty?

I create a lua table object called Map in my Map module, and this function creates a new instance:

function Map:new (o)
    o = o or {
    centers = {},
    corners = {},
    edges = {}
   }
    setmetatable(o, self)
    self.__index = self
    return o
end

and in my island module I put in this code in the first few lines:

local map = require (*map module location*)
Island = map:new ()

and when I print the number of centers, corners, and tables, they all come out to 0.

I have separate modules for Corner:new (), Center:new (), and Edge:new ()

Why does the length of centers, corners, and edges output as 0?

Edit:

This is what I input into the centers table for example(corners and edges is similar)

function pointToKey(point)
    return point.x.."_"..point.y    
end

function Map:generateCenters(centers)
    local N = math.sqrt(self.SIZE)
    for xx = 1, N do
        for yy = 1, N do
            local cntr = Center:new()
            cntr.point = {x = 0.5+xx - 1, y = 0.5+yy - 1}
            centers[pointToKey(cntr.point)] = cntr
        end
    end
    return centers
end

The size is always a perfect square

Upvotes: 1

Views: 1155

Answers (1)

GoojajiGreg
GoojajiGreg

Reputation: 1183

This seems to be a problem with variable scope. Firstly, in instantiating a new Map, the o that is returned should be local:

function Map:new (o)
    local o = o or { -- this should be local
        centers = {},
        corners = {},
        edges = {}
    }
    setmetatable(o, self)
    self.__index = self
    return o
end

When you pass a pointer to a table to Map:generateCenters(), there is no need to return that pointer. The centers have been added to that table:

function Map:generateCenters(centers)
    local N = math.sqrt(self.SIZE)
    for xx = 1, N do
        for yy = 1, N do
            local cntr = Center:new()
            cntr.point = {x = 0.5+xx - 1, y = 0.5+yy - 1}
            centers[pointToKey(cntr.point)] = cntr    -- HERE you're adding to the table passed as an argument
        end
    end
    -- return centers --> NO NEED TO RETURN THIS
end

Lastly, you would do:

local map = require( "map" )
local island = map:new()
map:generateCenters( island.centers )

You are saying, "Put the centers into the table pointed to by the table value corresponding to the key called centers in the table called island".

Lastly, note that

local t = island.centers
print( #t )

will still not output the number of elements in the table centers because there are gaps keys (i.e. they don't go {0,1,2,3,4,..} but rather whatever string the pointToKey() function returns ). To count the elements in centers, you could do:

local count = 0
for k,v in pairs( island.centers ) do
    count = count + 1
end
print( count )

Upvotes: 1

Related Questions