POO Tables on Moon!

4

I would like to know why you are not returning a table in the code I made:

TP = {} 
function TP:new(pos, newpos, effect) 
    return setmetatable({pos = pos, newpos = newpos, effect = effect}, { __index = self }) 
end 
function TP:setNewPos(position)
    self.newpos = position 
end 
function TP:setEffect(efeito) 
    self.effect = efeito 
end

var = TP:new({x = 160, y = 54, z = 7}, {x = 180, y = 60, z = 7}, 10) 
print("is "..var.newpos) -- era para retornar uma tabela.
    
asked by anonymous 30.05.2015 / 18:51

2 answers

4

Values are not returned because you are attempting to concatenate a table object with a string using operator .. , to print the table values, do:

var = TP:new({x = 160, y = 54, z = 7}, {x = 180, y = 60, z = 7}, 10) 

print ("is")
for chave, valor in pairs(var.newpos) do
  print (chave, valor)
end

View demonstração

Alternatively you can create a function and return the table:

function TP:getNewPos()
    return self.newpos 
end

To use it, do so:

var = TP:new({x = 160, y = 54, z = 7}, {x = 180, y = 60, z = 7}, 10) 
newpos = var:getNewPos()

print ("is")
for chave, valor in pairs(newpos) do
    print (chave, valor)
end

View demonstração

    
30.05.2015 / 20:55
0

The problem here is that you are trying to concatenate a string with a table, and that defines the metamethod to be called is the first operator. Fortunately for the case of strings, you can do an implementation in these metamethods that will work for what you intended there.

-- captura a metatable de string
local mt = getmetatable("")

-- faz override no metametodo __concat
mt.__concat = function(a, b) 
  if type(a) == "string" and type(b) == "table" then
    local at = {}
    for k, v in pairs(b) do 
      table.insert(at, k .. " = " .. v)
    end

    return a .. " {" .. table.concat(at, ", ") .. "}"  
  end

  return a .. b
end

-- com o metametodo sobreposto 
-- agora quando chamar o operador .. que é o operador de concatenação
-- a sua função costomizada será chamada no lugar da padrão
print("is:" .. {x=2, y = 2, z = 3})
    
02.04.2017 / 03:49