2017-04-13 81 views
1

我創造我的地圖模塊稱爲映射的LUA表對象,這個函數創建一個新的實例:爲什麼我的lua表格對象是空的?

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

,並在我的島模塊,我把這段代碼中的第幾行:

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

,當我打印中心,角落和表的數量,他們都站出來爲0

我有單獨的模塊角:新的(),中心:新的(),與邊緣:新的( )

爲什麼中心,角點和邊緣的長度輸出爲0?

編輯:

這是我輸入到中心表例如(四角和邊緣是相似的)

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 

大小始終是一個完美的正方形

+1

'map:new()'返回一個帶有「轉角」鍵的表格,指向空表格。爲什麼你會期望尺寸與零不同? – GoojajiGreg

+0

在檢查「Island.corners」中的元素數量之前,你正在做'table.insert(Island.corners,Corner:new())'嗎? – GoojajiGreg

+0

@GoojajiGreg再次檢查,我明白你的意思,所以我深入一點。對不起,混淆 – Denfeet

回答

1

這似乎是一個變量範圍的問題。首先,實例化一個新的Map,返回的o應該是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 

當你傳遞一個指針表Map:generateCenters(),沒有必要返回指針。該中心已被添加到該表:

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 

最後,你會怎麼做:

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

你是在說,「把中心到表由對應於鍵的表值指出,在名爲island的表中稱爲centers「。

最後,注意

local t = island.centers 
print(#t) 

意願依然不輸出元素表中的centers數量,因爲有差距鍵(即他們不去{0,1,2,3,4, ..}而是任何字符串pointToKey()函數返回)。要計算centers中的元素,您可以執行以下操作:

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

'o'是本地的,因爲它是一個參數。 – lhf

+0

@lhf哦,當然。感謝您指出了這一點。從「在Lua中編程」ch。 15:「參數與局部變量完全一樣,用函數調用中給出的實際參數初始化,你可以調用一個參數個數與參數個數不同的函數,Lua將參數個數調整爲參數個數,就像它在多個任務中所做的那樣:額外的參數被拋棄;額外的參數被取消爲零。「 – GoojajiGreg