POO tables in Lua!

Asked

Viewed 729 times

4

I wonder why it is 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.

2 answers

4


Values are not returned because you are trying to concatenate an object table with a string using the operator .., to print 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

See 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

See demonstração

  • strange thought that POO in LUA would be possible to return a table without using pairs or ipairs... in the case POO only serves to make changes in variables within the function... anyway, thanks! + 1

0

The problem ai is that you try to concatenate a string with a table, and that defining the metamethod that is going to be called is the first operator. Fortunately for the case of strings, it has how to make 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})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.