0

I have a working defined metatable (see below), but I cannot make it behave like I would like it to. When I feed a set of values to ht.array (see below) it works fine. When I try to give it a table, it doesn't work obviously since it expects a range of values and not a nested table. But, even if I modify ht.array to get rid of the nested table (like a = a[1]) it does not work. Any ideas? Would be greatly appreciated! In summary what I'm aiming for is v1 = ht.array{{1,2,3}}, where it would work when I do v1 + v1.

ht = {}
local mt = {}

function ht.array (a)
    array = {} 
    setmetatable(array, mt)
    for k, v in ipairs(a) do
        array[k] = v
    end
    return array
end

function ht.add (a, b) 
    local res = ht.array{}
    for k in pairs(a) do res[k] = a[k] + b[k] end
    return res
end

mt.__add = ht.add

-- This works
v1 = ht.array{4,5,6}
v2 = ht.array{3,45,90}

c = v1 + v2

for k, v in ipairs(c) do
    print(v)
end

-- But this does not work
a = {3,4,5}
b = {9,1,11}
v1 = ht.array{a}
v2 = ht.array{b}

c = v1 + v2

for k, v in ipairs(c) do
    print(v)
end
1
  • do local array = { } in your ht.array function. Commented Apr 6, 2011 at 3:37

1 Answer 1

1

First, why not just do this?

v1 = ht.array(a)
v2 = ht.array(b)

This way you are calling the "array" function (weird name by the way) with tables rather than single-element tables containing another table. But if you do want it to support single-element tables containing another table, you could add this quick hack to the top of ht.array:

if type(a[1]) == 'table' then
    a = a[1]
end
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.